Modern Apps git

← Modern-Apps.git

maps: mask tapped place labels by their baked boundary id

Commit
929113278fa2a5d6d196207ab609959c9bd24141
Author
vayun-mathur <[email protected]>
When
2026-09-22 02:57 UTC (2 months ago)
Parents
a30c004

Diff

library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex e4f31841a6..6d91b7f961 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -352,24 +352,18 @@ internal object MapNative {     external fun clearRailLines(handle: Long)      /**-     * Dim everything outside the region containing [lon]/[lat], and return which region-     * that is.-     *-     * Takes a point rather than a region id because nothing in the archive links a place to-     * its outline: a city is a `places` node with its own OSM id, while its boundary is a-     * `boundaries` relation, and OSM does not oblige the node to belong to the relation.-     * Containment is the link.-     *-     * [levelMin]/[levelMax] bound the OSM `admin_level` band the selection means, inclusive.-     * They are required because containment alone is ambiguous: every label sits inside a-     * whole stack of regions, so without a level a tap on a state resolves to whichever-     * county its label happens to sit in.-     *-     * Returns the region's OSM relation id, or 0 when no resident tile covers the point.-     * Callers can tell "there is no region here" from "the tiles have not landed yet" only by-     * retrying, which is why the id comes back rather than nothing.+     * Dim everything outside the region with id [regionId], and return whether it resolved.+     *+     * The id is the tagged OSM relation id of the admin boundary, baked onto the tapped+     * place label at build time (the tile's `region_links` table) — so the label names its+     * own outline directly and there is no point/level guess. `0` clears the mask and+     * returns 1 (resolved: there is nothing to wait for).+     *+     * Returns 1 when the mask is set (or intentionally cleared for a zero id) **and** a+     * resident tile actually carries that region, 0 when the region's tiles are not loaded+     * yet so the host retries next frame.      */-    external fun setRegionMask(handle: Long, lon: Float, lat: Float, levelMin: Int, levelMax: Int): Long+    external fun setRegionMask(handle: Long, regionId: Long): Long      /** Take the region mask away: the details sheet closed, or the selection moved on. */     external fun clearRegionMask(handle: Long)
library/map/src/main/java/com/vayunmathur/library/map/Projection.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt b/library/map/src/main/java/com/vayunmathur/library/map/Projection.ktindex 094cabfc1b..91fa785c06 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt@@ -38,6 +38,12 @@ data class PlacedLabel(      * the remaining bits.      */     val featureId: Long = 0L,+    /**+     * The tagged OSM relation id of the admin boundary this label names, baked at build+     * time into the tile's `region_links` table, or `0` (`REGION_NONE`) when linked to+     * nothing. The 7th field of the native pick row; legacy 6-field rows parse as `0`.+     */+    val regionId: Long = 0L, )  /**
library/map/src/main/java/com/vayunmathur/library/map/RegionLevel.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/RegionLevel.kt b/library/map/src/main/java/com/vayunmathur/library/map/RegionLevel.ktindex 38e068ed07..ffaa8a5aa7 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/RegionLevel.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/RegionLevel.kt@@ -1,18 +1,21 @@ package com.vayunmathur.library.map  /**- * Which rung of the administrative stack a region mask means.+ * Which rung of the administrative stack a region mask meant.  *- * A mask is asked for by point, because nothing in the archive links a place label to its- * outline. But a point is contained by every region above it at once — a city sits inside a- * county inside a state inside a country — so the point alone cannot say which outline was- * meant. Asking for the smallest was the first attempt and it always answers with the deepest- * rung: tapping a state selects whichever county its label happens to sit in.+ * @deprecated The mask is now the label's baked `regionId` passed straight through+ *   (`Long?` from `regionMaskFor` to `setRegionMask`): the tile's `region_links` table links+ *   each place label to its outline at build time, so no point/level guess is needed.+ *   Kept until the follow-up removes it; nothing references it anymore.  *- * The bands are OSM `admin_level` values, and match the names the tiler's boundary schema- * gives them (`kind_for`): 1-2 country, 3-4 region, 5-6 county, 7+ locality. Counties have no- * rung of their own because nothing in the app selects one.+ * A mask used to be asked for by point, because nothing in the archive linked a place label+ * to its outline. But a point is contained by every region above it at once — a city sits+ * inside a county inside a state inside a country — so the point alone could not say which+ * outline was meant, and the level band disambiguated. The bands were OSM `admin_level`+ * values, matching the names the tiler's boundary schema gives them (`kind_for`): 1-2+ * country, 3-4 region, 5-6 county, 7+ locality.  */+@Deprecated("Baked-id path: pass the label's regionId (Long?) straight through instead.") enum class RegionLevel(val min: Int, val max: Int) {     /** A country. */     COUNTRY(1, 2),@@ -32,8 +35,9 @@ enum class RegionLevel(val min: Int, val max: Int) { /**  * A request to dim everything outside one administrative region.  *- * [position] is a point inside the region — a label's anchor or a search result — and [level]- * says which rung of the stack containing that point was meant. Both travel together because- * neither identifies a region on its own.+ * @deprecated The mask is now a baked `regionId` (`Long?`): `[position]` + `[level]` travelled+ *   together because neither identified a region on its own, and the id does. Kept until the+ *   follow-up removes it; nothing references it anymore.  */+@Deprecated("Baked-id path: pass the label's regionId (Long?) straight through instead.") data class RegionMask(val position: GeoPoint, val level: RegionLevel)
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.ktindex 4b0f0f0df9..7090c85108 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapOverlays.kt@@ -150,32 +150,37 @@ internal fun SurfaceMapRenderer.tapMarkerAt(xDp: Float, yDp: Float): Long { }  /**- * Task-17 pick: placed labels intersecting [box] (Dp), restricted to- * [layerIds] (our flat ids), in placement order. Parses the native- * `\u0001`-joined rows; empty when the renderer isn't up or nothing hits.+ * One native pick row as a [PlacedLabel], or null when the row is malformed.+ *+ * Rows are 7 fields (`layerId/name/kind/lon/lat/featureId/regionId`, see+ * `bridge/pick.rs`); legacy 6-field rows parse with `regionId = 0`. Pure so the+ * contract is a JVM unit test rather than a screenshot.  */+internal fun parseLabelRow(parts: List<String>): PlacedLabel? {+    if (parts.size != 6 && parts.size != 7) return null+    return PlacedLabel(+        layerId = parts[0],+        name = parts[1],+        kind = parts[2],+        position = GeoPoint(+            longitude = parts[3].toDoubleOrNull() ?: 0.0,+            latitude = parts[4].toDoubleOrNull() ?: 0.0,+        ),+        // Unsigned on the native side; ids never come close to the sign bit+        // (an OSM id shifted left two is ~36 bits), so a Long is roomy.+        featureId = parts[5].toLongOrNull() ?: 0L,+        regionId = parts.getOrNull(6)?.toLongOrNull() ?: 0L,+    )+} internal fun SurfaceMapRenderer.tapLabelsIn(box: DpRect, layerIds: Set<String>): List<PlacedLabel> {     val h = handle     if (h == 0L) return emptyList()     return try {         MapNative.pickLabels(h, box.left.value, box.top.value, box.right.value, box.bottom.value)             .asSequence()-            .map { row -> row.split('\u0001') }-            .filter { parts -> parts.size == 6 && (layerIds.isEmpty() || parts[0] in layerIds) }-            .map { parts ->-                PlacedLabel(-                    layerId = parts[0],-                    name = parts[1],-                    kind = parts[2],-                    position = GeoPoint(-                        longitude = parts[3].toDoubleOrNull() ?: 0.0,-                        latitude = parts[4].toDoubleOrNull() ?: 0.0,-                    ),-                    // Unsigned on the native side; ids never come close to the sign bit-                    // (an OSM id shifted left two is ~36 bits), so a Long is roomy.-                    featureId = parts[5].toLongOrNull() ?: 0L,-                )-            }+            .map { row -> parseLabelRow(row.split('')) }+            .filter { label -> label != null && (layerIds.isEmpty() || label.layerId in layerIds) }+            .map { label -> label!! }             .toList()     } catch (_: Throwable) {         emptyList()
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 7d12744e39..2a54a71e0b 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -295,15 +295,15 @@ class SurfaceMapRenderer(         invalidate()     } -    /** The region to mask and which rung of the admin stack it is, or `null` for no mask. */-    private var regionProbe: RegionMask? = null+    /** The baked `regionId` to mask, or `null` for no mask. */+    private var selectedRegionId: Long? = null      /**-     * Whether [regionProbe] has been matched to a region yet.+     * Whether [selectedRegionId] has been matched to resident tiles yet.      *      * The match needs the region's tiles to be resident, and a selection usually arrives before      * they are - tapping a city label recentres the map, so the tiles under the new camera are-     * still in flight. So an unresolved probe is retried each frame until it lands rather than+     * still in flight. So an unresolved id is retried each frame until it lands rather than      * being dropped, which is the difference between the mask appearing and the mask silently      * never appearing.      */@@ -696,8 +696,8 @@ class SurfaceMapRenderer(     internal fun pickAt(xDp: Float, yDp: Float): Long = tapMarkerAt(xDp, yDp)      /** Dim everything outside the region [mask] names, or clear the mask with `null`. */-    fun setRegionMask(mask: RegionMask?) {-        this.regionProbe = mask+    fun setRegionMask(mask: Long?) {+        this.selectedRegionId = mask         this.regionResolved = false         applyRegionMask()         invalidate()@@ -713,20 +713,15 @@ class SurfaceMapRenderer(      private fun applyRegionMask() {         if (handle == 0L) return-        val probe = regionProbe-        if (probe == null) {+        val id = selectedRegionId+        if (id == null || id == 0L) {             MapNative.clearRegionMask(handle)             regionResolved = true             return         }-        val id = MapNative.setRegionMask(-            handle,-            probe.position.longitude.toFloat(),-            probe.position.latitude.toFloat(),-            probe.level.min,-            probe.level.max,-        )-        regionResolved = id != 0L+        // `0` clears above; a nonzero id returns nonzero once a resident tile carries it.+        // `0` back means the tiles have not landed yet — retried next frame, not a miss.+        regionResolved = MapNative.setRegionMask(handle, id) != 0L     }      private fun applyUserPuck() {
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 63f49a0425..53f2c22e18 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -68,7 +68,8 @@ import kotlin.math.roundToInt  *   glued to the ground while the map moves. Defaults to drawing nothing; see [UserPuck]  *   for why this is not a [MapMarker].  * @param regionMask dims everything outside the administrative region it names, for showing- *   which city or country a details sheet is about. Drawn inside the renderer's frame for the+ *   which city or country a details sheet is about. The baked `regionId` of the selected+ *   label (`null`/`0` draws no mask). Drawn inside the renderer's frame for the  *   same reason as [userPuck]: an overlay composed on top would lag the map by a frame while  *   panning. `null` draws no mask.  * @param trafficColors the live-traffic overlay's `component_id → ARGB` table. The baked@@ -121,7 +122,7 @@ fun VectorMap(     options: MapOptions = MapOptions(),     imageOverlay: ImageOverlay? = null,     userPuck: UserPuck? = null,-    regionMask: RegionMask? = null,+    regionMask: Long? = null,     trafficColors: TrafficColorTable? = null,     route: RouteOverlay? = null,     /**
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex c519ed220a..9a200955f5 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -55,8 +55,8 @@ internal fun VulkanMapSurface(     layerOptions: LayerOptions = LayerOptions(),     tileSource: TileSource = TileSource.Server,     userPuck: UserPuck? = null,-    /** Dim everything outside the administrative region this names. `null` draws no mask. */-    regionMask: RegionMask? = null,+    /** The baked `regionId` of the selected label. `null` draws no mask. */+    regionMask: Long? = null,     /**      * Mirror of `VectorMap`'s `globeEnabled`: pushed into the native frame as the      * per-frame `globe` flag (see `MapNative.render`), so the renderer draws the
library/map/src/main/rust/src/bridge/pick.rs
diff --git a/library/map/src/main/rust/src/bridge/pick.rs b/library/map/src/main/rust/src/bridge/pick.rsindex c209503cce..9499a54518 100644--- a/library/map/src/main/rust/src/bridge/pick.rs+++ b/library/map/src/main/rust/src/bridge/pick.rs@@ -6,14 +6,15 @@ use jni::objects::{JClass, JObject}; use jni::sys::{jfloat, jlong}; use jni::JNIEnv; /// Task-17 pick: placed labels intersecting the query box (Dp from the-/// viewport top-left). Returns `\u{1}`-joined `layerId/name/kind/lon/lat/featureId`+/// viewport top-left). Returns `\u{1}`-joined `layerId/name/kind/lon/lat/featureId/regionId` /// strings in placement order (topmost first); empty when nothing hits. Dp→device-px via the /// last frame's density, remembered on the map handle (same density the /// boxes were built with — boxes are device px, the query arrives in Dp). /// /// `kind` is the feature's own kind, not its layer's first one, so a `poi-food` hit says /// `cafe` rather than `restaurant`. `featureId` is the archive's stable id, or `0` for a-/// feature that has none.+/// feature that has none. `regionId` is the tagged relation id of the boundary the label+/// names from the tile's `region_links` table, or `0` (`REGION_NONE`) when linked to nothing. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_pickLabels<'l>(     mut env: JNIEnv<'l>,
library/map/src/test/java/com/vayunmathur/library/map/LabelRowParseTest.kt
diff --git a/library/map/src/test/java/com/vayunmathur/library/map/LabelRowParseTest.kt b/library/map/src/test/java/com/vayunmathur/library/map/LabelRowParseTest.ktnew file mode 100644index 0000000000..1e0ba088c7--- /dev/null+++ b/library/map/src/test/java/com/vayunmathur/library/map/LabelRowParseTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.library.map++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++/**+ * The native pick row contract (`bridge/pick.rs` emission vs [parseLabelRow]).+ *+ * Rows are `\u0001`-joined `layerId/name/kind/lon/lat/featureId/regionId`; legacy rows+ * carry 6 fields and parse with `regionId = 0`. Before the 7-field parse existed, the+ * `parts.size == 6` filter dropped every hit and taps selected nothing — silently, because+ * the empty list is also the legitimate "no hit" answer. These pin the sizes so a format+ * drift fails here rather than on device.+ */+class LabelRowParseTest {++    private fun row(vararg parts: String) = parts.toList()++    @Test+    fun seven_parts_parse_with_the_region_id_set() {+        val label = parseLabelRow(row("places-locality", "Paris", "locality", "2.35", "48.85", "1234", "777"))+            ?: error("expected a label")+        assertEquals("places-locality", label.layerId)+        assertEquals("Paris", label.name)+        assertEquals("locality", label.kind)+        assertEquals(2.35, label.position.longitude)+        assertEquals(48.85, label.position.latitude)+        assertEquals(1234L, label.featureId)+        assertEquals(777L, label.regionId)+    }++    @Test+    fun six_parts_parse_as_legacy_with_region_id_zero() {+        val label = parseLabelRow(row("places-locality", "Paris", "locality", "2.35", "48.85", "1234"))+            ?: error("expected a label")+        assertEquals(1234L, label.featureId)+        assertEquals(0L, label.regionId, "legacy rows link to nothing")+    }++    @Test+    fun wrong_sizes_are_dropped() {+        assertNull(parseLabelRow(row("places-locality", "Paris", "locality", "2.35", "48.85")))+        assertNull(parseLabelRow(row("places-locality", "Paris", "locality", "2.35", "48.85", "1", "2", "3")))+        assertNull(parseLabelRow(emptyList()))+    }++    @Test+    fun unparseable_numbers_fall_back_to_zero() {+        val label = assertNotNull(+            parseLabelRow(row("places-locality", "Paris", "locality", "oops", "oops", "oops", "oops")),+        )+        assertEquals(0.0, label.position.longitude)+        assertEquals(0.0, label.position.latitude)+        assertEquals(0L, label.featureId)+        assertEquals(0L, label.regionId)+    }+}
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktindex aef96b5724..585da71aba 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -21,24 +21,31 @@ sealed interface SpecificFeature {      * A country. [iso] and [wikipedia] are optional because the basemap archive carries neither:      * a picked label supplies a name and a position, and the Wikidata round trip that fills these      * in needs the network. Requiring them meant tapping a country did nothing at all offline.+     *+     * [regionId] is the baked link: the tagged OSM relation id of the boundary this label+     * names, stamped at build time (see `region_links`). `0` means unlinked — mask nothing.      */     @Serializable     data class Admin0Label(@SerialName("iso3166_1") val iso: String? = null, val wikipedia: String? = null, val name: String,-                           @Serializable(with = GeoPointAsCoordinates::class) val position: GeoPoint? = null) : SpecificFeature-    /** A state or region. [iso] and [wikipedia] are optional for the same reason as [Admin0Label]. */+                           @Serializable(with = GeoPointAsCoordinates::class) val position: GeoPoint? = null, val regionId: Long = 0L) : SpecificFeature+    /**+     * A state or region. [iso] and [wikipedia] are optional for the same reason as [Admin0Label].+     * [regionId] is the baked link, as in [Admin0Label].+     */     @Serializable     data class Admin1Label(@SerialName("iso3166_2") val iso: String? = null, val wikipedia: String? = null, val name: String,-                           @Serializable(with = GeoPointAsCoordinates::class) val position: GeoPoint? = null) : SpecificFeature+                           @Serializable(with = GeoPointAsCoordinates::class) val position: GeoPoint? = null, val regionId: Long = 0L) : SpecificFeature     /**      * A city / town. Unlike the country and region labels there is no ISO code to      * key on — the baked `admin_city` layer carries only `name` / `name_en` — so      * the border highlight matches on the name instead.      *      * [wikipedia] is optional for the same reason as [Admin0Label].+     * [regionId] is the baked link, as in [Admin0Label].      */     @Serializable     data class Admin2Label(val wikipedia: String? = null, val name: String,-                           @Serializable(with = GeoPointAsCoordinates::class) val position: GeoPoint? = null) : SpecificFeature+                           @Serializable(with = GeoPointAsCoordinates::class) val position: GeoPoint? = null, val regionId: Long = 0L) : SpecificFeature     @Serializable     data class Restaurant(override val name: String, val phone: String?, val website: String?, val menu: String?, val openingHours: OpeningHours?,                           @Serializable(with = GeoPointAsCoordinates::class) override val position: GeoPoint): RoutableFeature@@ -116,26 +123,31 @@ suspend fun parse(feature: Feature1): SpecificFeature? {     val wiki = properties.string("wikidata")?.let { id ->         try { Wikidata.get(id) } catch (_: Exception) { null }     }-    // Where the label sits, which is what the region mask probes with: the archive links a place-    // to its outline by containment and nothing else, so losing this loses the mask.+    // Where the label sits, kept for search-picked regions and as a fallback anchor: the+    // mask itself is the baked `regionId` below, not a containment probe.     val at = (feature.geometry as? Point)?.coordinates+    // The baked link: the tagged relation id of the boundary this label names, stamped at+    // build time (`region_links`). `0` is REGION_NONE — unlinked, mask nothing.+    val regionId = properties["regionId"]?.jsonPrimitive?.content?.toLongOrNull() ?: 0L     return when (properties.string("kind")) {         "country" -> SpecificFeature.Admin0Label(             iso = wiki?.getProperty("P297"),             wikipedia = wiki?.getWikipedia(),             name = name,             position = at,+            regionId = regionId,         )         "region" -> SpecificFeature.Admin1Label(             iso = wiki?.getProperty("P300"),             wikipedia = wiki?.getWikipedia(),             name = name,             position = at,+            regionId = regionId,         )         // No ISO lookup: a city has no ISO 3166 code, so the Wikidata round trip is only for the         // article URL.         "locality" ->-            SpecificFeature.Admin2Label(wikipedia = wiki?.getWikipedia(), name = name, position = at)+            SpecificFeature.Admin2Label(wikipedia = wiki?.getWikipedia(), name = name, position = at, regionId = regionId)         else -> null     } }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.ktindex aad540917f..5bd7b27cbc 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt@@ -151,8 +151,8 @@ class MapFeaturePicker(         /**          * The flat layer ids the native pick emits for the same labels          * (see `basemap.flat.json`: `places-country`, …). `places-subplace`-         * (neighbourhoods) has no `parse` branch and resolves to null, which-         * is the correct fall-through to reverse-geocode.+         * (neighbourhoods) converts with `locality` semantics so a linked+         * subplace can mask; unlinked (`regionId == 0`) it null-masks.          */         val NATIVE_LABEL_LAYER_IDS: Set<String> = setOf(             "places-country",@@ -166,14 +166,18 @@ class MapFeaturePicker(             "places-country" -> "places_country"             "places-region" -> "places_region"             "places-locality" -> "places_locality"+            "places-subplace" -> "places_locality"             else -> null         }          /**          * A native [PlacedLabel] as the [Feature1] [SpecificFeature.parse] reads:          * point geometry at [PlacedLabel.position] plus `{kind, name, name:en}`-         * properties. `kind` is the `country`/`region`/`locality` discriminator-         * `parse` switches on; only labels whose native id maps to a known admin+         * properties and the baked `regionId` the tile stamped on the label.+         * `kind` is the `country`/`region`/`locality` discriminator+         * `parse` switches on (a linked `places-subplace` arrives as `locality`+         * semantics so it can mask; unlinked it still null-masks);+         * only labels whose native id maps to a known admin          * base id convert, the rest return null and never enter the candidate list.          */         fun PlacedLabel.toFeature1(): Feature1? {@@ -182,9 +186,10 @@ class MapFeaturePicker(                 Point(position),                 JsonObject(                     mapOf(-                        "kind" to JsonPrimitive(kind),+                        "kind" to JsonPrimitive(if (layerId == "places-subplace") "locality" else kind),                         "name" to JsonPrimitive(name),                         "name:en" to JsonPrimitive(name),+                        "regionId" to JsonPrimitive(regionId),                     )                 ),             )
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.ktindex 14dc9bcce0..b944a61d23 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt@@ -258,34 +258,19 @@ internal suspend fun openVehicleTrip( }  /**- * The selected city/region's outline, dimmed outside. Derived from the sheet's own+ * The selected label's outline, dimmed outside. Derived from the sheet's own  * selection rather than the tap, so a region picked from search masks too — and the- * label's own kind supplies the admin level, because the point alone is inside every- * region above it and would otherwise resolve to the smallest, not the one named.+ * mask is the label's baked `regionId`, so no point/level guess: linked masks exactly+ * that region, unlinked (`0` / absent) masks nothing.  */ internal fun regionMaskFor(     selectedFeature: com.vayunmathur.maps.data.SpecificFeature?,-): com.vayunmathur.library.map.RegionMask? = when (selectedFeature) {+): Long? = when (selectedFeature) {     is com.vayunmathur.maps.data.SpecificFeature.Admin0Label ->-        selectedFeature.position?.let {-            com.vayunmathur.library.map.RegionMask(-                it,-                com.vayunmathur.library.map.RegionLevel.COUNTRY,-            )-        }+        selectedFeature.regionId.takeIf { it != 0L }     is com.vayunmathur.maps.data.SpecificFeature.Admin1Label ->-        selectedFeature.position?.let {-            com.vayunmathur.library.map.RegionMask(-                it,-                com.vayunmathur.library.map.RegionLevel.REGION,-            )-        }+        selectedFeature.regionId.takeIf { it != 0L }     is com.vayunmathur.maps.data.SpecificFeature.Admin2Label ->-        selectedFeature.position?.let {-            com.vayunmathur.library.map.RegionMask(-                it,-                com.vayunmathur.library.map.RegionLevel.LOCALITY,-            )-        }+        selectedFeature.regionId.takeIf { it != 0L }     else -> null }
maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.ktindex a1fb38d587..09fd0639f8 100644--- a/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt@@ -4,6 +4,7 @@ import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.dp import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.ui.FAMILY_LOCATION_LAYER_ID import com.vayunmathur.maps.ui.PARKING_PIN_LAYER_ID import com.vayunmathur.maps.ui.SAVED_PLACE_LAYER_ID@@ -191,7 +192,7 @@ class MapFeaturePickerTest {         )     } -    /** The adapter emits the {kind, name, name:en} properties `parse` reads. */+    /** The adapter emits the {kind, name, name:en, regionId} properties `parse` reads. */     @Test     fun `placed label converts to a parseable feature`() {         val feature = PlacedLabel(@@ -199,25 +200,66 @@ class MapFeaturePickerTest {             name = "France",             kind = "country",             position = GeoPoint(2.35, 48.85),+            regionId = 12345L,         ).toFeature1() ?: error("expected a feature")          val props = feature.properties ?: error("expected properties")         assertEquals("country", props["kind"]?.jsonPrimitive?.content)         assertEquals("France", props["name"]?.jsonPrimitive?.content)         assertEquals("France", props["name:en"]?.jsonPrimitive?.content)+        assertEquals("12345", props["regionId"]?.jsonPrimitive?.content)         val pos = (feature.geometry as? Point)?.coordinates ?: error("expected point")         assertEquals(2.35, pos.longitude)         assertEquals(48.85, pos.latitude)     } -    /** Unknown native layers (and subplace, which has no parse branch) convert to null. */+    /** A linked subplace converts with locality semantics so it can mask. */+    @Test+    fun `linked subplace converts as locality with its region id`() {+        val feature = PlacedLabel(+            layerId = "places-subplace",+            name = "SoHo",+            kind = "subplace",+            position = GeoPoint(-74.0, 40.7),+            regionId = 999L,+        ).toFeature1() ?: error("expected a feature")++        val props = feature.properties ?: error("expected properties")+        assertEquals("locality", props["kind"]?.jsonPrimitive?.content)+        assertEquals("999", props["regionId"]?.jsonPrimitive?.content)+    }++    /** Unknown native layers convert to null and never enter the candidate list. */     @Test     fun `unmapped native layers convert to null`() {         assertNull(             PlacedLabel("roads-bridges-major-casing", "x", "road", GeoPoint(0.0, 0.0)).toFeature1()         )+    }++    /** The mask is the label's baked id: nonzero passes through, zero/null clears. */+    @Test+    fun `region mask passes the baked id through`() {+        val paris = GeoPoint(2.35, 48.85)+        assertEquals(+            777L,+            regionMaskFor(SpecificFeature.Admin2Label(name = "Paris", position = paris, regionId = 777L)),+        )+        assertEquals(+            42L,+            regionMaskFor(SpecificFeature.Admin0Label(name = "France", position = paris, regionId = 42L)),+        )+        assertEquals(+            43L,+            regionMaskFor(SpecificFeature.Admin1Label(name = "Île-de-France", position = paris, regionId = 43L)),+        )+        // Unlinked (0) or positionless labels, and non-admin features, mask nothing.+        assertNull(+            regionMaskFor(SpecificFeature.Admin2Label(name = "Nowhere", position = paris, regionId = 0L)),+        )         assertNull(-            PlacedLabel("places-subplace", "SoHo", "subplace", GeoPoint(-74.0, 40.7)).toFeature1()+            regionMaskFor(SpecificFeature.Admin2Label(name = "Nowhere", position = null, regionId = 777L)),         )+        assertNull(regionMaskFor(null))     } }