Modern Apps git

← Modern-Apps.git

maps: make nav state snapshot-correct and the hit-test testable

Commit
d52daa8e0e340cb5248d54420967759a3b85177c
Author
vayun-mathur <[email protected]>
When
2026-08-21 16:49 UTC (3 months ago)
Parents
5567f04

Diff

maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt b/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.ktindex 738d8406e6..c19adf01be 100644--- a/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt+++ b/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt@@ -103,7 +103,7 @@ class NavMapScreen(carContext: CarContext) : Screen(carContext) {     // ----------------------------------------------------------------      private fun pushCameraAndOverlay(state: NavState) {-        renderer.setRoute(NavigationSessionManager.currentRoute?.polyline ?: emptyList())+        renderer.setRoute(NavigationSessionManager.session.value.route?.polyline ?: emptyList())         val progress = (state as? NavState.Navigating)?.progress         if (progress != null) {             renderer.setPuck(progress.snappedPosition)@@ -148,7 +148,7 @@ class NavMapScreen(carContext: CarContext) : Screen(carContext) {     }      private fun buildRoutingInfo(progress: NavigationProgress): RoutingInfo? {-        val steps = NavigationSessionManager.currentRoute?.step ?: return null+        val steps = NavigationSessionManager.session.value.route?.step ?: return null         val info = RoutingInfo.Builder()         // The maneuver the driver is approaching is the START of the next step;         // distanceToNextManeuver counts down to it (matches NavigationTts).@@ -164,7 +164,7 @@ class NavMapScreen(carContext: CarContext) : Screen(carContext) {             }         } else {             // On the final step: point at the destination.-            val destName = NavigationSessionManager.destinationName+            val destName = NavigationSessionManager.session.value.destinationName                 ?: carContext.getString(R.string.nav_default_destination)             val dest = Step.Builder(destName)                 .setManeuver(Maneuver.Builder(Maneuver.TYPE_DESTINATION).build())
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 436bd2bf3a..843cfc0ccd 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -72,6 +72,8 @@ import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.PoiIndex+import com.vayunmathur.maps.ui.map.MapFeaturePicker+import com.vayunmathur.maps.ui.map.MapHit import com.vayunmathur.maps.ui.theme.BasemapPalette import com.vayunmathur.maps.ui.theme.MapChromeMetrics import com.vayunmathur.maps.util.SelectedFeatureViewModel@@ -124,14 +126,14 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,      // Parking memory (P9): the single active parking spot (pin + recall).     val parkingSpot by parkingViewModel.active.collectAsState()-    var showParkingSheet by remember { mutableStateOf(false) }+    var showParkingSheet by retain { mutableStateOf(false) }      // Map-layer visibility toggles (P6 layers sheet, persisted via DataStore).     val trafficEnabled by settingsViewModel.trafficLayer.collectAsState()     val satelliteEnabled by settingsViewModel.satelliteLayer.collectAsState()     val safetyEnabled by settingsViewModel.safetyLayer.collectAsState()     val transitEnabled by settingsViewModel.transitLayer.collectAsState()-    var showLayersSheet by remember { mutableStateOf(false) }+    var showLayersSheet by retain { mutableStateOf(false) }      // Effective map palette (P14): resolve the P6 Map-theme setting against the     // OS dark mode using the same rule DynamicTheme applies (a null override =@@ -156,7 +158,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     // Active browse-category POI filter (P29): when set, the on-map `ma_pois`     // layer is filtered to this category's OSM types (see MaPoisLayer). null =     // no filter (all POIs shown). Toggled by the CategoryChips row below.-    var selectedCategory by remember { mutableStateOf<MapCategory?>(null) }+    var selectedCategory by retain { mutableStateOf<MapCategory?>(null) }      // TEST: default to San Francisco at z14 so the native ma_pois POIs are     // visible on cold start.@@ -213,15 +215,20 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,      // --- NAVIGATION SESSION ---     val navState by com.vayunmathur.maps.util.NavigationSessionManager.state.collectAsState()+    // Collected, not read off a field: a recalculation swaps the route mid-session, and reading+    // it as a plain property meant this screen kept drawing the OLD route's steps against the+    // new progress until something else happened to recompose.+    val navSession by com.vayunmathur.maps.util.NavigationSessionManager.session.collectAsState()     val isNavigating = navState !is com.vayunmathur.maps.util.NavigationSessionManager.NavState.Idle-    var autoFollow by remember { mutableStateOf(true) }+    var autoFollow by retain { mutableStateOf(true) }     // North-up vs heading-up during navigation (Vela onCompassTap idea).-    var navNorthUp by remember { mutableStateOf(false) }+    var navNorthUp by retain { mutableStateOf(false) }     // Posted speed limit under the puck (P5b maxspeed overlay; null when the-    // tileset is unhosted or the road has no limit).-    var postedLimit by remember { mutableStateOf<com.vayunmathur.maps.data.PostedLimit?>(null) }+    // tileset is unhosted or the road has no limit). Retained so a rotation does not blank+    // the sign until the next GPS fix arrives; it is re-queried on the following one.+    var postedLimit by retain { mutableStateOf<com.vayunmathur.maps.data.PostedLimit?>(null) }     var lastProgrammaticMoveMs by remember { mutableStateOf(0L) }-    val activeRoute = com.vayunmathur.maps.util.NavigationSessionManager.currentRoute+    val activeRoute = navSession.route     val navProgress = (navState as? com.vayunmathur.maps.util.NavigationSessionManager.NavState.Navigating)?.progress      // --- UI & BOTTOM SHEET STATE ---@@ -416,90 +423,41 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         onMapClick = { latLng, offset ->                             coroutineScope.launch {                                 val projection = camera.projection-                                // Give pin taps a tolerance box (~22dp radius)-                                // around the touch point so tapping NEAR a small-                                // POI glyph still selects it, instead of only-                                // registering on a pixel-exact hit.-                                val pad = MapChromeMetrics.hitSlop-                                val hitBox = DpRect(offset.x - pad, offset.y - pad, offset.x + pad, offset.y + pad)-                                // Parking pin (P9): tapping the saved car spot-                                // opens the parking sheet instead of selecting a-                                // place.-                                val parkingHit = projection?.queryRenderedFeatures(-                                    hitBox,-                                    setOf(PARKING_PIN_LAYER_ID)-                                )?.isNotEmpty() == true-                                if (parkingHit) {-                                    showParkingSheet = true-                                    return@launch-                                }+                                val picker = MapFeaturePicker(+                                    source = { box, layerIds ->+                                        projection?.queryRenderedFeatures(box, layerIds) ?: emptyList()+                                    },+                                    transitEnabled = transitEnabled,+                                ) -                                // Transit stop (P10): tapping a stop opens its-                                // live departure board instead of selecting a-                                // place. Only hit-tested while the layer is on.-                                if (transitEnabled) {-                                    val stopHit = projection?.queryRenderedFeatures(-                                        hitBox,-                                        setOf(TRANSIT_STOP_LAYER_ID)-                                    )?.firstNotNullOfOrNull { it.toTransitStop() }-                                    if (stopHit != null) {-                                        transitViewModel.openStop(stopHit)+                                when (val hit = picker.pickPin(offset)) {+                                    MapHit.Parking -> {+                                        showParkingSheet = true                                         return@launch                                     }-                                }--                                // Hit-test the search-result pins first, then the-                                // ambient offline POI pins — a POI tap selects the-                                // place (name + coord) as a GenericPlace so-                                // SelectedFeatureViewModel.currentPoiInfo fetches-                                // the Google rich details and GooglePoiEnrichment-                                // renders.-                                val pinHit = projection?.queryRenderedFeatures(-                                    hitBox,-                                    setOf(SEARCH_RESULT_LAYER_ID)-                                )?.firstNotNullOfOrNull { it.toSelectedSearchResult() }-                                    ?: projection?.queryRenderedFeatures(-                                        hitBox,-                                        setOf(SAVED_PLACE_LAYER_ID)-                                    )?.firstNotNullOfOrNull { it.toSelectedSavedPlace() }-                                    ?: projection?.queryRenderedFeatures(-                                        hitBox,-                                        setOf(FAMILY_LOCATION_LAYER_ID)-                                    )?.firstNotNullOfOrNull { it.toSelectedFamilyMember() }-                                    ?: projection?.queryRenderedFeatures(-                                        hitBox,-                                        setOf(MA_POIS_LAYER_ID)-                                    )?.firstNotNullOfOrNull { it.toSelectedMaPoi() }-                                if (pinHit != null) {-                                    viewModel.stashRouteSelection()-                                    viewModel.set(pinHit)-                                    sheetState.partialExpand()-                                    return@launch+                                    is MapHit.Stop -> {+                                        transitViewModel.openStop(hit.stop)+                                        return@launch+                                    }+                                    is MapHit.Place -> {+                                        viewModel.stashRouteSelection()+                                        viewModel.set(hit.feature)+                                        sheetState.partialExpand()+                                        return@launch+                                    }+                                    null -> Unit                                 }                                  // Otherwise fall back to basemap admin labels                                 // (country/region/city). Native POIs are suppressed                                 // and the amenity-DB enrichment path is gone.-                                val features = projection?.queryRenderedFeatures(-                                    offset,-                                    setOf("places_country", "places_region", "places_locality").flatMap {-                                        listOf("${it}_base", "${it}_hybrid")-                                    }.toSet()-                                ) ?: emptyList()-                                // parse() may do a Wikidata round-trip per-                                // feature; queryRenderedFeatures returns one-                                // Feature PER LAYER at the tap point, so stop at-                                // the first parseable hit instead of doing every-                                // round-trip serially in the foreground.-                                val firstFeature = withContext(Dispatchers.IO) {-                                    features.firstNotNullOfOrNull { raw ->-                                        runCatching { parse(raw) }.getOrNull()-                                    }-                                }--                                if (firstFeature != null) {+                                //+                                // Resolving a label may do a Wikidata round-trip, so it belongs+                                // to the ViewModel rather than to this gesture handler.+                                val labelFeature = viewModel.resolveAdminLabel(picker.pickAdminLabels(offset))+                                if (labelFeature != null) {                                     viewModel.stashRouteSelection()-                                    viewModel.set(firstFeature)+                                    viewModel.set(labelFeature)                                     sheetState.partialExpand()                                     return@launch                                 }@@ -694,7 +652,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                     postedLimit = postedLimit,                     northUp = navNorthUp,                     onToggleNorthUp = { navNorthUp = !navNorthUp },-                    destinationName = com.vayunmathur.maps.util.NavigationSessionManager.destinationName,+                    destinationName = navSession.destinationName,                     darkBasemap = darkMap,                 ) 
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.ktnew file mode 100644index 0000000000..a6b59941be--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapFeaturePicker.kt@@ -0,0 +1,141 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.DpRect+import androidx.compose.ui.unit.DpSize+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.ui.FAMILY_LOCATION_LAYER_ID+import com.vayunmathur.maps.ui.MA_POIS_LAYER_ID+import com.vayunmathur.maps.ui.PARKING_PIN_LAYER_ID+import com.vayunmathur.maps.ui.SAVED_PLACE_LAYER_ID+import com.vayunmathur.maps.ui.SEARCH_RESULT_LAYER_ID+import com.vayunmathur.maps.ui.TRANSIT_STOP_LAYER_ID+import com.vayunmathur.maps.ui.theme.MapChromeMetrics+import com.vayunmathur.maps.ui.toSelectedFamilyMember+import com.vayunmathur.maps.ui.toSelectedMaPoi+import com.vayunmathur.maps.ui.toSelectedSavedPlace+import com.vayunmathur.maps.ui.toSelectedSearchResult+import com.vayunmathur.maps.ui.toTransitStop++/**+ * What a tap on the map resolved to.+ *+ * A closed set, because the caller has to do something different for each and the compiler+ * should say so when a new one appears.+ */+sealed interface MapHit {+    /** The saved parking spot: opens the parking sheet rather than selecting a place. */+    data object Parking : MapHit++    /** A baked GTFS stop: opens its departure board. */+    data class Stop(val stop: TransitStop) : MapHit++    /** A pin or label that resolves to a selectable place. */+    data class Place(val feature: SpecificFeature) : MapHit+}++/**+ * Where features can be queried from. One method, so the picker can be tested without a+ * renderer — the whole reason this is a class and not a lambda inside a gesture handler.+ */+fun interface FeatureSource {+    fun query(box: DpRect, layerIds: Set<String>): List<Feature1>+}++/**+ * Resolves a tap to the topmost thing under it.+ *+ * Hit-testing is a **priority order**, not a set of conditions: a parking pin beats a transit+ * stop beats a search result, and so on down to the basemap's own labels. Expressed as an+ * ordered list of probes resolved by `firstNotNullOfOrNull`, so the order is a value that can+ * be read and asserted on rather than the shape of a hundred-line chain of `?:` and early+ * `return`s.+ *+ * Not a composable and not suspending. It does no I/O — the admin-label branch used to make a+ * Wikidata round-trip inside the gesture handler; that now belongs to the ViewModel, which is+ * why [adminLabelIds] hits are returned as raw features for the caller to resolve.+ */+class MapFeaturePicker(+    private val source: FeatureSource,+    /** Whether the transit layer is on. Stops are only probed when they are drawn. */+    private val transitEnabled: Boolean,+) {++    /**+     * One layer to probe, and how to turn a hit on it into a [MapHit].+     *+     * [enabled] rather than filtering the list at construction, so a disabled probe still+     * appears in [probes] and the order stays legible.+     */+    private class Probe(+        val layerId: String,+        val enabled: Boolean = true,+        val resolve: (List<Feature1>) -> MapHit?,+    )++    private val probes: List<Probe> = listOf(+        Probe(PARKING_PIN_LAYER_ID) { hits -> if (hits.isNotEmpty()) MapHit.Parking else null },+        Probe(TRANSIT_STOP_LAYER_ID, enabled = transitEnabled) { hits ->+            hits.firstNotNullOfOrNull { it.toTransitStop() }?.let { MapHit.Stop(it) }+        },+        Probe(SEARCH_RESULT_LAYER_ID) { hits ->+            hits.firstNotNullOfOrNull { it.toSelectedSearchResult() }?.let { MapHit.Place(it) }+        },+        Probe(SAVED_PLACE_LAYER_ID) { hits ->+            hits.firstNotNullOfOrNull { it.toSelectedSavedPlace() }?.let { MapHit.Place(it) }+        },+        Probe(FAMILY_LOCATION_LAYER_ID) { hits ->+            hits.firstNotNullOfOrNull { it.toSelectedFamilyMember() }?.let { MapHit.Place(it) }+        },+        Probe(MA_POIS_LAYER_ID) { hits ->+            hits.firstNotNullOfOrNull { it.toSelectedMaPoi() }?.let { MapHit.Place(it) }+        },+    )++    /** The layers probed, in priority order. Disabled ones are omitted. */+    val probeOrder: List<String> get() = probes.filter { it.enabled }.map { it.layerId }++    /**+     * The topmost pin under [offset], or null when the tap landed on no pin.+     *+     * Every probe uses the same tolerance box so a tap NEAR a small glyph still counts; see+     * [MapChromeMetrics.hitSlop].+     */+    fun pickPin(offset: DpOffset): MapHit? {+        val box = hitBox(offset)+        return probes.firstNotNullOfOrNull { probe ->+            if (!probe.enabled) null else probe.resolve(source.query(box, setOf(probe.layerId)))+        }+    }++    /**+     * The basemap's own place labels under [offset], returned unresolved.+     *+     * Queried at the exact point rather than through the tolerance box, matching the behaviour+     * this replaced. `queryRenderedFeatures` returns one feature per layer, so this is a+     * handful of candidates for the caller to resolve.+     */+    fun pickAdminLabels(offset: DpOffset): List<Feature1> =+        source.query(DpRect(offset, DpSize.Zero), ADMIN_LABEL_LAYER_IDS)++    private fun hitBox(offset: DpOffset): DpRect {+        val pad = MapChromeMetrics.hitSlop+        return DpRect(offset.x - pad, offset.y - pad, offset.x + pad, offset.y + pad)+    }++    companion object {+        /**+         * The basemap label layers probed for a "what's here?" tap.+         *+         * A `Set`, so this does not express a priority: the renderer decides what order it+         * returns them in, and the caller resolves the first that parses. `_base`/`_hybrid`+         * because the style patcher splits every layer in two by zoom.+         */+        val ADMIN_LABEL_LAYER_IDS: Set<String> =+            setOf("places_country", "places_region", "places_locality")+                .flatMap { listOf("${it}_base", "${it}_hybrid") }+                .toSet()+    }+}
maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.ktindex fb3edde0d3..f4950c6878 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt@@ -112,7 +112,7 @@ class NavigationService : Service() {     private fun handleState(state: NavigationSessionManager.NavState) {         when (state) {             is NavigationSessionManager.NavState.Navigating -> {-                val route = NavigationSessionManager.currentRoute+                val route = NavigationSessionManager.session.value.route                 if (route != null && voiceGuidanceEnabled()) {                     NavigationTts.onProgressUpdate(state.progress, route.step)                 }@@ -202,8 +202,8 @@ class NavigationService : Service() {             PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT         ) -        val mode = NavigationSessionManager.travelMode-        val destLabel = NavigationSessionManager.destinationName ?: getString(R.string.nav_default_destination)+        val mode = NavigationSessionManager.session.value.travelMode+        val destLabel = NavigationSessionManager.session.value.destinationName ?: getString(R.string.nav_default_destination)          val (title, content, progressPercent, smallIcon) = describe(state, mode, destLabel) @@ -267,7 +267,7 @@ class NavigationService : Service() {                 val percent = (p.fractionComplete * 100).roundToInt().coerceIn(0, 100)                 val distRemaining = formatDistance(p.distanceRemaining)                 val etaText = formatEta(p.etaEpochMs)-                val route = NavigationSessionManager.currentRoute+                val route = NavigationSessionManager.session.value.route                 val currentStep = route?.step?.getOrNull(p.currentStepIndex)                 when (mode) {                     TravelMode.DRIVE -> {
maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.ktindex c12308c125..c18161f2dd 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt@@ -74,17 +74,40 @@ object NavigationSessionManager {     private val _state: MutableStateFlow<NavState> = MutableStateFlow(NavState.Idle)     val state: StateFlow<NavState> = _state.asStateFlow() +    /**+     * What is being navigated, as opposed to how it is going.+     *+     * Deliberately a sibling of [NavState] rather than fields on its variants: route, mode and+     * destination are orthogonal to the state machine, so folding them in would make every+     * transition re-copy them — and a transition that forgets to is exactly the bug this fixes.+     *+     * A [StateFlow] because these were plain `@Volatile var`s read straight from composition,+     * which Compose cannot observe. A post-recalculation route swap therefore did not+     * recompose, and the UI kept drawing the OLD route's steps against the new progress.+     *+     * No Compose or lifecycle dependency, so the process-global lifetime this object+     * deliberately has is unchanged, and it stays safe to read from the background service.+     */+    data class NavSession(+        val route: RouteService.Route? = null,+        val travelMode: TravelMode? = null,+        val destinationName: String? = null,+    )++    private val _session = MutableStateFlow(NavSession())+    val session: StateFlow<NavSession> = _session.asStateFlow()+     /** Travel mode for the active session (or last session). Used by UI/notification. */-    @Volatile var travelMode: TravelMode? = null-        private set+    @Deprecated("Read session.value.travelMode, or collect session for a snapshot-correct read.")+    val travelMode: TravelMode? get() = _session.value.travelMode      /** Human-readable destination shown in the notification. */-    @Volatile var destinationName: String? = null-        private set+    @Deprecated("Read session.value.destinationName, or collect session.")+    val destinationName: String? get() = _session.value.destinationName      /** The active route (snapshot used by UI for step list / polyline split). */-    @Volatile var currentRoute: RouteService.Route? = null-        private set+    @Deprecated("Read session.value.route, or collect session.")+    val currentRoute: RouteService.Route? get() = _session.value.route      private val initialized = AtomicBoolean(false)     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)@@ -136,9 +159,9 @@ object NavigationSessionManager {             return         }         Log.i(TAG, "start(mode=$mode, label=$destinationLabel, steps=${route.step.size}, dist=${route.distanceMeters})")-        currentRoute = route-        travelMode = mode-        destinationName = destinationLabel+        // One emission, so an observer never sees a route from this session paired with a+        // destination from the last one.+        _session.value = NavSession(route = route, travelMode = mode, destinationName = destinationLabel)         this.destination = destination         polylineIndex = PolylineIndex(route)         lastSegmentIndex = 0@@ -161,9 +184,7 @@ object NavigationSessionManager {         // for stop-without-service-teardown paths.         NavigationTts.reset()         polylineIndex = null-        currentRoute = null-        travelMode = null-        destinationName = null+        _session.value = NavSession()         destination = null         lastSegmentIndex = 0         offRouteSinceMs = null@@ -299,7 +320,7 @@ object NavigationSessionManager {         // trip (tunnels, GPS drift inside a vehicle), and a recalc would         // replace the planned transit route with a walking route mid-trip.         val now = System.currentTimeMillis()-        if (travelMode != TravelMode.TRANSIT && snap.distanceOffRoute > OFF_ROUTE_THRESHOLD_M) {+        if (_session.value.travelMode != TravelMode.TRANSIT && snap.distanceOffRoute > OFF_ROUTE_THRESHOLD_M) {             val since = offRouteSinceMs ?: run {                 offRouteSinceMs = now                 now@@ -329,7 +350,7 @@ object NavigationSessionManager {      private fun triggerRecalculate(from: Position) {         val dest = destination ?: return-        val mode = travelMode ?: return+        val mode = _session.value.travelMode ?: return         Log.i(TAG, "off-route; recalculating from $from to $dest (attempt ${recalcAttempts + 1})")         _state.value = NavState.Recalculating         recalcAttempts++@@ -347,7 +368,7 @@ object NavigationSessionManager {                     position = from,                 )                 val toFeature = SpecificFeature.GenericPlace(-                    name = destinationName ?: "Destination",+                    name = _session.value.destinationName ?: "Destination",                     phone = null,                     website = null,                     openingHours = null,@@ -380,7 +401,7 @@ object NavigationSessionManager {             }              // Swap in the new polyline. Reset state for the new shape.-            currentRoute = newRoute+            _session.value = _session.value.copy(route = newRoute)             polylineIndex = PolylineIndex(newRoute)             lastSegmentIndex = 0             offRouteSinceMs = null
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex 61e65fee43..3fb3402d77 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -3,13 +3,16 @@ import android.app.Application import android.hardware.SensorManager import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.maps.data.Feature1 import com.vayunmathur.maps.data.SpecificFeature import com.vayunmathur.maps.data.google.GooglePoiDataSource import com.vayunmathur.maps.data.google.GooglePoiInfo import com.vayunmathur.maps.data.google.WebReviewsFetcher+import com.vayunmathur.maps.data.parse import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.*+import kotlinx.coroutines.withContext import org.maplibre.spatialk.geojson.Position  class SelectedFeatureViewModel(application: Application): AndroidViewModel(application) {@@ -101,6 +104,19 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli         (_selectedFeature.value as? SpecificFeature.Route)?.let { _inactiveNavigation.value = it }     } +    /**+     * Resolve the first basemap place label that parses, or null.+     *+     * Lives here rather than in the tap handler because `parse` may make a Wikidata round-trip+     * per candidate. `queryRenderedFeatures` returns one feature per layer, so stopping at the+     * first success is what keeps a tap from doing every round-trip serially — and doing any of+     * them on the caller's thread is what made the gesture handler a hundred lines long.+     */+    suspend fun resolveAdminLabel(candidates: List<Feature1>): SpecificFeature? =+        withContext(Dispatchers.IO) {+            candidates.firstNotNullOfOrNull { raw -> runCatching { parse(raw) }.getOrNull() }+        }+     /**      * Keyless Google Maps enrichment (rating, reviews, hours, photos, price,      * popular times, …) for the currently selected restaurant or generic place.
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.ktnew file mode 100644index 0000000000..355c1fedfe--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/MapFeaturePickerTest.kt@@ -0,0 +1,161 @@+package com.vayunmathur.maps.ui.map++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.ui.FAMILY_LOCATION_LAYER_ID+import com.vayunmathur.maps.ui.MA_POIS_LAYER_ID+import com.vayunmathur.maps.ui.PARKING_PIN_LAYER_ID+import com.vayunmathur.maps.ui.SAVED_PLACE_LAYER_ID+import com.vayunmathur.maps.ui.SEARCH_RESULT_LAYER_ID+import com.vayunmathur.maps.ui.TRANSIT_STOP_LAYER_ID+import com.vayunmathur.maps.ui.theme.MapChromeMetrics+import org.maplibre.spatialk.geojson.Point+import org.maplibre.spatialk.geojson.Position+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Hit-test priority, which used to be a hundred-line lambda inside a gesture handler and so+ * could not be tested at all. It is priority order that matters here: a parking pin and a POI+ * can sit on the same point, and which one a tap selects is a product decision, not an+ * accident of which `?:` came first.+ *+ * [FeatureSource] is the seam — no renderer, no composition, no device.+ */+class MapFeaturePickerTest {++    /** Records what was asked for, and answers with whatever the test planted. */+    private class FakeSource(private val hits: Map<String, List<Feature1>>) : FeatureSource {+        val queried = mutableListOf<Set<String>>()+        val boxes = mutableListOf<DpRect>()++        override fun query(box: DpRect, layerIds: Set<String>): List<Feature1> {+            queried += layerIds+            boxes += box+            return layerIds.flatMap { hits[it] ?: emptyList() }+        }+    }++    /** A geometry-only feature: present on the layer, but with no properties to resolve from. */+    private fun bareFeature() = Feature1(Point(Position(0.0, 0.0)), null)++    private val tap = DpOffset(100.dp, 200.dp)++    @Test+    fun `probes run parking, stop, search, saved, family, poi in that order`() {+        val source = FakeSource(emptyMap())+        MapFeaturePicker(source, transitEnabled = true).pickPin(tap)++        assertEquals(+            listOf(+                setOf(PARKING_PIN_LAYER_ID),+                setOf(TRANSIT_STOP_LAYER_ID),+                setOf(SEARCH_RESULT_LAYER_ID),+                setOf(SAVED_PLACE_LAYER_ID),+                setOf(FAMILY_LOCATION_LAYER_ID),+                setOf(MA_POIS_LAYER_ID),+            ),+            source.queried,+        )+    }++    @Test+    fun `probeOrder matches what actually gets queried`() {+        val source = FakeSource(emptyMap())+        val picker = MapFeaturePicker(source, transitEnabled = true)+        picker.pickPin(tap)+        assertEquals(picker.probeOrder, source.queried.map { it.single() })+    }++    /** Parking wins outright: a car spot on top of a POI is still the car spot. */+    @Test+    fun `parking beats everything below it and stops the search`() {+        val source = FakeSource(+            mapOf(+                PARKING_PIN_LAYER_ID to listOf(bareFeature()),+                MA_POIS_LAYER_ID to listOf(bareFeature()),+            )+        )+        val hit = MapFeaturePicker(source, transitEnabled = true).pickPin(tap)++        assertEquals(MapHit.Parking, hit)+        assertEquals(1, source.queried.size, "later probes must not run once a hit is found")+    }++    /** The transit probe is skipped entirely when the layer is not drawn. */+    @Test+    fun `a transit stop is not probed while the layer is off`() {+        val source = FakeSource(emptyMap())+        MapFeaturePicker(source, transitEnabled = false).pickPin(tap)+        assertTrue(+            source.queried.none { TRANSIT_STOP_LAYER_ID in it },+            "probed an invisible layer: ${source.queried}",+        )+    }++    @Test+    fun `probeOrder omits the transit layer while it is off`() {+        val picker = MapFeaturePicker(FakeSource(emptyMap()), transitEnabled = false)+        assertTrue(TRANSIT_STOP_LAYER_ID !in picker.probeOrder)+        assertEquals(5, picker.probeOrder.size)+    }++    /**+     * A feature that is present but does not resolve must not stop the search — the layer+     * being hit and the hit being usable are different things.+     */+    @Test+    fun `an unresolvable feature falls through to the next probe`() {+        val source = FakeSource(mapOf(SEARCH_RESULT_LAYER_ID to listOf(bareFeature())))+        val hit = MapFeaturePicker(source, transitEnabled = false).pickPin(tap)++        assertNull(hit)+        assertTrue(+            source.queried.any { MA_POIS_LAYER_ID in it },+            "gave up before reaching the POI layer",+        )+    }++    @Test+    fun `no hits anywhere yields null`() {+        assertNull(MapFeaturePicker(FakeSource(emptyMap()), transitEnabled = true).pickPin(tap))+    }++    /** The slop box is what makes tapping *near* a small glyph work. */+    @Test+    fun `every pin probe uses the same hit slop box around the tap`() {+        val source = FakeSource(emptyMap())+        MapFeaturePicker(source, transitEnabled = true).pickPin(tap)++        val pad = MapChromeMetrics.hitSlop+        val expected = DpRect(tap.x - pad, tap.y - pad, tap.x + pad, tap.y + pad)+        assertTrue(source.boxes.isNotEmpty())+        for (box in source.boxes) assertEquals(expected, box)+    }++    /** Labels are probed at the point, with no slop — matching the pre-refactor behaviour. */+    @Test+    fun `admin labels are probed at the exact point`() {+        val source = FakeSource(emptyMap())+        MapFeaturePicker(source, transitEnabled = true).pickAdminLabels(tap)++        assertEquals(1, source.boxes.size)+        assertEquals(DpRect(tap.x, tap.y, tap.x, tap.y), source.boxes.single())+        assertEquals(MapFeaturePicker.ADMIN_LABEL_LAYER_IDS, source.queried.single())+    }++    /** The style patcher splits every base layer into `_base` and `_hybrid` by zoom. */+    @Test+    fun `admin label ids cover both zoom variants of all three levels`() {+        val ids = MapFeaturePicker.ADMIN_LABEL_LAYER_IDS+        assertEquals(6, ids.size)+        for (level in listOf("places_country", "places_region", "places_locality")) {+            assertTrue("${level}_base" in ids, "missing ${level}_base")+            assertTrue("${level}_hybrid" in ids, "missing ${level}_hybrid")+        }+    }+}