Modern Apps git

← Modern-Apps.git

maps: fix transit discovery, sheet ceiling, lag; drop dead assets

Commit
e943a698498356db0f7d2849cf93f878a26013b6
Author
vayun-mathur <[email protected]>
When
2026-09-14 05:03 UTC (2 months ago)
Parents
db4a165

Diff

maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.ktindex 80a9b30956..f926b8e670 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt@@ -71,8 +71,9 @@ fun LayersSheet(                 )             } -            // Transit — live (P10). Shows nearby stops; tap a stop for its-            // live departure board (Transitous, online-only).+            // Transit — offline rail lines + moving vehicles from the on-device+            // pack, and a departure board for the stop nearest a tap. Stop pins+            // themselves are a tracked renderer gap ([TransitStopsLayer]).             SettingsSwitchRow(                 title = stringResource(R.string.layer_transit),                 supportingText = stringResource(R.string.layer_transit_desc),
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 0f2c600265..7d238a82c7 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -114,8 +114,22 @@ fun MapPage(     val camera = rememberCameraState(INITIAL_CAMERA)      val selectedFeature by viewModel.selectedFeature.collectAsState()+    // Keep the router's plan order on the visible tab: routes plans the+    // selected mode first, so a tab switch made before the flow restarts must+    // still reach it. A plain assignment (not a flow input) so switching tabs+    // never re-plans every mode — the flow restarts on selection change only.+    val selectedRouteType = chrome.selectedRouteType+    LaunchedEffect(selectedRouteType) {+        viewModel.selectedRouteMode = selectedRouteType+    }     val inactiveNavigation by viewModel.inactiveNavigation.collectAsState()     val route by viewModel.routes.collectAsState(null)+    // Collected here (rather than inside the sheet) so the inner place sheet's+    // contentKey can name them: the tab switch and the late-arriving reviews+    // each change the sheet's content height, and without them in the key the+    // learned ceiling from Details traps the taller Reviews list.+    val poiSection by viewModel.poiSection.collectAsState()+    val currentPoiInfo by viewModel.currentPoiInfo.collectAsState()     val userPosition by viewModel.userPosition.collectAsState()     val userBearing by viewModel.userBearing.collectAsState()     val userHeadingAccuracy by viewModel.userHeadingAccuracy.collectAsState()@@ -238,6 +252,8 @@ fun MapPage(         selectedFeature = selectedFeature,         inactiveNavigation = inactiveNavigation,         route = route,+        poiSection = poiSection,+        poiEnrichmentKey = PoiEnrichmentKey.of(currentPoiInfo),         userPosition = userPosition,         userBearing = userBearing,         userHeadingAccuracy = userHeadingAccuracy,
maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.ktindex d9df5b4bc1..bd8c477e86 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPageScope.kt@@ -11,6 +11,8 @@ import com.vayunmathur.maps.Route import com.vayunmathur.maps.data.ParkingSpot import com.vayunmathur.maps.data.SavedPlace import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.google.GooglePoiInfo+import com.vayunmathur.maps.data.google.PoiSection import com.vayunmathur.maps.data.transit.TransitStop import com.vayunmathur.maps.ipc.FamilyMember import com.vayunmathur.maps.ui.map.MapChromeState@@ -27,6 +29,30 @@ import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.TransitStopsViewModel import kotlinx.coroutines.CoroutineScope +/**+ * Coarse identity of the place enrichment for the inner place sheet's+ * contentKey: review/photo counts plus featured-review presence.+ *+ * Late-arriving reviews and photos grow the sheet content after measurement,+ * which the scaffold's learned ceiling would otherwise never re-learn. Kept+ * to counts/presence rather than the full lists so progressive review+ * streaming settles the key (null → base → final) instead of resetting the+ * ceiling on every partial.+ */+data class PoiEnrichmentKey(+    val reviewCount: Int,+    val photoCount: Int,+    val hasFeaturedReview: Boolean,+) {+    companion object {+        fun of(poi: GooglePoiInfo?): PoiEnrichmentKey = PoiEnrichmentKey(+            reviewCount = poi?.reviews?.size ?: 0,+            photoCount = poi?.photoUrls?.size ?: 0,+            hasFeaturedReview = poi?.featuredReview != null,+        )+    }+}+ /**  * An open search sheet.  *@@ -71,6 +97,21 @@ internal class MapPageScope(     val selectedFeature: SpecificFeature?,     val inactiveNavigation: SpecificFeature.Route?,     val route: Map<RouteService.TravelMode, RouteService.RouteType?>?,+    /**+     * Which of the place sheet's Details / Photos / Reviews tabs is showing.+     * Part of the inner place sheet's contentKey (with [poiEnrichmentKey]):+     * each tab is a different content height, and without the tab in the key+     * a sheet opened on Details keeps its low learned ceiling on Reviews.+     */+    val poiSection: PoiSection,+    /**+     * Coarse enrichment signature for the inner place sheet's contentKey.+     * Late-arriving reviews/photos grow the content after measurement, which+     * the learned ceiling would otherwise never re-learn; kept to+     * counts/presence (not the full lists) so progressive review streaming+     * settles the key instead of resetting it on every partial.+     */+    val poiEnrichmentKey: PoiEnrichmentKey,     val userPosition: GeoPoint,     val userBearing: Float?,     val userHeadingAccuracy: Int,
maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.ktindex e4b4949e5b..4dcd60285f 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapSheets.kt@@ -85,7 +85,15 @@ internal fun MapPageScope.MapSheets(                     Modifier.padding(horizontal = Spacing.lg).padding(top = Spacing.sm),                 )             },-            contentKey = listOf(selectedFeature, chrome.selectedRouteType),+            // The selection, the route-type, the POI tab AND the enrichment+            // identity: each names a different content height. The tab because+            // Details content teaches the scaffold a low ceiling that would+            // trap the taller Reviews list; the enrichment signature because+            // late-arriving reviews/photos grow the content after measurement.+            // Coarse (counts/presence, not the lists) so progressive streaming+            // settles the key instead of resetting it on every partial. Wide+            // layout has no sheet (MapSidePanel) and needs no key.+            contentKey = listOf(selectedFeature, chrome.selectedRouteType, poiSection, poiEnrichmentKey),         ) { _ ->             MapContentBox(Modifier.fillMaxSize())         }
maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.ktindex 1e0b08c765..c106219435 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt@@ -39,6 +39,23 @@ private const val VEHICLE_TICK_MS = 1_000L  */ private const val VEHICLE_MIN_ZOOM = 11.0 +/**+ * How far the bbox centre may drift (degrees) before a recompute is forced.+ * A degree of latitude is ~111 km, so this is ~50 m: a static camera reuses+ * the last enumeration rather than paying a JNI round-trip plus a full marker+ * rebuild every second for sprites that moved a few metres.+ */+private const val VEHICLE_BBOX_TOLERANCE_DEG = 0.0005++/**+ * How many consecutive 1 Hz ticks may reuse the last enumeration while the+ * camera is static. Positions are interpolated per recompute, so an unbounded+ * skip would freeze the sprites; this bounds the staleness to a few seconds+ * (a few dozen metres at transit speeds) while still cutting the steady-state+ * JNI + recomposition rate of a stationary map.+ */+private const val VEHICLE_MAX_REUSE_TICKS = 3+ /**  * The simulated in-service transit vehicles for the visible bbox, recomputed at ~1 Hz and mapped to  * renderer markers, or an empty list when the transit layer is off, the surface is hidden, or the@@ -80,24 +97,50 @@ fun rememberTransitVehicles(             vehicles = emptyList()             return@LaunchedEffect         }+        // Last enumeration, reused while the camera is static (see below).+        var lastCentreLat = Double.NaN+        var lastCentreLon = Double.NaN+        var lastZoom = Double.NaN+        var reuseTicks = 0         while (true) {             val bounds = camera.visibleBoundsOrWorld()-            vehicles = if (camera.position.zoom < VEHICLE_MIN_ZOOM) {-                emptyList()-            } else {-                OfflineRouter.activeVehicles(-                    context,-                    minLat = bounds.south,-                    minLon = bounds.west,-                    maxLat = bounds.north,-                    maxLon = bounds.east,-                ).map { v ->-                    MapMarker(-                        id = v.id,-                        position = GeoPoint(longitude = v.lon, latitude = v.lat),-                        icon = gtfsModeToMarkerIcon(v.mode),-                    )+            val zoom = camera.position.zoom+            val centreLat = (bounds.south + bounds.north) / 2.0+            val centreLon = (bounds.west + bounds.east) / 2.0+            // A static camera reuses the last enumeration: the native call+            // interpolates positions per recompute, but a second of drift is+            // metres at transit speeds while the JNI round-trip plus the+            // marker-list rebuild and re-push cost every tick. Bounded by+            // VEHICLE_MAX_REUSE_TICKS so the sprites never freeze; reusing the+            // same list instance also skips recomposition downstream.+            val cameraStatic = zoom >= VEHICLE_MIN_ZOOM &&+                kotlin.math.abs(centreLat - lastCentreLat) < VEHICLE_BBOX_TOLERANCE_DEG &&+                kotlin.math.abs(centreLon - lastCentreLon) < VEHICLE_BBOX_TOLERANCE_DEG &&+                kotlin.math.abs(zoom - lastZoom) < 0.25+            if (!cameraStatic || reuseTicks >= VEHICLE_MAX_REUSE_TICKS) {+                vehicles = if (zoom < VEHICLE_MIN_ZOOM) {+                    emptyList()+                } else {+                    OfflineRouter.activeVehicles(+                        context,+                        minLat = bounds.south,+                        minLon = bounds.west,+                        maxLat = bounds.north,+                        maxLon = bounds.east,+                    ).map { v ->+                        MapMarker(+                            id = v.id,+                            position = GeoPoint(longitude = v.lon, latitude = v.lat),+                            icon = gtfsModeToMarkerIcon(v.mode),+                        )+                    }                 }+                lastCentreLat = centreLat+                lastCentreLon = centreLon+                lastZoom = zoom+                reuseTicks = 0+            } else {+                reuseTicks++             }             delay(VEHICLE_TICK_MS)         }
maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.ktindex c2535eaa94..7484ffd03f 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt@@ -31,6 +31,13 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {     /** What [acceptsFix] compares against. Kept beside [lastLocation] so the two never disagree. */     private var lastFix: Fix? = null     private var currentHeading: Float? = null+    /**+     * Last compass heading actually emitted to the UI. The emit gate compares+     * against this rather than the previous sensor sample: smoothing moves a+     * fraction of the remaining gap per sample, so during a slow turn each+     * step is sub-degree while the accumulated movement is real.+     */+    private var lastEmittedHeading: Float? = null     /** Listener we registered with the OS so [stop] can unregister it. */     private var registeredLocationListener: LocationListener? = null @@ -55,6 +62,10 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {                 lastLocation = location                 // If location has a GPS bearing, we prioritize it while moving                 val heading = if (location.hasBearing()) location.bearing else currentHeading+                // A GPS fix is authoritative: re-anchor the compass emit gate so+                // the next sensor sample compares against what the UI just drew+                // rather than a pre-fix heading.+                if (location.hasBearing()) lastEmittedHeading = location.bearing                 onUpdate?.invoke(GeoPoint(location.longitude, location.latitude), heading)             }             @Deprecated("Overrides deprecated LocationListener.onStatusChanged")@@ -93,9 +104,12 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {         onAccuracy = null         // Otherwise a restart compares the first fix against one from the previous session and         // can reject it: `elapsedRealtimeNanos` keeps counting while updates are unregistered,-        // so the old fix would look fresh enough to keep winning.+        // so the old fix would look fresh enough to keep winning. The heading gate is reset+        // for the same reason: the first compass sample must always emit.         lastFix = null         lastLocation = null+        currentHeading = null+        lastEmittedHeading = null     }      override fun onSensorChanged(event: SensorEvent) {@@ -121,9 +135,15 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {             // renderer takes it away.             currentHeading = smoothHeading(currentHeading, newHeading) -            // Update UI if we have a location but the user is standing still+            // Update UI if we have a location but the user is standing still.+            // Gated on movement since the last EMIT (not the last sample):+            // the sensor fires at ~60 ms whether or not the phone turned, and+            // an ungated emit pushes userPosition/userBearing through the page+            // (and wakes the renderer) at sensor rate even on a desk. Location+            // fixes bypass this — they always emit.             lastLocation?.let {-                if (!it.hasBearing()) {+                if (!it.hasBearing() && headingDelta(lastEmittedHeading, currentHeading ?: newHeading) >= HEADING_EMIT_DEGREES) {+                    lastEmittedHeading = currentHeading                     onUpdate?.invoke(GeoPoint(it.longitude, it.latitude), currentHeading)                 }             }@@ -165,6 +185,26 @@ internal fun smoothHeading(  */ private const val HEADING_SMOOTHING = 0.15f +/**+ * Minimum smoothed-heading movement (degrees) that re-emits the compass update.+ * The sensor fires at ~60 ms even when the phone is sitting on a desk, and every+ * emission used to push `userPosition`/`userBearing` through the page and wake the+ * renderer — so a stationary phone recomposed at sensor rate for a heading that+ * had converged to a tenth of a degree. Below this delta the cone cannot move a+ * visible pixel, and the update is dropped.+ */+private const val HEADING_EMIT_DEGREES = 1.0f++/**+ * Shortest-arc distance between two headings, in degrees. Null [current] (the+ * first reading) counts as infinitely far: the initial fix must always emit.+ */+internal fun headingDelta(current: Float?, target: Float): Float {+    if (current == null) return Float.MAX_VALUE+    val delta = (target - current + 540f) % 360f - 180f+    return kotlin.math.abs(delta)+}+ /**  * The part of a fix that decides whether it is worth taking, independent of `android.location`  * so the policy can be tested without a device.
maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt b/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.ktindex e06c8991ae..6b9b82511c 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt@@ -4,6 +4,17 @@ import android.content.Context import android.util.Log import java.util.concurrent.ConcurrentHashMap +/**+ * Last-resort route-colour lookup from a GTFS `routes.txt`.+ *+ * Pack-first: [OfflineRouterRouteBuilder] prefers the `route_color` baked into+ * the transit pack and only falls back here. The lookup opens+ * `assets/<feedName>/routes.txt` from the APK; no feed assets ship anymore+ * (the SLO-only `US-CA-SLOT/` folder and the orphan `world_map.png` were+ * deleted — the world pack covers San Francisco and the sidecars never did),+ * so this returns null when absent rather than failing. API unchanged: the+ * CSV parser is covered by `GTFSProviderTest`.+ */ object GTFSProvider {     // Accessed concurrently from OfflineRouter.getRoute (Dispatchers.Default)     // and from the map layers on the Main thread, so use a thread-safe map —
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex 58c24d4ffa..183c3e55a5 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -150,6 +150,19 @@ object OfflineRouter {             overlayTimes: IntArray,             max: Int     ): Array<RawDeparture>?+    /**+     * Whether `<basePath>/basemap.mamaps` carries a transit section (kind 13).+     *+     * The archive already ships the world transit pack (packed by+     * `mamaps_pack --transit` and read archive-first by the native+     * `transit_index`), but the Kotlin discovery gate used to list only the+     * per-region sidecar packs under `<basePath>` - so on an archive-only+     * device every transit entry point short-circuited before any JNI call.+     * A pure presence probe (section directory only, no pack parse), cheap+     * enough to call on every entry.+     */+    internal external fun hasTransitArchiveNative(basePath: String): Boolean+     /**      * IANA timezone of the feed covering `(lat,lon)` in the given pack, or null      * when the pack is stale/absent, doesn't cover the point, or its GTFS had no@@ -245,6 +258,14 @@ object OfflineRouter {      * (a graph swap can renumber ids).      */     private val componentBySquare = java.util.concurrent.ConcurrentHashMap<Int, TrafficComponents>()+    /**+     * Last published merge, for the unchanged-content skip in+     * [republishComponents]. Volatile (not confined): fetches complete on+     * IO threads, so the read-modify-publish must tolerate races — the worst+     * case is one redundant publish, never a missed one.+     */+    @Volatile+    private var lastPublishedComponents: TrafficComponents? = null     private val _trafficComponents =             kotlinx.coroutines.flow.MutableStateFlow(TrafficComponents.EMPTY) @@ -267,7 +288,18 @@ object OfflineRouter {             System.arraycopy(s.ratioPct, 0, ratios, off, s.ratioPct.size)             off += s.ids.size         }-        _trafficComponents.value = TrafficComponents(ids, ratios)+        // Skip the publish when the merged content is unchanged: every fetch+        // lands here, and a fresh object wakes the trafficComponents+        // collectors (table rebuild + renderer re-push) even when a refetch+        // returned identical bytes. Content-compare is O(n) against the same+        // concat that already ran, far cheaper than the downstream rebuild.+        val last = lastPublishedComponents+        if (last != null && last.ids.contentEquals(ids) && last.ratioPct.contentEquals(ratios)) {+            return+        }+        val snapshot = TrafficComponents(ids, ratios)+        lastPublishedComponents = snapshot+        _trafficComponents.value = snapshot     }      private var cacheDirPath: String? = null@@ -488,7 +520,7 @@ object OfflineRouter {     )      private var isInitialized = false-    /** Base dir (external files) holding downloaded packs incl. `*.transit`. */+    /** Base dir (external files) holding the downloaded `basemap.mamaps` archive and legacy `*.transit` packs. */     private var basePath: String? = null      /**@@ -525,6 +557,7 @@ object OfflineRouter {         // A new graph vintage can renumber edge/component ids, so the display cache from the         // old graph must not survive the swap.         componentBySquare.clear()+        lastPublishedComponents = null         _trafficComponents.value = TrafficComponents.EMPTY         initialize(context)     }@@ -612,8 +645,9 @@ object OfflineRouter {      /**      * Offline transit routing (P11d): plan a journey with the on-device RAPTOR-     * planner over any downloaded per-region `*.transit` index that covers the-     * endpoints. Returns null when no index is present/covering or no journey is+     * planner over the transit pack covering the endpoints (the world pack in+     * the archive when present, else a downloaded per-region `*.transit`+     * index). Returns null when no index is present/covering or no journey is      * found — the caller then falls back to the P10 online Transitous planner.      *      * Runs at most **two** RAPTOR passes: a schedule-only plan, then, when the@@ -652,7 +686,7 @@ object OfflineRouter {     ): List<Vehicle> = OfflineRouterTransit.activeVehicles(context, minLat, minLon, maxLat, maxLon)      /**-     * Departure board from the baked `*.transit` index for the stop nearest+     * Departure board from the on-device transit index for the stop nearest      * `(lat,lon)` — see [OfflineRouterTransit.getStopDeparturesOffline] for the      * shared implementation. Kept here as a thin delegate so existing callers      * don't move.
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.ktindex e770f811bd..5f13cb2606 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTransit.kt@@ -1,6 +1,7 @@ package com.vayunmathur.maps.util  import android.content.Context+import android.util.Log import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.library.util.ConnectivityMonitor import com.vayunmathur.maps.data.transit.Departure@@ -14,8 +15,10 @@ import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.withContext  /**- * Offline transit planning over the per-region `*.transit` packs, extracted from- * [OfflineRouter] to keep that file under the length limit.+ * Offline transit planning over the on-device transit pack - the world pack+ * inside `<base>/basemap.mamaps` when the archive carries it, else the legacy+ * per-region sidecar packs - extracted from [OfflineRouter] to keep that file+ * under the length limit.  *  * The JNI surface (native methods, `RawStep`/`RawDeparture`/`RawVehicle`, the traffic fetch  * callback) stays on [OfflineRouter] — native code resolves those by class and member name, so@@ -51,9 +54,13 @@ internal object OfflineRouterTransit {     /**      * Pack names under the base path, listed once.      *-     * Every transit entry point used to `listFiles` this directory and loop over-     * the result; in practice there is exactly one pack. Cleared by [onReload], which-     * [OfflineRouter.reload] calls once a download has replaced it.+     * The single-archive `basemap.mamaps` already ships the world transit+     * pack as section 13 (packed by `mamaps_pack --transit`), and the native+     * index reads it first - so an archive-present device reports a single+     * `world` pseudo-feed that routes every transit entry point to that+     * archive path. Legacy per-file sidecar packs are the fallback for+     * archives without a transit section. Cleared by [onReload], which+     * [OfflineRouter.reload] calls once a download has replaced the archive.      */     @Volatile     private var cachedTransitFeeds: List<String>? = null@@ -65,6 +72,18 @@ internal object OfflineRouterTransit {      private fun transitFeeds(base: String): List<String> {         cachedTransitFeeds?.let { return it }+        // Archive first: on an archive-only device there are no sidecar files,+        // so a file listing alone would disable offline transit everywhere.+        // The probe reads the archive section directory only (no pack parse);+        // a negative simply falls through to the legacy per-file list below.+        // The native index reads the archive first and ignores the feed name+        // on that path, so this stable pseudo-feed routes there.+        if (runCatching { OfflineRouter.hasTransitArchiveNative(base) }.getOrDefault(false)) {+            Log.d("OfflineRouterTransit", "archive transit section found")+            val feeds = listOf("world")+            cachedTransitFeeds = feeds+            return feeds+        }         val feeds = File(base)                 .listFiles { f -> f.isFile && f.name.endsWith(".transit") }                 ?.map { it.name.removeSuffix(".transit") }@@ -77,8 +96,9 @@ internal object OfflineRouterTransit {      /**      * Offline transit routing (P11d): plan a journey with the on-device RAPTOR-     * planner over any downloaded per-region `*.transit` index that covers the-     * endpoints. Returns null when no index is present/covering or no journey is+     * planner over the transit pack covering the endpoints (the world pack in+     * the archive when present, else a downloaded per-region sidecar index).+     * Returns null when no index is present/covering or no journey is      * found — the caller then falls back to the P10 online Transitous planner.      *      * Runs at most **two** RAPTOR passes: a schedule-only plan, then, when the@@ -199,7 +219,7 @@ internal object OfflineRouterTransit {     }      /**-     * The stop nearest `(lat, lon)` from the baked `*.transit` packs, as a+     * The stop nearest `(lat, lon)` from the on-device transit pack, as a      * [TransitStop] whose id is the MOTIS/Transitous id so the realtime board can      * query it. Null when no pack covers the point.      *@@ -227,7 +247,7 @@ internal object OfflineRouterTransit {      /**      * Simulated moving transit vehicles within the visible bbox (WS-F). Positions-     * are interpolated on-device from each downloaded `*.transit` pack's schedule ++     * are interpolated on-device from the on-device pack's schedule +      * shape by the native `activeVehiclesNative`; there is no live GPS feed. The      * result is meant to be recomputed at ~1 Hz by a ticker (the renderer's frame      * clock smooths motion between recomputes) and pushed to the map overlay.@@ -287,7 +307,7 @@ internal object OfflineRouterTransit {     }      /**-     * Departure board from the baked `*.transit` index for the stop nearest+     * Departure board from the on-device transit index for the stop nearest      * `(lat,lon)`. Scheduled times come from the pack; when the device is online      * the MOTIS board for that stop is folded in as a realtime overlay, so      * `delayMinutes`/`realTime`/`cancelled` are live. Returns an empty list when
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 d6b58571ec..d8f31194d8 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -40,6 +40,28 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli         _poiSection.value = section     } +    /**+     * The route tab the sheet is showing (DRIVE by default). Read once per+     * selection by [routes] so the visible tab's mode plans first; the flow+     * restarts on the next selection change anyway, so this is a plain var+     * rather than a collected flow (collecting it would re-plan every mode+     * on each tab switch). Synced from the chrome tab in MapPage.+     */+    var selectedRouteMode: RouteService.TravelMode = RouteService.TravelMode.DRIVE++    /**+     * Coalescing gates for the review-streaming partials in [currentPoiInfo]:+     * forward a partial only when the list grew by [PARTIAL_MIN_GROWTH]+     * reviews or [PARTIAL_MIN_INTERVAL_MS] elapsed since the last forward.+     * Dozens of per-parse emissions used to recompose the sheet for a list+     * the user barely sees change; the authoritative final send still always+     * runs, so a dropped partial loses nothing.+     */+    private companion object {+        const val PARTIAL_MIN_GROWTH = 5+        const val PARTIAL_MIN_INTERVAL_MS = 2_000L+    }+     /** A pending request for the map to fly to [position] (at [zoom] when set) and      *  show the place bottom PANE (peek), the Vela-style place card. Backed by a      *  StateFlow so a request made before MapPage is composed (a cold-start deep@@ -164,11 +186,28 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli                 // failure/timeout just leaves reviews empty and the sheet as-is.                 val fid = base?.featureId                 if (base != null && !fid.isNullOrBlank()) {+                    // Coalesce the progressive partials: the scraper streams the+                    // accumulated list on every parse, and each trySend+                    // recomposes the sheet that collects this flow. Forward a+                    // partial only when it grew meaningfully or enough time+                    // passed; the authoritative final send below still always+                    // runs, so nothing is ever lost by a dropped partial.+                    var lastPartialSize = 0+                    var lastPartialMs = 0L                     val reviews = runCatching {                         webReviews.fetch(                             featureId = fid,                             onPartial = { list ->-                                if (list.isNotEmpty()) trySend(base.copy(reviews = list))+                                if (list.isNotEmpty()) {+                                    val nowMs = System.currentTimeMillis()+                                    if (list.size - lastPartialSize >= PARTIAL_MIN_GROWTH ||+                                        nowMs - lastPartialMs >= PARTIAL_MIN_INTERVAL_MS+                                    ) {+                                        lastPartialSize = list.size+                                        lastPartialMs = nowMs+                                        trySend(base.copy(reviews = list))+                                    }+                                }                             },                         )                     }.getOrDefault(emptyList())@@ -183,31 +222,48 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli         )      // Move heavy computation to a background StateFlow+    //+    // The selected tab's mode is computed first and emitted immediately, so+    // the visible route overlay resolves after one plan instead of four: the+    // old sequential loop emitted five maps (empty + one per mode) through+    // `scan`, and every emission re-resolved the route overlay/traffic tables+    // and re-pushed to the renderer. The remaining modes compute lazily off+    // the critical path and arrive in a single coalesced map. [selectedRouteMode]+    // is read once per selection (not collected): the flow restarts on the+    // next selection change anyway, and collecting the tab here would re-plan+    // every mode on each tab switch.     @OptIn(ExperimentalCoroutinesApi::class)     val routes = selectedFeature         .flatMapLatest { feature ->             val pos = userPosition.value+            val selectedMode = selectedRouteMode             val routeFeature = feature as? SpecificFeature.Route ?: return@flatMapLatest flowOf(null) -            // Create a flow that emits results one by one             flow {-                // Start with an empty map                 emit(emptyMap()) +                suspend fun plan(mode: RouteService.TravelMode): RouteService.RouteType? =+                    try {+                        OfflineRouter.getRouteForMode(application, routeFeature, pos, mode)+                    } catch (_: Exception) {+                        null+                    } ?: RouteService.EmptyRoute()+                 // Offline-first routing with chained multi-waypoint support.                 // TRANSIT prefers the on-device RAPTOR planner over any                 // downloaded region index (P11d); if none covers the trip, it                 // falls back to the P10 online Transitous (MOTIS) planner.                 // getRouteForMode owns that split so the road graph, which has no                 // timetable, never sees TRANSIT.-                RouteService.TravelMode.entries.forEach { mode ->-                    val result = try {-                        OfflineRouter.getRouteForMode(application, routeFeature, pos, mode)-                    } catch (_: Exception) {-                        null-                    }-                    emit(mapOf(mode to (result ?: RouteService.EmptyRoute())))+                val first = plan(selectedMode)+                emit(mapOf(selectedMode to first))++                val rest = mutableMapOf<RouteService.TravelMode, RouteService.RouteType?>()+                for (mode in RouteService.TravelMode.entries) {+                    if (mode == selectedMode) continue+                    rest[mode] = plan(mode)                 }+                emit(mapOf(selectedMode to first) + rest)             }                 .scan(RouteService.TravelMode.entries.associateWith { null as RouteService.RouteType? }) { accumulator, newEntry ->                     accumulator + newEntry // Combine the old map with the new calculation
maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.ktindex 1072c4c231..620a229822 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt@@ -27,10 +27,11 @@ import kotlinx.coroutines.withContext /**  * Drives the P10 public-transit UI: the departure board for a tapped stop.  *- * The stop *pins* are no longer this class's business — they render straight from- * the baked `transit_stops` basemap layer (see- * [com.vayunmathur.maps.ui.TransitStopsLayer]), since stops are static data and a- * per-viewport fetch on every camera idle bought nothing.+ * The stop *pins* are no longer this class's business — and currently nobody's:+ * they used to render straight from the baked `transit_stops` basemap layer,+ * but the renderer has no vector source-layer API so [com.vayunmathur.maps.ui.TransitStopsLayer]+ * is a no-op until it grows one (tracked gap). Stop taps arrive via baked POI+ * hits / station-POI nearest-stop resolution instead.  *  * [departures] is the board for the [openStop]-selected stop, re-fetched on  * [refresh]. The live countdown itself is computed client-side in the sheet from@@ -39,8 +40,9 @@ import kotlinx.coroutines.withContext  * All network is on [Dispatchers.IO], and is skipped entirely when  * [ConnectivityMonitor] reports no validated internet — otherwise every offline  * lookup pays a full HTTP timeout. The departure board is offline-first: the- * baked `.transit` pack supplies the schedule and MOTIS supplies the realtime- * overlay on top of it.+ * on-device transit pack (the world pack in the archive when present, else a+ * legacy `*.transit` sidecar) supplies the schedule and MOTIS supplies the+ * realtime overlay on top of it.  */ class TransitStopsViewModel(application: Application) : AndroidViewModel(application) { 
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex b136691a24..75c60fde2e 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -327,8 +327,8 @@     <string name="layer_safety_unavailable">Coming soon</string>     <!-- LayersSheet: public-transit layer toggle. Noun. -->     <string name="layer_transit">Transit</string>-    <!-- LayersSheet: transit layer description. Covers both the rail/route lines the basemap renderer draws and the tappable stop pins with live departure times. -->-    <string name="layer_transit_desc">Show rail lines, nearby stops and live departures</string>+    <!-- LayersSheet: transit layer description. Rail lines the basemap renderer draws plus the simulated vehicle sprites and the departure board for the stop nearest a tap; stop pins are a tracked renderer gap (TransitStopsLayer is a no-op). -->+    <string name="layer_transit_desc">Show rail lines, live vehicles and departures</string>      <!-- Departure board: section subtitle under the stop name. Noun. -->     <string name="transit_departures_title">Departures</string>
maps/src/main/rust/src/jni/transit_jni/lookups.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/lookups.rs b/maps/src/main/rust/src/jni/transit_jni/lookups.rsindex fd02e92348..17c31b9e30 100644--- a/maps/src/main/rust/src/jni/transit_jni/lookups.rs+++ b/maps/src/main/rust/src/jni/transit_jni/lookups.rs@@ -3,11 +3,41 @@ //! Pure move out of `super` (`transit_jni.rs`); no logic changes.  use jni::objects::{JObject, JString};-use jni::sys::{jdouble, jstring};+use jni::sys::{jboolean, jdouble, jstring}; use jni::JNIEnv;  use super::cache::transit_index; +// ---------------------------------------------------------------------------+// JNI: hasTransitArchiveNative (does the archive carry a transit section?)+// ---------------------------------------------------------------------------++/// Whether `<base_path>/basemap.mamaps` carries a transit section (kind 13).+///+/// The Kotlin discovery gate calls this before listing per-region+/// `<base>/*.transit` files: on an archive-only device there are no sidecar+/// files, so without this the gate finds nothing and every transit entry+/// point short-circuits before any JNI call. A pure presence probe — it reads+/// the archive's section directory without parsing the TRIX pack — so it is+/// cheap enough to call on every entry.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_hasTransitArchiveNative<+    'local,+>(+    mut env: JNIEnv<'local>,+    _thiz: JObject<'local>,+    base_path: JString<'local>,+) -> jboolean {+    let base: String = match env.get_string(&base_path) {+        Ok(s) => s.into(),+        Err(_) => return 0,+    };+    let present = crate::transit::TransitIndex::has_archive_transit(+        &crate::graph::archive_path(&base),+    );+    present as jboolean+}+ // --------------------------------------------------------------------------- // JNI: getFeedTimezoneNative (IANA tz of the feed covering a coordinate) // ---------------------------------------------------------------------------
maps/src/main/rust/src/transit_part10.rs
diff --git a/maps/src/main/rust/src/transit_part10.rs b/maps/src/main/rust/src/transit_part10.rsindex 6c6f72ce8e..5f044627c2 100644--- a/maps/src/main/rust/src/transit_part10.rs+++ b/maps/src/main/rust/src/transit_part10.rs@@ -10,6 +10,31 @@ use tilecodec::mamaps::archive::{ARCHIVE_KIND_TRANSIT, ArchiveView}; use tilecodec::mamaps::header::Header;  impl TransitIndex {+    /// Whether `path` is a single-archive (`.mamaps`) carrying a transit+    /// section (kind 13).+    ///+    /// A pure presence probe for the Kotlin discovery gate: it maps the+    /// container and reads its section directory, without parsing the TRIX+    /// pack itself, so it is cheap and safe to call on every transit entry.+    /// False when the file is missing, the container is corrupt, or the+    /// archive simply has no transit section (a tiles-only build).+    pub fn has_archive_transit(path: &str) -> bool {+        let Some(region) = MmapRegion::map(path) else {+            return false;+        };+        // The mapping must cover the whole file: ArchiveView::parse checks+        // `bytes.len() == header.file_len`, and a short mapping would refuse+        // a good archive rather than read past it.+        let bytes = unsafe { std::slice::from_raw_parts(region.base(), region.len) };+        let Ok(header) = Header::parse(bytes) else {+            return false;+        };+        let Ok(view) = ArchiveView::parse(bytes, &header) else {+            return false;+        };+        view.location(ARCHIVE_KIND_TRANSIT).is_some()+    }+     /// Load the transit pack from a single-archive `.mamaps` file.     ///     /// Returns `None` when the container is corrupt, the build id disagrees,
maps/src/main/rust/src/transit_part9.rs
diff --git a/maps/src/main/rust/src/transit_part9.rs b/maps/src/main/rust/src/transit_part9.rsindex 134e88c43d..6ca96f85f7 100644--- a/maps/src/main/rust/src/transit_part9.rs+++ b/maps/src/main/rust/src/transit_part9.rs@@ -308,3 +308,65 @@         assert_eq!((ride.dep_secs, ride.arr_secs), (28_800, 29_400));         std::fs::remove_file(&path).ok();     }++    // The Kotlin discovery gate's presence probe: an archive with section 13+    // reads present, a tiles-only archive (or a missing/garbage file) reads+    // absent. Unix only, same mmap reason as the test above.+    #[cfg(unix)]+    #[test]+    fn has_archive_transit_sees_section_thirteen() {+        let pack = one_route_pack().build_with_version(VERSION);+        let bytes = archive_with_pack(&pack);+        let path = std::env::temp_dir().join(format!(+            "transit_presence_{}.mamaps",+            std::process::id()+        ));+        std::fs::write(&path, &bytes).unwrap();+        assert!(+            TransitIndex::has_archive_transit(path.to_str().unwrap()),+            "an archive built with a transit section reads present"+        );+        std::fs::remove_file(&path).ok();+    }++    #[cfg(unix)]+    #[test]+    fn has_archive_transit_refuses_a_tiles_only_archive() {+        // Same tiles-only container as+        // `an_archive_without_a_transit_section_yields_no_index`: no section+        // 13, so the probe reads absent and Kotlin keeps the legacy+        // per-file path rather than advertising transit it cannot plan.+        let mut header = archive_header(0);+        let mut out = vec![0u8; 4096];+        while out.len() as u64 % ARCHIVE_ALIGN != 0 {+            out.push(0);+        }+        let dir_offset = out.len() as u64;+        let (dir, _) = tilecodec::mamaps::archive::serialize_dir(&[], ARCHIVE_BUILD_ID, dir_offset);+        out.extend_from_slice(&dir);+        let footer = ArchiveFooter {+            dir_offset,+            dir_len: dir.len() as u64,+            build_id: ARCHIVE_BUILD_ID,+        };+        out.extend_from_slice(&footer.serialize());+        header.file_len = out.len() as u64;+        let head = header.serialize();+        out[..head.len()].copy_from_slice(&head);+        let path = std::env::temp_dir().join(format!(+            "transit_presence_tiles_only_{}.mamaps",+            std::process::id()+        ));+        std::fs::write(&path, &out).unwrap();+        assert!(+            !TransitIndex::has_archive_transit(path.to_str().unwrap()),+            "a tiles-only archive reads absent"+        );+        assert!(+            !TransitIndex::has_archive_transit(+                path.with_extension("missing").to_str().unwrap()+            ),+            "a missing file reads absent rather than panicking"+        );+        std::fs::remove_file(&path).ok();+    }
maps/src/test/java/com/vayunmathur/maps/ui/PoiEnrichmentKeyTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/PoiEnrichmentKeyTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/PoiEnrichmentKeyTest.ktnew file mode 100644index 0000000000..43c5909907--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/PoiEnrichmentKeyTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.maps.ui++import com.vayunmathur.maps.data.google.GooglePoiInfo+import com.vayunmathur.maps.data.google.GoogleReview+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals++/**+ * The coarse enrichment identity behind the inner place sheet's contentKey.+ *+ * Late-arriving reviews/photos grow the sheet content after measurement, which+ * the scaffold's learned ceiling would otherwise never re-learn — so the key+ * must move when the enrichment arrives. But it must stay coarse+ * (counts/presence, not the lists): progressive review streaming would reset+ * the ceiling on every partial if the key named the content itself.+ */+class PoiEnrichmentKeyTest {++    private fun review(i: Int) = GoogleReview(+        author = "a$i",+        authorPhoto = null,+        rating = 5,+        relativeTime = null,+        text = "review $i",+    )++    @Test+    fun `null enrichment keys to zero`() {+        assertEquals(PoiEnrichmentKey(0, 0, false), PoiEnrichmentKey.of(null))+    }++    @Test+    fun `arriving reviews move the key`() {+        val before = PoiEnrichmentKey.of(GooglePoiInfo())+        val after = PoiEnrichmentKey.of(GooglePoiInfo(reviews = List(8, ::review)))+        assertNotEquals(before, after)+    }++    @Test+    fun `arriving photos move the key`() {+        val before = PoiEnrichmentKey.of(GooglePoiInfo())+        val after = PoiEnrichmentKey.of(GooglePoiInfo(photoUrls = listOf("u1", "u2")))+        assertNotEquals(before, after)+    }++    @Test+    fun `a featured review moves the key`() {+        val before = PoiEnrichmentKey.of(GooglePoiInfo())+        val after = PoiEnrichmentKey.of(GooglePoiInfo(featuredReview = "great soup"))+        assertNotEquals(before, after)+    }++    @Test+    fun `review text churn without growth keeps the key`() {+        // Progressive streaming re-sends the accumulated list on every parse:+        // same size, same shape → same key → the ceiling survives the partials.+        val a = PoiEnrichmentKey.of(GooglePoiInfo(reviews = List(8, ::review)))+        val b = PoiEnrichmentKey.of(+            GooglePoiInfo(reviews = List(8) { review(it).copy(text = "edited $it") })+        )+        assertEquals(a, b)+    }+}
maps/src/test/java/com/vayunmathur/maps/util/HeadingGateTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/HeadingGateTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/HeadingGateTest.ktnew file mode 100644index 0000000000..a7942af1ee--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/HeadingGateTest.kt@@ -0,0 +1,44 @@+package com.vayunmathur.maps.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The compass emit gate behind the user puck's bearing cone.+ *+ * The magnetometer fires at ~60 ms whether or not the phone turned, and every+ * emission used to push `userPosition`/`userBearing` through the page (and wake+ * the renderer) — so a stationary phone recomposed at sensor rate. The gate+ * compares the smoothed heading against the last *emitted* one and drops+ * sub-degree jitter, while a real turn accumulates past it.+ */+class HeadingGateTest {++    @Test+    fun `the first reading always emits`() {+        assertEquals(Float.MAX_VALUE, headingDelta(null, 213f))+    }++    @Test+    fun `sub-degree jitter does not emit`() {+        // Settled sensor hovering around north: a tenth of a degree moves no pixel.+        assertTrue(headingDelta(90f, 90.4f) < 1.0f)+        assertTrue(headingDelta(90f, 89.6f) < 1.0f)+    }++    @Test+    fun `a real turn emits`() {+        assertTrue(headingDelta(90f, 92f) >= 1.0f)+        assertTrue(headingDelta(90f, 88f) >= 1.0f)+    }++    @Test+    fun `crossing north takes the short way round`() {+        // 359 to 1 is +2 degrees, not -358 — the gate must see a turn, not jitter.+        assertEquals(2f, headingDelta(359f, 1f), absoluteTolerance = 1e-3f)+        assertEquals(2f, headingDelta(1f, 359f), absoluteTolerance = 1e-3f)+        // And 359.9 to 0.1 is jitter, not a turn.+        assertTrue(headingDelta(359.9f, 0.1f) < 1.0f)+    }+}