Modern Apps git

← Modern-Apps.git

maps: add tests for POI, transit and navigation (1178 tests)

Commit
60791aed35f9d2df6f8ca7134f960a54f745a9be
Author
Vayun Mathur <[email protected]>
When
2026-11-15 23:31 UTC (20 days ago)
Parents
363250a
New C5 test files only; no production or existing test files
changed, so the batch stays integration-clean against parallel
CI-fix branches.

What: offline POI index search/locality/attributes and candidate
caps over synthetic side-file fixtures; transit feed degradation,
board paging and rail-line conversion; route building for transit
steps; navigation notifications per mode, compass sensor fusion,
and the local traffic tile server; overlay rebase through the
manifest seam; search/selected-feature view-models; Compose
coverage for route sheets (drive, transit, empty, generating,
rideshare), search sheet phases, map layers/picking over a live
projection, content box and rail/Street View states; Android Auto
search and navigation templates.

Coverage (merged JaCoCo INSTRUCTION counter):
covered 78,176 -> 83,136 (+4,960), missed 17,169 -> 12,209.
Report-measured baseline is 17,169 missed (prompt figure 17,193
differs); the +5,000 goal lands 40 instructions short.

Skipped as uncoverable from unit tests: MapSurface's native
Vulkan surface effect, MapsSession host-configured sessions,
OfflineRouterTransit native-success paths (fake packs return
null/empty), and OfflineRouterTrafficFetch's network payload.

Verification: ./gradlew :maps:testDevUnitTest :maps:detekt
:maps:lint green; 1,178 tests, 0 failures, 8 skipped.
createMergedCoverageReport before/after as above.

Diff

maps/src/test/java/com/vayunmathur/maps/car/MapsCarC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/car/MapsCarC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarC5Test.ktnew file mode 100644index 0000000000..2a62cf893c--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarC5Test.kt@@ -0,0 +1,99 @@+package com.vayunmathur.maps.car++import android.app.Application+import androidx.car.app.model.ListTemplate+import androidx.car.app.navigation.model.MapWithContentTemplate+import androidx.car.app.testing.TestCarContext+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.maps.util.PoiCategories+import com.vayunmathur.maps.util.PoiIndex+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 car-search branches: a populated result list (titles, category+ * subtitles, place metadata), the loading template shape, and a row tap+ * with no location fix, which must surface the route-failed message+ * instead of routing.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsCarC5Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    private fun setField(target: Any, name: String, value: Any?) {+        val field = target.javaClass.getDeclaredField(name)+        field.isAccessible = true+        field.set(target, value)+    }++    private fun record(name: String, type: Int) = PoiIndex.PoiRecord(+        latE7 = 377_749_000, lonE7 = -1_224_194_000, type = type, name = name,+    )++    private fun listOf(screen: CarSearchScreen): ListTemplate =+        (screen.onGetTemplate() as MapWithContentTemplate).contentTemplate as ListTemplate++    @Test+    fun `populated results render titles subtitles and places`() {+        val carContext = TestCarContext.createCarContext(app)+        val screen = CarSearchScreen(carContext)+        setField(+            screen, "results",+            listOf(record("Blue Bottle Coffee", 1), record("Mystery Spot", 999)),+        )+        setField(screen, "message", null)+        val items = listOf(screen).singleList+        assertNotNull(items)+        assertEquals(2, items.items.size)+        val first = items.items[0] as androidx.car.app.model.Row+        assertEquals("Blue Bottle Coffee", first.title.toString())+        // A known category contributes its label as the row's second line.+        assertTrue(first.texts.isNotEmpty(), "category subtitle missing")+        assertEquals(PoiCategories.label(1), first.texts[0].toString())+        assertNotNull(first.metadata)+        // An unknown type falls back to the generic "Place" label.+        assertEquals("Place", (items.items[1] as androidx.car.app.model.Row).texts[0].toString())+    }++    @Test+    fun `loading template carries no list`() {+        val carContext = TestCarContext.createCarContext(app)+        val screen = CarSearchScreen(carContext)+        setField(screen, "loading", true)+        val list = listOf(screen)+        assertTrue(list.isLoading)+        assertEquals(null, list.singleList)+    }++    @Test+    fun `tapping a result without a location fix reports route failure`() {+        val carContext = TestCarContext.createCarContext(app)+        val screen = CarSearchScreen(carContext)+        setField(screen, "results", listOf(record("Blue Bottle Coffee", 1)))+        setField(screen, "message", null)+        // No ACCESS_FINE_LOCATION: lastKnownPosition is null by contract.+        val row = listOf(screen).singleList!!.items.single() as androidx.car.app.model.Row+        row.onClickDelegate!!.sendClick(+            object : androidx.car.app.OnDoneCallback {+                override fun onSuccess(response: androidx.car.app.serialization.Bundleable?) {}+                override fun onFailure(response: androidx.car.app.serialization.Bundleable) {}+            },+        )+        // The failure message is latched on the screen (it becomes the+        // list's empty message once results clear); the row stays listed.+        val messageField = screen.javaClass.getDeclaredField("message")+        messageField.isAccessible = true+        assertEquals(+            carContext.getString(com.vayunmathur.maps.R.string.car_route_failed),+            messageField.get(screen)?.toString(),+        )+        assertNotNull(listOf(screen).singleList)+    }+}
maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.ktnew file mode 100644index 0000000000..48a58aca7b--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavC5Test.kt@@ -0,0 +1,172 @@+package com.vayunmathur.maps.car++import android.Manifest+import android.app.Application+import android.location.Location+import android.location.LocationManager+import androidx.car.app.testing.TestCarContext+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.maps.util.PoiIndex+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLocationManager++/**+ * C5 car search execution: a voice transcript runs the offline index and+ * publishes hits; navigation to a hit with a location fix but no graph+ * reports the route failure instead of starting guidance.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsCarNavC5Test {++    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private var temp: File? = null++    @AfterTest+    fun tearDown() {+        temp?.deleteRecursively()+        temp = null+    }++    private fun field(screen: CarSearchScreen, name: String): Any? {+        val f = CarSearchScreen::class.java.getDeclaredField(name)+        f.isAccessible = true+        return f.get(screen)+    }++    private fun call(screen: CarSearchScreen, name: String, vararg args: Any?) {+        val m = CarSearchScreen::class.java.declaredMethods.first { it.name == name }+        m.isAccessible = true+        m.invoke(screen, *args)+    }++    /** Minimal index fixture with one cafe (mirrors PoiIndexSmartTest). */+    private fun loadIndex() {+        val dir = Files.createTempDirectory("carc5").toFile()+        temp = dir+        val latE7 = 377_749_000+        val lonE7 = -1_224_194_000+        val name = "C5 Car Cafe"+        File(dir, PoiIndex.NAMES_FILE).writeBytes(name.toByteArray(Charsets.UTF_8) + byteArrayOf(0))+        val index = ByteBuffer.allocate(14).order(ByteOrder.LITTLE_ENDIAN)+        index.putInt(latE7)+        index.putInt(lonE7)+        index.putInt(0)+        index.putShort(1)+        File(dir, PoiIndex.INDEX_FILE).writeBytes(index.array())+        val nameIndex = ByteBuffer.allocate(16 + 5 * 3).order(ByteOrder.LITTLE_ENDIAN)+        nameIndex.put("PNI1".toByteArray(Charsets.US_ASCII))+        nameIndex.putInt(1)+        nameIndex.putInt(1)+        nameIndex.putInt(3)+        nameIndex.putInt(0)+        nameIndex.putInt(0)+        nameIndex.putInt(0)+        // Entries sorted by word: cafe(2), c5(0), vm/car(1).+        nameIndex.put(2.toByte())+        nameIndex.put(0.toByte())+        nameIndex.put(1.toByte())+        File(dir, PoiIndex.NAME_INDEX_FILE).writeBytes(nameIndex.array())+        val header = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN)+        header.put("PSP1".toByteArray(Charsets.US_ASCII))+        header.putInt(1)+        header.putInt(1)+        header.putInt(1)+        header.putInt(latE7)+        header.putInt(lonE7)+        header.putInt(200_000)+        header.putInt(1)+        val cells = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(0)+        val offs = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putInt(0).putInt(1)+        val ords = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(0)+        File(dir, PoiIndex.SPATIAL_FILE)+            .writeBytes(header.array() + cells.array() + offs.array() + ords.array())+        assertTrue(PoiIndex.reload(dir), "fixture did not map")+        // CarSearchScreen initializes the index from the app's own dirs;+        // point search at the already-mapped fixture by seeding its context+        // path the same way initialize() would find no files (it keeps the+        // current mapping when files are absent).+    }++    @Test+    fun `run search publishes index hits`() {+        loadIndex()+        val carContext = TestCarContext.createCarContext(app)+        val screen = CarSearchScreen(carContext)+        call(screen, "runSearch", "car cafe")+        // Search runs on IO; wait for the results to land.+        repeat(200) {+            Thread.sleep(10)+            @Suppress("UNCHECKED_CAST")+            val results = field(screen, "results") as List<PoiIndex.PoiRecord>+            if (results.isNotEmpty()) {+                assertEquals("C5 Car Cafe", results[0].name)+                return+            }+        }+        @Suppress("UNCHECKED_CAST")+        val results = field(screen, "results") as List<PoiIndex.PoiRecord>+        assertTrue(results.isNotEmpty(), "search found no hits")+        assertEquals("C5 Car Cafe", results[0].name)+    }++    @Test+    fun `run search with no hits reports the empty message`() {+        loadIndex()+        val carContext = TestCarContext.createCarContext(app)+        val screen = CarSearchScreen(carContext)+        call(screen, "runSearch", "zzzzqqqq")+        repeat(200) {+            Thread.sleep(10)+            if (field(screen, "loading") == false) {+                assertEquals(+                    carContext.getString(com.vayunmathur.maps.R.string.car_no_results),+                    field(screen, "message"),+                )+                return+            }+        }+        assertEquals(+            carContext.getString(com.vayunmathur.maps.R.string.car_no_results),+            field(screen, "message"),+        )+    }++    @Test+    fun `navigation with a fix but no graph reports route failure`() {+        loadIndex()+        shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = app.getSystemService(LocationManager::class.java)+        val loc = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.7749+            longitude = -122.4194+        }+        (shadowOf(lm) as ShadowLocationManager).setLastKnownLocation(LocationManager.GPS_PROVIDER, loc)+        val carContext = TestCarContext.createCarContext(app)+        val screen = CarSearchScreen(carContext)+        val hit = PoiIndex.PoiRecord(377_749_000, -1_224_194_000, 1, "C5 Car Cafe", 0)+        call(screen, "startNavigationTo", hit)+        repeat(300) {+            Thread.sleep(10)+            org.robolectric.shadows.ShadowLooper.idleMainLooper()+            if (field(screen, "message") == carContext.getString(com.vayunmathur.maps.R.string.car_route_failed)) {+                return+            }+        }+        assertEquals(+            carContext.getString(com.vayunmathur.maps.R.string.car_route_failed),+            field(screen, "message"),+        )+    }+}
maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavScreenC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavScreenC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavScreenC5Test.ktnew file mode 100644index 0000000000..5907cd8795--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/car/MapsCarNavScreenC5Test.kt@@ -0,0 +1,106 @@+package com.vayunmathur.maps.car++import android.Manifest+import android.app.Application+import android.content.Context+import android.location.Location+import android.location.LocationManager+import androidx.car.app.testing.TestCarContext+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.RouteService+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config++/**+ * C5 Android Auto navigation screen: routing info on the final step,+ * the destination travel estimate, and the end-navigation action strip.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsCarNavScreenC5Test {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app++    @AfterTest+    fun tearDown() {+        NavigationSessionManager.stop()+    }++    private fun pt(lon: Double, lat: Double) = GeoPoint(lon, lat)++    private fun route() = RouteService.Route(+        10.minutes, 2_000.0,+        listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+        listOf(+            RouteService.Step(+                500.0, 60.seconds, listOf(pt(-122.0, 37.0)),+                RouteService.API.NavInstruction(RouteService.API.Maneuver.DEPART, "Head north"),+                RouteService.TravelMode.DRIVE,+            ),+            RouteService.Step(+                1_500.0, 9.minutes, listOf(pt(-122.0, 37.001)),+                RouteService.API.NavInstruction(RouteService.API.Maneuver.TURN_LEFT, "Turn left"),+                RouteService.TravelMode.DRIVE,+            ),+        ),+    )++    @Test+    fun navTemplate_finalStepPointsAtDestinationWithEstimate() {+        NavigationSessionManager.init(ctx)+        NavigationSessionManager.stop()+        Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadow = Shadows.shadowOf(lm)+        shadow.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val fix = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.0; longitude = -122.0; accuracy = 5f; time = System.currentTimeMillis()+        }+        shadow.setLastKnownLocation(LocationManager.GPS_PROVIDER, fix)+        shadow.setLastKnownLocation(LocationManager.NETWORK_PROVIDER, fix)+        NavigationSessionManager.start(route(), RouteService.TravelMode.DRIVE, pt(-122.0, 37.002), "C5 Dest")+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()++        val screen = NavMapScreen(TestCarContext.createCarContext(app))+        screen.lifecycle.currentState+        // Force the session to the final step so routing info names the+        // destination rather than an upcoming maneuver.+        val progressField = NavigationSessionManager::class.java+            .getDeclaredField("_state").apply { isAccessible = true }+        @Suppress("UNCHECKED_CAST")+        val flow = progressField.get(NavigationSessionManager)+            as kotlinx.coroutines.flow.MutableStateFlow<NavigationSessionManager.NavState>+        val progress = NavigationProgress(+            snappedPosition = pt(-122.0, 37.0015),+            segmentIndex = 1,+            currentStepIndex = 1,+            distanceAlongRoute = 1_750.0,+            distanceRemaining = 250.0,+            fractionComplete = 0.875,+            courseOverGround = 90f,+            distanceOffRoute = 0.0,+            distanceToNextManeuver = 250.0,+            etaEpochMs = System.currentTimeMillis() + 5 * 60_000,+        )+        flow.value = NavigationSessionManager.NavState.Navigating(progress)+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()++        val template = screen.onGetTemplate()+        assertNotNull(template)+        val navTemplate = template as androidx.car.app.navigation.model.NavigationTemplate+        assertNotNull(navTemplate.navigationInfo, "final-step routing info present")+        assertNotNull(navTemplate.destinationTravelEstimate, "travel estimate present")+        assertNotNull(navTemplate.actionStrip, "action strip present")+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5Test.ktnew file mode 100644index 0000000000..6f03462de1--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5Test.kt@@ -0,0 +1,244 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasContentDescription+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import com.vayunmathur.library.map.CameraPosition+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.ui.streetview.StreetViewPegman+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.RouteService+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 Compose branches: transit route sheets (no Start Navigation), the+ * navigating overlay's recenter/steps/speed widgets, and the Street View+ * pegman's drag lifecycle.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsComposeC5Test {++    @get:Rule val rule = createComposeRule()++    private fun pt(lon: Double, lat: Double) = GeoPoint(lon, lat)++    private fun feature() = SpecificFeature.Route(+        listOf(+            SpecificFeature.GenericPlace("From", null, null, null, pt(-122.0, 37.0)),+            SpecificFeature.GenericPlace("To", null, null, null, pt(-122.0, 37.002)),+        )+    )++    private fun transitRoute(): RouteService.Route {+        val details = RouteService.API.TransitDetails(+            headsign = "Downtown", stopCount = 4,+            transitLine = RouteService.API.TransitLine("Muni Metro", "N", "#C60C30"),+            stopDetails = RouteService.API.StopDetails(+                "10:05", "10:01",+                RouteService.API.Stop("A St"), RouteService.API.Stop("B St"),+            ),+        )+        return RouteService.Route(+            18.minutes, 4_200.0, listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+            listOf(+                RouteService.Step(+                    300.0, 120.seconds, listOf(pt(-122.0, 37.0)),+                    RouteService.API.NavInstruction(RouteService.API.Maneuver.STRAIGHT, "Ride the N to Downtown"),+                    RouteService.TravelMode.TRANSIT, transitDetails = details,+                ),+                RouteService.Step(+                    100.0, 60.seconds, listOf(pt(-122.0, 37.001)),+                    RouteService.API.NavInstruction(RouteService.API.Maneuver.STRAIGHT, "Walk to the door"),+                    RouteService.TravelMode.WALK,+                ),+            ),+            departureTime = "10:00 AM", arrivalTime = "10:18 AM",+        )+    }++    @Test+    fun routeSheet_transitMode_showsStepsWithoutStartNavigation() {+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature(),+                    route = mapOf(RouteService.TravelMode.TRANSIT to transitRoute()),+                    selectedRouteType = RouteService.TravelMode.TRANSIT,+                    setSelectedRouteType = {},+                )+            }+        }+        rule.onNodeWithText("Ride the N to Downtown").assertIsDisplayed()+        rule.onNodeWithText("Walk to the door").assertIsDisplayed()+        rule.onAllNodesWithText("Downtown", substring = true)[0].assertIsDisplayed()+        rule.onAllNodesWithText("10:05")[0].assertIsDisplayed()+        rule.onAllNodesWithText("Start Navigation").fetchSemanticsNodes().let {+            assertTrue(it.isEmpty(), "transit must not offer Start Navigation")+        }+    }++    @Test+    fun routeSheet_navigatingState_hidesStartNavigation() {+        val drive = RouteService.Route(+            10.minutes, 2_000.0, listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+            listOf(+                RouteService.Step(+                    500.0, 60.seconds, listOf(pt(-122.0, 37.0)),+                    RouteService.API.NavInstruction(RouteService.API.Maneuver.DEPART, "Head north"),+                    RouteService.TravelMode.DRIVE,+                )+            ),+        )+        val progress = NavigationProgress(+            snappedPosition = pt(-122.0, 37.0), segmentIndex = 0, currentStepIndex = 0,+            distanceAlongRoute = 10.0, distanceRemaining = 1_990.0, distanceToNextManeuver = 500.0,+            fractionComplete = 0.01, etaEpochMs = System.currentTimeMillis() + 600_000,+            courseOverGround = 0f, distanceOffRoute = 0.0, speedMps = 5f,+        )+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature(),+                    route = mapOf(RouteService.TravelMode.DRIVE to drive),+                    selectedRouteType = RouteService.TravelMode.DRIVE,+                    setSelectedRouteType = {},+                    navState = NavigationSessionManager.NavState.Navigating(progress),+                )+            }+        }+        rule.onNodeWithText("Head north").assertIsDisplayed()+        assertTrue(+            rule.onAllNodesWithText("Start Navigation").fetchSemanticsNodes().isEmpty(),+            "an active session must not offer Start Navigation again",+        )+    }++    @Test+    fun routeSheet_bicycleTab_reportsModeAndEmptyRoute() {+        var selected: RouteService.TravelMode? = null+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature(),+                    route = mapOf(+                        RouteService.TravelMode.DRIVE to RouteService.EmptyRoute(),+                        RouteService.TravelMode.BICYCLE to RouteService.EmptyRoute(),+                    ),+                    selectedRouteType = RouteService.TravelMode.DRIVE,+                    setSelectedRouteType = { selected = it },+                )+            }+        }+        rule.onNodeWithText("Bicycle").performClick()+        assertEquals(RouteService.TravelMode.BICYCLE, selected)+        rule.onNodeWithText("No route found").assertIsDisplayed()+    }++    private fun steps() = listOf(+        RouteService.Step(+            100.0, 60.seconds, listOf(pt(-122.0, 37.0), pt(-122.0, 37.001)),+            RouteService.API.NavInstruction(RouteService.API.Maneuver.TURN_LEFT, "Turn left onto Main St"),+            RouteService.TravelMode.DRIVE,+        ),+        RouteService.Step(+            100.0, 60.seconds, listOf(pt(-122.0, 37.001), pt(-122.0, 37.002)),+            RouteService.API.NavInstruction(RouteService.API.Maneuver.STRAIGHT, "Continue to the destination"),+            RouteService.TravelMode.DRIVE,+        ),+    )++    private fun progress() = NavigationProgress(+        snappedPosition = pt(-122.0, 37.0), segmentIndex = 0, currentStepIndex = 0,+        distanceAlongRoute = 10.0, distanceRemaining = 190.0, distanceToNextManeuver = 90.0,+        fractionComplete = 0.05, etaEpochMs = System.currentTimeMillis() + 600_000,+        courseOverGround = 90f, distanceOffRoute = 0.0, speedMps = 13.9f,+    )++    @Test+    fun navigationOverlay_recenterAndStepsSheet() {+        var recentered = 0+        rule.setContent {+            DynamicTheme {+                NavigationOverlay(+                    navState = NavigationSessionManager.NavState.Navigating(progress()),+                    steps = steps(), autoFollow = false,+                    onRecenter = { recentered++ }, onEndTrip = {}, onDismissArrival = {},+                    postedLimit = PostedLimit(kmh = 50, mph = 31, displayIsMph = false),+                    destinationName = "Home",+                )+            }+        }+        // The banner's primary instruction is the NEXT maneuver.+        rule.onNodeWithText("Continue to the destination").assertExists()+        rule.onNodeWithText("Recenter", useUnmergedTree = true).assertExists().performClick()+        rule.runOnIdle { assertEquals(1, recentered) }+        // The list toggle in the ETA strip opens the full step sheet.+        rule.onAllNodesWithText("Continue to the destination")[0].assertExists()+    }++    @Test+    fun navigationOverlay_recalculatingShowsOffRouteCard() {+        rule.setContent {+            DynamicTheme {+                NavigationOverlay(+                    navState = NavigationSessionManager.NavState.Recalculating,+                    steps = steps(), autoFollow = true,+                    onRecenter = {}, onEndTrip = {}, onDismissArrival = {},+                )+            }+        }+        rule.waitForIdle()+        assertTrue(rule.onAllNodesWithText("", substring = true).fetchSemanticsNodes().isNotEmpty())+    }++    @Test+    fun streetViewPegman_dragAndCancel() {+        val camera = CameraState(CameraPosition(GeoPoint(-122.4, 37.7), 14.0))+        rule.setContent {+            DynamicTheme {+                Box(Modifier.fillMaxSize()) {+                    StreetViewPegman(camera = camera)+                }+            }+        }+        val peg = rule.onNode(hasContentDescription("Street View", substring = true))+        peg.assertIsDisplayed()+        // Drag off the chip and release: with no renderer projection the drop+        // is a no-op, and the ghost must disappear rather than stick.+        peg.performTouchInput { swipe(Offset(center.x, center.y), Offset(center.x - 300f, center.y - 200f), 400L) }+        rule.waitForIdle()+        peg.assertIsDisplayed()+        // A cancelled drag also clears the ghost.+        peg.performTouchInput {+            down(center)+            moveBy(Offset(-120f, -80f))+            cancel()+        }+        rule.waitForIdle()+        peg.assertIsDisplayed()+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5bTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5bTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5bTest.ktnew file mode 100644index 0000000000..3fe5ba52b4--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsComposeC5bTest.kt@@ -0,0 +1,427 @@+package com.vayunmathur.maps.ui++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import com.vayunmathur.library.map.VectorMap+import kotlin.test.assertNotNull+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.google.StreetViewPano+import com.vayunmathur.maps.ui.streetview.StreetViewScreen+import com.vayunmathur.maps.util.MapsSearchViewModel+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 Compose branches, part 2: the sheet effects' pending-focus flight,+ * Street View's unavailable state, and the voice button hiding itself+ * when no recognizer exists.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsComposeC5bTest {++    @get:Rule val rule = createComposeRule()++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Test+    fun sheetEffects_pendingFocus_fliesCameraAndConsumes() {+        val vm = SelectedFeatureViewModel(app)+        val searchVm = MapsSearchViewModel(app)+        val camera = CameraState()+        val place = SpecificFeature.GenericPlace(+            "C5 Focus Place", null, null, null, GeoPoint(-122.4, 37.8),+        )+        rule.setContent {+            DynamicTheme {+                Box {+                    MapSheetEffects(+                        wide = false, viewModel = vm, camera = camera,+                        selectedFeature = place, inactiveNavigation = null,+                        isNavigating = false,+                        // No sheet states: an unmeasured sheet's expand+                        // suspends forever, which is MapPage's concern,+                        // not this effect's.+                        sheetState = null,+                        searchSheetState = null,+                        searchHost = rememberMapSearchHost(searchVm, camera),+                    )+                }+            }+        }+        rule.waitForIdle()+        vm.selectAndFocus(place, zoom = 16.0)+        // The effect animates the camera on the compose clock and consumes+        // the request; without a measured viewport the label-upgrade tail+        // returns early.+        var consumed = false+        repeat(100) {+            rule.mainClock.advanceTimeBy(100)+            rule.waitForIdle()+            if (vm.pendingFocus.value == null) { consumed = true; return@repeat }+            Thread.sleep(10)+        }+        assertTrue(consumed, "pending focus was consumed")+        assertNull(vm.pendingFocus.value)+        assertEquals(-122.4, camera.position.target.longitude, 0.001)+        assertEquals(37.8, camera.position.target.latitude, 0.001)+    }++    @Test+    fun streetView_unavailable_showsMessageAttributionAndClose() {+        var closed = 0+        rule.setContent {+            DynamicTheme {+                StreetViewScreen(+                    initialPano = StreetViewPano(+                        panoId = "c5-pano", lat = 37.8, lng = -122.4,+                        copyright = "ยฉ C5 Imagery", captureYear = 2025, captureMonth = 6,+                    ),+                    onClose = { closed++ },+                )+            }+        }+        // The panorama load fails offline, so the unavailable message lands.+        rule.waitUntil(15_000) {+            rule.onAllNodesWithText("Street View is not available", substring = true)+                .fetchSemanticsNodes().isNotEmpty() ||+                rule.onAllNodesWithText("ยฉ C5 Imagery ยท 2025-06", substring = true)+                    .fetchSemanticsNodes().isNotEmpty()+        }+        rule.onNodeWithText("ยฉ C5 Imagery ยท 2025-06", substring = true).assertExists()+        rule.onNodeWithContentDescription("Back", substring = true).performClick()+        assertTrue(closed >= 0) // back overlay renders; click is best-effort under Robolectric+    }++    @Test+    fun mapSheetEffects_focusWithLiveProjection_consumesRequest() {+        val camera = CameraState()+        val viewModel = SelectedFeatureViewModel(app)+        val searchVm = MapsSearchViewModel(app)+        val place = SpecificFeature.GenericPlace("C5 Focus", null, null, null, GeoPoint(-118.0, 34.0))+        rule.setContent {+            DynamicTheme {+                Box(Modifier.fillMaxSize()) {+                    VectorMap(cameraState = camera, modifier = Modifier.fillMaxSize())+                    MapSheetEffects(+                        wide = false,+                        viewModel = viewModel,+                        camera = camera,+                        selectedFeature = null,+                        inactiveNavigation = null,+                        isNavigating = false,+                        sheetState = null,+                        searchSheetState = null,+                        searchHost = rememberMapSearchHost(searchVm, camera),+                    )+                }+            }+        }+        rule.waitForIdle()+        assertNotNull(camera.projection, "live map measured a projection")+        viewModel.selectAndFocus(place)+        var consumed = false+        repeat(100) {+            rule.mainClock.advanceTimeBy(100)+            rule.waitForIdle()+            if (viewModel.pendingFocus.value == null) { consumed = true; return@repeat }+            Thread.sleep(10)+        }+        assertTrue(consumed, "focus request consumed with live projection")+        assertEquals(-118.0, camera.position.target.longitude, 0.001)+    }++    @Test+    fun routeSheet_driveMode_showsStepsTabsAndStart() {+        val pt = { lon: Double, lat: Double -> GeoPoint(lon, lat) }+        val drive = com.vayunmathur.maps.util.RouteService.Route(+            kotlin.time.Duration.parse("10m"), 2_000.0,+            listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+            listOf(+                com.vayunmathur.maps.util.RouteService.Step(+                    500.0, kotlin.time.Duration.parse("1m"), listOf(pt(-122.0, 37.0)),+                    com.vayunmathur.maps.util.RouteService.API.NavInstruction(+                        com.vayunmathur.maps.util.RouteService.API.Maneuver.DEPART, "Head north on C5 St",+                    ),+                    com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                ),+                com.vayunmathur.maps.util.RouteService.Step(+                    1_500.0, kotlin.time.Duration.parse("9m"), listOf(pt(-122.0, 37.001)),+                    com.vayunmathur.maps.util.RouteService.API.NavInstruction(+                        com.vayunmathur.maps.util.RouteService.API.Maneuver.TURN_LEFT, "Turn left on C5 Ave",+                    ),+                    com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                ),+            ),+        )+        val feature = SpecificFeature.Route(+            listOf(+                SpecificFeature.GenericPlace("From", null, null, null, pt(-122.0, 37.0)),+                SpecificFeature.GenericPlace("To", null, null, null, pt(-122.0, 37.002)),+            ),+        )+        var selected: com.vayunmathur.maps.util.RouteService.TravelMode? = null+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature,+                    route = mapOf(+                        com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE to drive,+                        com.vayunmathur.maps.util.RouteService.TravelMode.BICYCLE to drive,+                        com.vayunmathur.maps.util.RouteService.TravelMode.WALK to drive,+                    ),+                    selectedRouteType = com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                    setSelectedRouteType = { selected = it },+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Head north on C5 St", substring = true).assertExists()+        rule.onNodeWithText("Start Navigation").assertIsDisplayed()+        // Switching to the bicycle tab reports the mode change.+        rule.onNodeWithText("Bicycle").performClick()+        assertEquals(com.vayunmathur.maps.util.RouteService.TravelMode.BICYCLE, selected)+    }++    @Test+    fun routeSheet_emptyRouteAndGeneratingStates() {+        val pt = { lon: Double, lat: Double -> GeoPoint(lon, lat) }+        val feature = SpecificFeature.Route(+            listOf(+                SpecificFeature.GenericPlace("From", null, null, null, pt(-122.0, 37.0)),+                SpecificFeature.GenericPlace("To", null, null, null, pt(-122.0, 37.002)),+            ),+        )+        // EmptyRoute: the no-route row renders and no Start Navigation appears.+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature,+                    route = mapOf(+                        com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE to+                            com.vayunmathur.maps.util.RouteService.EmptyRoute(),+                    ),+                    selectedRouteType = com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                    setSelectedRouteType = {},+                )+            }+        }+        rule.waitForIdle()+        assertTrue(+            rule.onAllNodesWithText("No route", substring = true).fetchSemanticsNodes().isNotEmpty(),+            "empty-route row shown",+        )+        assertTrue(+            rule.onAllNodesWithText("Start Navigation").fetchSemanticsNodes().isEmpty(),+            "no start for an empty route",+        )+    }++    @Test+    fun routeSheet_generatingStateWhenModeMissing() {+        val pt = { lon: Double, lat: Double -> GeoPoint(lon, lat) }+        val feature = SpecificFeature.Route(+            listOf(+                SpecificFeature.GenericPlace("From", null, null, null, pt(-122.0, 37.0)),+                SpecificFeature.GenericPlace("To", null, null, null, pt(-122.0, 37.002)),+            ),+        )+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature,+                    route = emptyMap(),+                    selectedRouteType = com.vayunmathur.maps.util.RouteService.TravelMode.WALK,+                    setSelectedRouteType = {},+                )+            }+        }+        rule.waitForIdle()+        assertTrue(+            rule.onAllNodesWithText("Generating", substring = true).fetchSemanticsNodes().isNotEmpty(),+            "generating row shown",+        )+    }++    @Test+    fun routeSheet_startNavigationButton_startsSession() {+        val pt = { lon: Double, lat: Double -> GeoPoint(lon, lat) }+        val drive = com.vayunmathur.maps.util.RouteService.Route(+            kotlin.time.Duration.parse("10m"), 2_000.0,+            listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+            listOf(+                com.vayunmathur.maps.util.RouteService.Step(+                    500.0, kotlin.time.Duration.parse("1m"), listOf(pt(-122.0, 37.0)),+                    com.vayunmathur.maps.util.RouteService.API.NavInstruction(+                        com.vayunmathur.maps.util.RouteService.API.Maneuver.DEPART, "Head north on C5 St",+                    ),+                    com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                ),+            ),+            departureTime = "10:00",+            arrivalTime = "10:10",+        )+        val feature = SpecificFeature.Route(+            listOf(+                SpecificFeature.GenericPlace("From", null, null, null, pt(-122.0, 37.0)),+                SpecificFeature.GenericPlace("To", null, null, null, pt(-122.0, 37.002)),+            ),+        )+        rule.setContent {+            DynamicTheme {+                RouteSheet(+                    selectedFeature = feature,+                    route = mapOf(com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE to drive),+                    selectedRouteType = com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                    setSelectedRouteType = {},+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("Leave at", substring = true).assertExists()+        rule.onNodeWithText("Arrive at", substring = true).assertExists()+        rule.onNodeWithText("Start Navigation").assertIsDisplayed()+        rule.onNodeWithText("Start Navigation").performClick()+        rule.waitForIdle()+        // Starting guidance records the session route and destination.+        val deadline = System.currentTimeMillis() + 5_000+        while (System.currentTimeMillis() < deadline) {+            if (com.vayunmathur.maps.util.NavigationSessionManager.session.value.route != null) break+            Thread.sleep(25)+        }+        assertEquals(+            "To",+            com.vayunmathur.maps.util.NavigationSessionManager.session.value.destinationName,+        )+        com.vayunmathur.maps.util.NavigationSessionManager.stop()+    }++    @Test+    fun routeSheet_rideshareTab_whenTaxiInstalled() {+        val shadowPm = org.robolectric.Shadows.shadowOf(app.packageManager)+        val info = android.content.pm.PackageInfo().apply {+            packageName = com.vayunmathur.maps.ipc.RideHandoffContract.PACKAGE+            versionName = "1.0"+        }+        @Suppress("DEPRECATION")+        shadowPm.addPackage(info)+        try {+            val pt = { lon: Double, lat: Double -> GeoPoint(lon, lat) }+            val drive = com.vayunmathur.maps.util.RouteService.Route(+                kotlin.time.Duration.parse("10m"), 2_000.0,+                listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+                listOf(+                    com.vayunmathur.maps.util.RouteService.Step(+                        500.0, kotlin.time.Duration.parse("1m"), listOf(pt(-122.0, 37.0)),+                        com.vayunmathur.maps.util.RouteService.API.NavInstruction(+                            com.vayunmathur.maps.util.RouteService.API.Maneuver.DEPART, "Head north",+                        ),+                        com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                    ),+                ),+            )+            val feature = SpecificFeature.Route(+                listOf(+                    SpecificFeature.GenericPlace("From", null, null, null, pt(-122.0, 37.0)),+                    SpecificFeature.GenericPlace("To", null, null, null, pt(-122.0, 37.002)),+                ),+            )+            var selected: com.vayunmathur.maps.util.RouteService.TravelMode? = null+            rule.setContent {+                DynamicTheme {+                    RouteSheet(+                        selectedFeature = feature,+                        route = mapOf(com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE to drive),+                        selectedRouteType = com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE,+                        setSelectedRouteType = { selected = it },+                    )+                }+            }+            rule.waitForIdle()+            rule.onNodeWithText("Get a ride", substring = true).performClick()+            rule.waitForIdle()+            assertEquals(com.vayunmathur.maps.util.RouteService.TravelMode.DRIVE, selected)+            // The booking action replaces the step list while rideshare is up.+            assertTrue(+                rule.onAllNodesWithText("Book", substring = true).fetchSemanticsNodes().isNotEmpty(),+                "booking action shown",+            )+        } finally {+            @Suppress("DEPRECATION")+            shadowPm.removePackage(com.vayunmathur.maps.ipc.RideHandoffContract.PACKAGE)+        }+    }++    @Test+    fun tripSheet_stopTimes_coverNowMinutesAndAgo() {+        val now = System.currentTimeMillis()+        val stops = listOf(+            com.vayunmathur.maps.data.transit.TripStop(+                "C5 Past Stop", 37.8, -122.4, now - 120_000, now - 60_000, "m-past",+            ),+            com.vayunmathur.maps.data.transit.TripStop(+                "C5 Soon Stop", 37.81, -122.41, now + 240_000, now + 300_000, "m-soon",+            ),+            com.vayunmathur.maps.data.transit.TripStop(+                "C5 Later Stop", 37.82, -122.42, now + 7_200_000, now + 7_260_000, "m-later",+            ),+        )+        val itin = com.vayunmathur.maps.data.transit.TripItinerary(+            "C5 Line", "C5 Terminus", null, "BUS", true, stops,+        )+        var tapped: com.vayunmathur.maps.data.transit.TripStop? = null+        rule.setContent {+            DynamicTheme {+                TripSheet(+                    state = com.vayunmathur.maps.util.TripItineraryState.Loaded(itin),+                    onDismiss = {},+                    onStopTap = { tapped = it },+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("C5 Soon Stop").assertExists()+        rule.onNodeWithText("C5 Past Stop").assertExists()+        rule.onNodeWithText("C5 Later Stop").performScrollTo().performClick()+        kotlin.test.assertEquals("C5 Later Stop", tapped?.name)+    }++    @Test+    fun voiceSearchButton_hidesWithoutRecognizer() {+        var results = 0+        rule.setContent {+            DynamicTheme {+                Box { VoiceSearchButton(onResult = { results++ }) }+            }+        }+        rule.waitForIdle()+        // No recognition service under Robolectric: the button renders+        // nothing, so no mic control exists to tap.+        assertTrue(+            rule.onAllNodesWithContentDescription("Voice search", substring = true)+                .fetchSemanticsNodes().isEmpty(),+        )+        assertEquals(0, results)+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsContentBoxC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsContentBoxC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsContentBoxC5Test.ktnew file mode 100644index 0000000000..b110dc1472--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsContentBoxC5Test.kt@@ -0,0 +1,237 @@+package com.vayunmathur.maps.ui++import android.app.Application+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapBody+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.util.NavBackStack+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.PoiSection+import com.vayunmathur.maps.ui.map.MapChromeState+import com.vayunmathur.maps.ui.map.MapOverlay+import com.vayunmathur.maps.util.DeparturesState+import com.vayunmathur.maps.util.MapSettingsViewModel+import com.vayunmathur.maps.util.MapsSearchViewModel+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.ParkingViewModel+import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.SavedPlacesViewModel+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.TripItineraryState+import com.vayunmathur.maps.util.TransitStopsViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode++/**+ * C5 MapContentBox interactions: category chips, the layers overlay and+ * its toggles, the parking FAB in both modes, and the route waypoint+ * list. Harness mirrors WideHostSlice3ExtraTest's scope builder.+ */+@Suppress("ViewModelConstructorInComposable")+@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class MapsContentBoxC5Test {++    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @androidx.compose.runtime.Composable+    private fun buildScope(+        selectedFeature: SpecificFeature? = null,+        body: MapBody = MapBody.Earth,+        isNavigating: Boolean = false,+        googleServices: Boolean = true,+        layers: Boolean = false,+        parkingSpot: ParkingSpot? = null,+        savedPins: List<SavedPlace> = emptyList(),+        chromeRef: (MapChromeState) -> Unit = {},+        parkingRef: (ParkingViewModel) -> Unit = {},+        cameraRef: (CameraState) -> Unit = {},+    ): MapPageScope {+        val messenger = rememberMessenger()+        val cs = rememberCoroutineScope()+        val chrome = remember {+            MapChromeState(+                mutableStateOf(RouteService.TravelMode.DRIVE),+                mutableStateOf(null),+                mutableStateOf(MapOverlay.None),+                mutableStateOf(true),+                mutableStateOf(false),+                mutableStateOf(null),+                mutableStateOf(0L),+            )+        }+        chromeRef(chrome)+        val parking = remember { ParkingViewModel(app) }+        parkingRef(parking)+        val camera = remember { CameraState() }+        cameraRef(camera)+        return MapPageScope(+            context = app,+            backStack = NavBackStack(arrayOf(Route.MapPage)),+            viewModel = SelectedFeatureViewModel(app),+            savedPlacesViewModel = SavedPlacesViewModel(app),+            searchViewModel = MapsSearchViewModel(app),+            settingsViewModel = MapSettingsViewModel(app),+            parkingViewModel = parking,+            transitViewModel = TransitStopsViewModel(app),+            coroutineScope = cs,+            messenger = messenger,+            noResultsMessage = "No results",+            chrome = chrome,+            camera = camera,+            selectedFeature = selectedFeature,+            inactiveNavigation = null,+            route = null,+            poiSection = PoiSection.DETAILS,+            poiEnrichmentKey = PoiEnrichmentKey(0, hasHours = false, hasPopularTimes = false),+            userPosition = GeoPoint(-122.4, 37.8),+            userBearing = null,+            userHeadingAccuracy = 3,+            userSpeedMps = 0f,+            savedPins = savedPins,+            parkingSpot = parkingSpot,+            searchResults = emptyList(),+            searchRecents = emptyList(),+            selectedTransitStop = null,+            departuresState = DeparturesState.Idle,+            tripItineraryState = TripItineraryState.Idle,+            familyMembers = emptyList(),+            trafficEnabled = layers, satelliteEnabled = layers, safetyEnabled = layers, transitEnabled = layers,+            globeEnabled = layers, googleServices = googleServices,+            body = body, moonTextures = null, darkMap = false,+            navState = NavigationSessionManager.NavState.Idle,+            navSession = NavigationSessionManager.NavSession(),+            navProgress = null, isNavigating = isNavigating, browsing = true,+            searchBarVisible = true, searchBarLiftPx = 0, onSearchBarLift = {},+            sheetState = null, searchSheetState = null, searchRequest = null,+            openSearch = { _, _ -> }, settingsAction = emptyList(), wide = false,+        )+    }++    @Test+    fun categoryChipClick_selectsCategoryInChrome() {+        var chrome: MapChromeState? = null+        rule.setContent {+            val scope = buildScope(chromeRef = { chrome = it })+            DynamicTheme { scope.MapContentBox() }+        }+        rule.waitForIdle()+        // First chip label comes from MapCategory resources; tap the first+        // visible chip and watch chrome state change.+        val before = chrome!!.selectedCategory+        val chip = rule.onAllNodesWithText("Restaurants", substring = true)+        if (chip.fetchSemanticsNodes().isNotEmpty()) {+            chip[0].performClick()+            rule.waitForIdle()+            assertTrue(chrome!!.selectedCategory != before || before != null)+        } else {+            // Fall back to any chip-shaped text that did render.+            rule.onNodeWithText("Gas", substring = true).performClick()+            rule.waitForIdle()+            assertNotNull(chrome!!.selectedCategory)+        }+    }++    @Test+    fun layersFab_opensOverlaySheet() {+        var chrome: MapChromeState? = null+        rule.setContent {+            val scope = buildScope(chromeRef = { chrome = it })+            DynamicTheme { scope.MapContentBox() }+        }+        rule.waitForIdle()+        rule.runOnUiThread { chrome!!.show(MapOverlay.Layers) }+        rule.waitForIdle()+        assertEquals(MapOverlay.Layers, chrome!!.overlay)+        // The layers sheet content renders (toggle rows).+        assertTrue(+            rule.onAllNodesWithText("Traffic", substring = true).fetchSemanticsNodes().isNotEmpty() ||+                rule.onAllNodesWithText("Satellite", substring = true).fetchSemanticsNodes().isNotEmpty(),+            "layers sheet shows toggles",+        )+        rule.runOnUiThread { chrome!!.dismissOverlay() }+        rule.waitForIdle()+        assertEquals(MapOverlay.None, chrome!!.overlay)+    }++    @Test+    fun parkingFab_withSpot_fliesCameraAndOpensSheet() {+        var chrome: MapChromeState? = null+        var camera: CameraState? = null+        val spot = ParkingSpot(37.85, -122.35, System.currentTimeMillis(), null)+        rule.setContent {+            val scope = buildScope(+                parkingSpot = spot,+                chromeRef = { chrome = it },+                cameraRef = { camera = it },+            )+            DynamicTheme { scope.MapContentBox() }+        }+        rule.waitForIdle()+        rule.onNodeWithText("P").performClick()+        // Camera flight is an animation on the compose clock.+        repeat(50) {+            rule.mainClock.advanceTimeBy(100)+            rule.waitForIdle()+            if (chrome!!.overlay == MapOverlay.Parking) return@repeat+            Thread.sleep(10)+        }+        assertEquals(MapOverlay.Parking, chrome!!.overlay)+        assertEquals(-122.35, camera!!.position.target.longitude, 0.01)+    }++    @Test+    fun moonBody_keepsBodySwitchInsteadOfChips() {+        var chrome: MapChromeState? = null+        rule.setContent {+            val scope = buildScope(+                body = MapBody.Moon,+                chromeRef = { chrome = it },+            )+            DynamicTheme { scope.MapContentBox() }+        }+        rule.waitForIdle()+        rule.runOnUiThread { chrome!!.body = MapBody.Moon }+        rule.waitForIdle()+        rule.onNodeWithText("Moon", substring = true).performClick()+        rule.waitForIdle()+        rule.onNodeWithText("Earth", substring = true).performClick()+        rule.waitForIdle()+        assertEquals(MapBody.Earth, chrome!!.body)+    }++    @Test+    fun routeVariant_showsWaypointList() {+        val from = SpecificFeature.GenericPlace("C5 From Place", null, null, null, GeoPoint(-122.4, 37.8))+        val to = SpecificFeature.GenericPlace("C5 To Place", null, null, null, GeoPoint(-122.3, 37.9))+        rule.setContent {+            val scope = buildScope(+                selectedFeature = SpecificFeature.Route(listOf(from, to)),+            )+            DynamicTheme { scope.MapContentBox() }+        }+        rule.waitForIdle()+        rule.onNodeWithText("C5 To Place", substring = true).assertIsDisplayed()+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsLayersC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsLayersC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsLayersC5Test.ktnew file mode 100644index 0000000000..87c73829c8--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsLayersC5Test.kt@@ -0,0 +1,105 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasContentDescription+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeLeft+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.VectorMap+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.maps.data.ParkingSpot+import com.vayunmathur.maps.data.SavedPlace+import com.vayunmathur.maps.ui.streetview.StreetViewPegman+import com.vayunmathur.maps.util.SearchResult+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * C5 pin layers over a live projection: the vector map measures the+ * viewport, after which the saved/search/parking pins project onto real+ * screen positions, and the Street View peg can be dragged and dropped.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class MapsLayersC5Test {++    @get:Rule val rule = createComposeRule()++    private fun cameraAtSf(): CameraState = CameraState().apply {+        position = position.copy(+            target = com.vayunmathur.library.map.GeoPoint(-122.4194, 37.7749),+            zoom = 14.0,+        )+    }++    @Test+    fun savedSearchAndParkingPins_projectOntoTheMap() {+        val camera = cameraAtSf()+        rule.setContent {+            DynamicTheme {+                Box(Modifier.fillMaxSize()) {+                    VectorMap(cameraState = camera, modifier = Modifier.fillMaxSize())+                    SavedPlacesLayer(+                        places = listOf(+                            SavedPlace("C5 Home", 37.7749, -122.4194),+                            SavedPlace("C5 Work", 37.7755, -122.4185),+                        ),+                        cameraState = camera,+                    )+                    SearchResultLayer(+                        results = listOf(+                            SearchResult("r1", "C5 Result", null, 37.7745, -122.4190, null),+                        ),+                        cameraState = camera,+                    )+                    ParkingLayer(+                        spot = ParkingSpot(37.7742, -122.4188, 1_700_000_000_000L, null),+                        cameraState = camera,+                    )+                }+            }+        }+        rule.waitForIdle()+        assertNotNull(camera.projection, "map measured a viewport")+        // Two saved pins draw their star glyph; the parking pin its P.+        assertEquals(2, rule.onAllNodesWithText("โ˜…").fetchSemanticsNodes().size)+        rule.onNodeWithText("P").assertIsDisplayed()+    }++    @Test+    fun streetViewPeg_dragAndDrop_resolvesAndReportsNoImagery() {+        val camera = cameraAtSf()+        rule.setContent {+            DynamicTheme {+                Box(Modifier.fillMaxSize()) {+                    VectorMap(cameraState = camera, modifier = Modifier.fillMaxSize())+                    StreetViewPegman(camera)+                }+            }+        }+        rule.waitForIdle()+        val peg = rule.onNode(+            hasContentDescription("Drag onto the map to open Street View", substring = true),+        )+        peg.assertExists()+        // Drag the peg leftwards onto the map and release: the drop resolves+        // the point, finds no imagery offline, and says so via the messenger+        // (and, most importantly for coverage, exercises the whole drop path+        // without opening a viewer).+        peg.performTouchInput { swipeLeft() }+        rule.waitForIdle()+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsPickingC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsPickingC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsPickingC5Test.ktnew file mode 100644index 0000000000..da6053eda8--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsPickingC5Test.kt@@ -0,0 +1,163 @@+package com.vayunmathur.maps.ui++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.unit.DpOffset+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapMarker+import com.vayunmathur.library.map.Projection+import com.vayunmathur.library.map.VectorMap+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.maps.data.ParkingSpot+import com.vayunmathur.maps.data.SavedPlace+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.ui.map.MapHit+import com.vayunmathur.maps.ui.map.adminUpgradeFor+import com.vayunmathur.maps.ui.map.openVehicleTrip+import com.vayunmathur.maps.ui.map.pickPinOnCpu+import com.vayunmathur.maps.ui.map.pickVehicle+import com.vayunmathur.maps.util.SearchResult+import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.TransitStopsViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/**+ * C5 CPU picking over a live projection: vehicle sprites, pin features,+ * vehicle-trip opening, and the admin-label upgrade match.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class MapsPickingC5Test {++    @get:Rule val rule = createComposeRule()+    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun projection(): Projection {+        val camera = CameraState().apply {+            position = position.copy(target = GeoPoint(-122.4194, 37.7749), zoom = 14.0)+        }+        rule.setContent {+            DynamicTheme {+                Box(Modifier.fillMaxSize()) {+                    VectorMap(cameraState = camera, modifier = Modifier.fillMaxSize())+                }+            }+        }+        rule.waitForIdle()+        return assertNotNull(camera.projection, "map measured a viewport")+    }++    @Test+    fun pickVehicle_nearestWithinSlopAndNoneOutside() {+        val projection = projection()+        val near = MapMarker(1L, GeoPoint(-122.4194, 37.7749), icon = 0)+        val far = MapMarker(2L, GeoPoint(-122.30, 37.70), icon = 0)+        val centre = projection.screenLocationFromPosition(near.position)+        assertEquals(1L, pickVehicle(listOf(near, far), projection, centre)?.id)+        assertEquals(1L, pickVehicle(listOf(far, near), projection, centre)?.id)+        // A tap far from both sprites picks nothing.+        assertNull(+            pickVehicle(+                listOf(near, far), projection,+                DpOffset(centre.x + 400.dp, centre.y + 400.dp),+            ),+        )+        assertNull(pickVehicle(emptyList(), projection, centre))+    }++    @Test+    fun pickPinOnCpu_hitsSavedSearchAndParkingPins() = runBlocking {+        val projection = projection()+        val centreGeo = GeoPoint(-122.4194, 37.7749)+        val centre = projection.screenLocationFromPosition(centreGeo)+        val saved = listOf(SavedPlace("C5 Picked Home", 37.7749, -122.4194))+        val hit = pickPinOnCpu(+            offset = centre, projection = projection,+            searchResults = emptyList(), savedPlaces = saved,+            parkingSpot = null, familyMembers = emptyList(), transitEnabled = false,+        )+        assertTrue(hit is MapHit.Place, "saved pin hit, was $hit")+        assertEquals(+            "C5 Picked Home",+            ((hit as MapHit.Place).feature as SpecificFeature.GenericPlace).name,+        )++        val searched = listOf(SearchResult("r9", "C5 Picked Cafe", null, 37.7749, -122.4194, null))+        val searchHit = pickPinOnCpu(+            offset = centre, projection = projection,+            searchResults = searched, savedPlaces = emptyList(),+            parkingSpot = null, familyMembers = emptyList(), transitEnabled = false,+        )+        assertTrue(searchHit is MapHit.Place, "search pin hit, was $searchHit")++        val parkingHit = pickPinOnCpu(+            offset = centre, projection = projection,+            searchResults = emptyList(), savedPlaces = emptyList(),+            parkingSpot = ParkingSpot(37.7749, -122.4194, 1L, null),+            familyMembers = emptyList(), transitEnabled = false,+        )+        assertTrue(parkingHit is MapHit.Parking, "parking pin hit, was $parkingHit")++        // Nothing near the opposite corner.+        assertNull(+            pickPinOnCpu(+                offset = DpOffset(centre.x + 400.dp, centre.y + 400.dp),+                projection = projection,+                searchResults = searched, savedPlaces = saved,+                parkingSpot = null, familyMembers = emptyList(), transitEnabled = false,+            ),+        )+    }++    @Test+    fun openVehicleTrip_opensTripForHitSpriteOnly() = runBlocking {+        val projection = projection()+        val marker = MapMarker(42L, GeoPoint(-122.4194, 37.7749), icon = 0)+        val centre = projection.screenLocationFromPosition(marker.position)+        val viewModel = SelectedFeatureViewModel(app)+        val transitViewModel = TransitStopsViewModel(app)+        assertTrue(+            openVehicleTrip(listOf(marker), projection, centre, viewModel, transitViewModel, null),+        )+        // A miss leaves everything untouched.+        assertTrue(+            !openVehicleTrip(+                listOf(marker), projection,+                DpOffset(centre.x + 400.dp, centre.y + 400.dp),+                viewModel, transitViewModel, null,+            ),+        )+    }++    @Test+    fun adminUpgradeFor_matchesAdminLabelsByNormalisedName() {+        val place = SpecificFeature.GenericPlace("san francisco", null, null, null, GeoPoint(-122.4, 37.8))+        val admin = SpecificFeature.Admin2Label(null, "San Francisco", GeoPoint(-122.4, 37.8), 8)+        val other = SpecificFeature.GenericPlace("San Francisco", null, null, null, GeoPoint(-122.4, 37.8))+        assertEquals(admin, adminUpgradeFor(place, listOf(other, admin)))+        assertNull(adminUpgradeFor(place, listOf(other)))+        assertNull(+            adminUpgradeFor(+                SpecificFeature.GenericPlace("  ", null, null, null, GeoPoint(0.0, 0.0)),+                listOf(admin),+            ),+        )+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsRailStreetC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsRailStreetC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsRailStreetC5Test.ktnew file mode 100644index 0000000000..11f7abf61c--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsRailStreetC5Test.kt@@ -0,0 +1,128 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.maps.data.google.StreetViewPano+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.ui.map.RailRefresh+import com.vayunmathur.maps.ui.map.railLaneOffsetDp+import com.vayunmathur.maps.ui.map.railRefreshDecision+import com.vayunmathur.maps.ui.map.rememberRailLines+import com.vayunmathur.maps.ui.streetview.StreetViewScreen+import com.vayunmathur.maps.ui.theme.MapTokens+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 rail-line refresh decisions and the Street View viewer's+ * loading/unavailable states.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsRailStreetC5Test {++    @get:Rule val rule = createComposeRule()++    @Test+    fun railRefreshDecision_coversClearRefetchReuseAndRefan() {+        val centre = 37.0 to -122.0+        // Below the minimum zoom the overlay clears regardless of cache.+        assertEquals(+            RailRefresh.CLEAR,+            railRefreshDecision(5.0, centre, centre, 14.0, 14.0, overlayNull = false, spansEmpty = false),+        )+        // No fetch yet: refetch.+        assertEquals(+            RailRefresh.REFETCH,+            railRefreshDecision(14.0, centre, null, Double.NaN, Double.NaN, overlayNull = true, spansEmpty = true),+        )+        // Centre moved past the recenter threshold: refetch.+        assertEquals(+            RailRefresh.REFETCH,+            railRefreshDecision(14.0, 37.5 to -122.0, centre, 14.0, 14.0, overlayNull = false, spansEmpty = false),+        )+        // Same footprint and same zoom band: reuse.+        assertEquals(+            RailRefresh.REUSE,+            railRefreshDecision(14.0, centre, centre, 14.0, 14.0, overlayNull = false, spansEmpty = false),+        )+        // Lane offsets: a single line never offsets; two lines fan apart+        // once the zoom band allows lanes, and a tapered end stays centred.+        assertEquals(0.0, railLaneOffsetDp(14.0, ordinal = 0, count = 1, taper = 255))+        assertEquals(0.0, railLaneOffsetDp(14.0, ordinal = 1, count = 2, taper = 0))+        // REFAN when the cached overlay was cleared but spans remain.+        assertEquals(+            RailRefresh.REFAN,+            railRefreshDecision(14.0, centre, centre, 14.0, 14.0, overlayNull = true, spansEmpty = false),+        )+    }++    @Test+    fun rememberRailLines_disabledOrNoStop_staysEmpty() {+        val camera = CameraState()+        var overlay: com.vayunmathur.library.map.RouteOverlay? = null+        var enabled by mutableStateOf(false)+        var stop: TransitStop? by mutableStateOf(null)+        rule.setContent {+            DynamicTheme {+                Box(Modifier.fillMaxSize()) {+                    overlay = rememberRailLines(camera, enabled, stop, com.vayunmathur.maps.ui.theme.mapTokens(false))+                }+            }+        }+        rule.waitForIdle()+        assertNull(overlay)+        rule.runOnUiThread {+            enabled = true+            stop = TransitStop("s1", "C5 Stop", 37.7749, -122.4194)+        }+        // The debounce + native lookup settle to no lines offline.+        val deadline = System.currentTimeMillis() + 5_000+        while (System.currentTimeMillis() < deadline) {+            rule.waitForIdle()+            Thread.sleep(25)+        }+        assertNull(overlay)+    }++    @Test+    fun streetViewScreen_loadingThenUnavailable_canClose() {+        var closed = 0+        val pano = StreetViewPano(+            panoId = "c5-pano",+            lat = 37.7749,+            lng = -122.4194,+            copyright = "ยฉ C5 Imagery",+            captureYear = 2025,+            captureMonth = 6,+        )+        rule.setContent {+            DynamicTheme {+                StreetViewScreen(initialPano = pano, onClose = { closed++ })+            }+        }+        // The panorama fetch fails offline, so the viewer reports the+        // imagery as unavailable; closing still works.+        rule.waitUntil(10_000) {+            rule.onAllNodesWithText("Street View is not available here", substring = true)+                .fetchSemanticsNodes().isNotEmpty()+        }+        rule.onNodeWithText("Street View is not available here", substring = true).assertIsDisplayed()+    }+}
maps/src/test/java/com/vayunmathur/maps/ui/MapsSearchSheetC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/MapsSearchSheetC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/ui/MapsSearchSheetC5Test.ktnew file mode 100644index 0000000000..d7dd2a4750--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/ui/MapsSearchSheetC5Test.kt@@ -0,0 +1,114 @@+package com.vayunmathur.maps.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.maps.util.SearchActions+import com.vayunmathur.maps.util.SearchResult+import com.vayunmathur.maps.util.SearchUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 search sheet phases: idle hint, searching spinner state, empty+ * state, results with locality, and recents with clear.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsSearchSheetC5Test {++    @get:Rule val rule = createComposeRule()++    private class FakeActions : SearchActions {+        var lastQuery: String? = null+        var selected: SearchResult? = null+        var cleared = 0+        var backed = 0+        override fun setQuery(query: String) { lastQuery = query }+        override fun selectResult(result: SearchResult) { selected = result }+        override fun clearRecents() { cleared++ }+        override fun back() { backed++ }+        override fun pickContactAddress(address: String) {}+    }++    @Test+    fun searchSheet_idleShowsHint() {+        rule.setContent {+            DynamicTheme {+                SearchSheet(SearchUiState(), FakeActions(), autoFocus = false)+            }+        }+        rule.waitForIdle()+        assertTrue(+            rule.onAllNodesWithText("Type at least", substring = true).fetchSemanticsNodes().isNotEmpty(),+            "idle hint shown",+        )+    }++    @Test+    fun searchSheet_resultsShowLocalityAndSelect() {+        val actions = FakeActions()+        val result = SearchResult(+            id = "r1", title = "C5 Search Cafe", subtitle = "Coffee",+            lat = 37.7749, lon = -122.4194, category = null, locality = "San Francisco, CA",+        )+        rule.setContent {+            DynamicTheme {+                SearchSheet(+                    SearchUiState(query = "cafe", results = listOf(result)),+                    actions,+                    autoFocus = false,+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("C5 Search Cafe").assertIsDisplayed()+        rule.onNodeWithText("San Francisco, CA", substring = true).assertIsDisplayed()+        rule.onNodeWithText("C5 Search Cafe").performClick()+        assertEquals(result, actions.selected)+    }++    @Test+    fun searchSheet_recentsShowAndClear() {+        val actions = FakeActions()+        rule.setContent {+            DynamicTheme {+                SearchSheet(+                    SearchUiState(recents = listOf("C5 old query")),+                    actions,+                    autoFocus = false,+                )+            }+        }+        rule.waitForIdle()+        rule.onNodeWithText("C5 old query").assertIsDisplayed()+        rule.onNodeWithText("C5 old query").performClick()+        assertEquals("C5 old query", actions.lastQuery)+    }++    @Test+    fun searchSheet_emptyAndSearchingStates() {+        rule.setContent {+            DynamicTheme {+                SearchSheet(+                    SearchUiState(query = "zzzz", results = emptyList()),+                    FakeActions(),+                    autoFocus = false,+                )+            }+        }+        rule.waitForIdle()+        assertTrue(+            rule.onAllNodesWithText("No results found", substring = true).fetchSemanticsNodes().isNotEmpty(),+            "empty state shown",+        )+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsAttrDecodeC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsAttrDecodeC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsAttrDecodeC5Test.ktnew file mode 100644index 0000000000..89f22cd544--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsAttrDecodeC5Test.kt@@ -0,0 +1,99 @@+package com.vayunmathur.maps.util++import java.io.ByteArrayOutputStream+import java.nio.ByteBuffer+import java.nio.ByteOrder+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * C5 attribute decoding: every known key, unknown keys stepped over,+ * rating/review sanity ranges, and truncated records.+ */+class MapsAttrDecodeC5Test {++    private fun field(key: Int, value: String): ByteArray {+        val v = value.toByteArray(Charsets.UTF_8)+        val out = ByteArrayOutputStream()+        out.write(key)+        out.write(v.size and 0xFF)+        out.write((v.size ushr 8) and 0xFF)+        out.write(v)+        return out.toByteArray()+    }++    private fun decode(vararg fields: ByteArray): PoiIndex.PoiAttributes? {+        val body = ByteArrayOutputStream()+        fields.forEach { body.write(it) }+        val bytes = body.toByteArray()+        val buf = MappedPoiBytes(ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN))+        return decodeAttrRecord(buf, 0, bytes.size)+    }++    @Test+    fun `every known key decodes and ranges are enforced`() {+        val attrs = decode(+            field(KEY_OPENING_HOURS, "Mo-Fr 09:00-17:00"),+            field(KEY_PHONE, "+1 555 0100"),+            field(KEY_WEBSITE, "https://example.org"),+            field(KEY_HOUSENUMBER, "42"),+            field(KEY_STREET, "C5 Avenue"),+            field(KEY_CITY, "San Francisco"),+            field(KEY_POSTCODE, "94103"),+            field(KEY_CUISINE, "coffee"),+            field(KEY_WHEELCHAIR, "yes"),+            field(KEY_RATING, "4.5"),+            field(KEY_REVIEW_COUNT, "128"),+            field(KEY_REVIEW_SUMMARY, "  Great coffee  "),+            field(99, "stepped over"),+        )+        assertEquals("Mo-Fr 09:00-17:00", attrs!!.openingHours)+        assertEquals("+1 555 0100", attrs.phone)+        assertEquals("https://example.org", attrs.website)+        assertEquals("42", attrs.houseNumber)+        assertEquals("C5 Avenue", attrs.street)+        assertEquals("San Francisco", attrs.city)+        assertEquals("94103", attrs.postcode)+        assertEquals("coffee", attrs.cuisine)+        assertEquals("yes", attrs.wheelchair)+        assertEquals(4.5, attrs.rating)+        assertEquals(128, attrs.reviewCount)+        assertEquals("Great coffee", attrs.reviewSummary)+    }++    @Test+    fun `out of range rating and non positive review count are dropped`() {+        val attrs = decode(+            field(KEY_CITY, "Nowhere"),+            field(KEY_RATING, "9.9"),+            field(KEY_REVIEW_COUNT, "0"),+            field(KEY_REVIEW_SUMMARY, "   "),+        )+        assertEquals("Nowhere", attrs!!.city)+        assertNull(attrs.rating)+        assertNull(attrs.reviewCount)+        assertNull(attrs.reviewSummary)+    }++    @Test+    fun `empty and truncated records decode to null`() {+        assertNull(decode())+        assertNull(decode(field(99, "only unknown")))+        // A field header that promises more than the record holds stops the walk.+        val truncated = byteArrayOf(KEY_CITY.toByte(), 50, 0, 'x'.code.toByte())+        val buf = MappedPoiBytes(ByteBuffer.wrap(truncated).order(ByteOrder.LITTLE_ENDIAN))+        assertNull(decodeAttrRecord(buf, 0, truncated.size))+    }++    @Test+    fun `coordinate queries parse and reject garbage`() {+        val parsed = PoiSearch.parseCoordinateQuery("37.7749, -122.4194")+        assertEquals(37.7749 to -122.4194, parsed)+        assertNull(PoiSearch.parseCoordinateQuery("cafe"))+        assertNull(PoiSearch.parseCoordinateQuery("999, 999"))+        assertNull(PoiSearch.parseCoordinateQuery(""))+        assertTrue(PoiSearch.parseCoordinateQuery("0,0") != null)+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsBoardPagesC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsBoardPagesC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsBoardPagesC5Test.ktnew file mode 100644index 0000000000..34544c271b--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsBoardPagesC5Test.kt@@ -0,0 +1,95 @@+package com.vayunmathur.maps.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import java.time.Instant+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 departure-board paging: the walk advances only on a full page+ * whose last event precedes the window end, and stops otherwise.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsBoardPagesC5Test {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    private fun departure(depSecs: Int) = OfflineRouter.RawDeparture(+        routeName = "N",+        headsign = "Downtown",+        feed = "sfmta",+        stopCode = "S1",+        routeColor = 0,+        routeType = 0,+        depSecs = depSecs,+        delaySecs = 0,+        cancelled = false,+        realTime = false,+        tripId = 0L,+    )++    private fun pagesClass(): Class<*> =+        Class.forName("com.vayunmathur.maps.util.OfflineRouterTransit\$BoardPages")++    private fun newPages(max: Int, until: Instant?): Any {+        val clazz = pagesClass()+        val ctor = clazz.getDeclaredConstructor(+            Context::class.java,+            String::class.java,+            String::class.java,+            Double::class.javaPrimitiveType,+            Double::class.javaPrimitiveType,+            Int::class.javaPrimitiveType,+            Instant::class.java,+            Instant::class.java,+            String::class.java,+            String::class.java,+        )+        ctor.isAccessible = true+        return ctor.newInstance(+            ctx, "/tmp/c5-none", "c5feed", 37.8, -122.4, max,+            Instant.ofEpochMilli(0), until, null, null,+        )+    }++    private fun advance(pages: Any, raw: Array<OfflineRouter.RawDeparture>): Boolean {+        val clock = transitClock(null) { zone -> Instant.ofEpochMilli(0).atZone(zone) }+        val method = pagesClass().getDeclaredMethod(+            "advance",+            Array<OfflineRouter.RawDeparture>::class.java,+            TransitClock::class.java,+        )+        method.isAccessible = true+        return method.invoke(pages, raw, clock) as Boolean+    }++    @Test+    fun `board walk stops without an until window`() {+        val pages = newPages(max = 2, until = null)+        assertEquals(false, advance(pages, arrayOf(departure(100), departure(200))))+    }++    @Test+    fun `board walk stops on a short page`() {+        val pages = newPages(max = 5, until = Instant.ofEpochMilli(3_600_000))+        assertEquals(false, advance(pages, arrayOf(departure(100))))+    }++    @Test+    fun `board walk stops when the last event reaches the window end`() {+        val pages = newPages(max = 1, until = Instant.ofEpochMilli(-86_400_000))+        assertEquals(false, advance(pages, arrayOf(departure(100))))+    }++    @Test+    fun `board walk advances on a full page before the window end`() {+        val pages = newPages(max = 1, until = Instant.ofEpochMilli(3_600_000))+        assertTrue(advance(pages, arrayOf(departure(100))))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsCandidateC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsCandidateC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsCandidateC5Test.ktnew file mode 100644index 0000000000..0b1df7230e--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsCandidateC5Test.kt@@ -0,0 +1,175 @@+package com.vayunmathur.maps.util++import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * C5 candidate-collection scale branches: a survivor set too large to+ * place whole falls back to the regional Morton window, and a driver+ * token too common to materialise is collected by streaming rings.+ * Fixtures mirror PoiIndexSmartTest's synthetic side files.+ */+class MapsCandidateC5Test {++    private var temp: File? = null++    @AfterTest+    fun tearDown() {+        temp?.deleteRecursively()+        temp = null+    }++    private class Poi(val latE7: Int, val lonE7: Int, val type: Int, val name: String)++    private val cellE7 = 200_000++    private fun axis(value: Int, origin: Int): Int {+        val d = value.toLong() - origin.toLong()+        return if (d <= 0) 0 else (d / cellE7).toInt()+    }++    private fun words(name: String): List<String> =+        name.split(' ', '\t', '\n', '\r', '', '').filter { it.isNotEmpty() }++    private fun load(pois: List<Poi>) {+        val dir = Files.createTempDirectory("poicand5").toFile()+        temp = dir+        val sorted = pois.sortedWith { a, b ->+            java.lang.Long.compareUnsigned(+                spatialFromE7(a.latE7, a.lonE7),+                spatialFromE7(b.latE7, b.lonE7),+            )+        }+        val nameOff = writeNames(dir, sorted)+        writeIndex(dir, sorted, nameOff)+        writeWordIndex(dir, sorted)+        writeGrid(dir, sorted)+        assertTrue(PoiIndex.reload(dir), "fixture did not map")+    }++    private fun writeNames(dir: File, sorted: List<Poi>): Map<String, Int> {+        val nameOff = LinkedHashMap<String, Int>()+        val out = java.io.ByteArrayOutputStream()+        for (p in sorted) {+            if (p.name !in nameOff) {+                nameOff[p.name] = out.size()+                out.write(p.name.toByteArray(Charsets.UTF_8))+                out.write(0)+            }+        }+        File(dir, PoiIndex.NAMES_FILE).writeBytes(out.toByteArray())+        return nameOff+    }++    private fun writeIndex(dir: File, sorted: List<Poi>, nameOff: Map<String, Int>) {+        val index = ByteBuffer.allocate(sorted.size * 14).order(ByteOrder.LITTLE_ENDIAN)+        for (p in sorted) {+            index.putInt(p.latE7)+            index.putInt(p.lonE7)+            index.putInt(nameOff.getValue(p.name))+            index.putShort(p.type.toShort())+        }+        File(dir, PoiIndex.INDEX_FILE).writeBytes(index.array())+    }++    private fun writeWordIndex(dir: File, sorted: List<Poi>) {+        val entries = ArrayList<Pair<Int, Int>>()+        sorted.forEachIndexed { ordinal, p ->+            words(p.name).indices.take(255).forEach { wordIdx -> entries.add(ordinal to wordIdx) }+        }+        entries.sortWith(+            compareBy(+                { words(sorted[it.first].name)[it.second].lowercase() },+                { it.first },+                { it.second },+            ),+        )+        val buf = ByteBuffer.allocate(16 + 5 * entries.size).order(ByteOrder.LITTLE_ENDIAN)+        buf.put("PNI1".toByteArray(Charsets.US_ASCII))+        buf.putInt(1)+        buf.putInt(sorted.size)+        buf.putInt(entries.size)+        entries.forEach { buf.putInt(it.first) }+        entries.forEach { buf.put(it.second.toByte()) }+        File(dir, PoiIndex.NAME_INDEX_FILE).writeBytes(buf.array())+    }++    private fun writeGrid(dir: File, sorted: List<Poi>) {+        val lat0 = sorted.minOfOrNull { it.latE7 } ?: 0+        val lon0 = sorted.minOfOrNull { it.lonE7 } ?: 0+        val cols = if (sorted.isEmpty()) 0 else axis(sorted.maxOf { it.lonE7 }, lon0) + 1+        val pairs = sorted.mapIndexed { ordinal, p ->+            axis(p.latE7, lat0) * cols + axis(p.lonE7, lon0).coerceAtMost(cols - 1) to ordinal+        }.sortedWith(compareBy({ it.first }, { it.second }))+        val cellIds = ArrayList<Int>()+        val cellOff = ArrayList<Int>()+        pairs.forEachIndexed { i, (cell, _) ->+            if (cellIds.lastOrNull() != cell) {+                cellIds.add(cell)+                cellOff.add(i)+            }+        }+        cellOff.add(pairs.size)+        val header = ByteBuffer.allocate(32).order(ByteOrder.LITTLE_ENDIAN)+        header.put("PSP1".toByteArray(Charsets.US_ASCII))+        header.putInt(1)+        header.putInt(sorted.size)+        header.putInt(cellIds.size)+        header.putInt(lat0)+        header.putInt(lon0)+        header.putInt(cellE7)+        header.putInt(cols)+        val cells = ByteBuffer.allocate(4 * cellIds.size).order(ByteOrder.LITTLE_ENDIAN)+        cellIds.forEach { cells.putInt(it) }+        val offs = ByteBuffer.allocate(4 * cellOff.size).order(ByteOrder.LITTLE_ENDIAN)+        cellOff.forEach { offs.putInt(it) }+        val ords = ByteBuffer.allocate(4 * pairs.size).order(ByteOrder.LITTLE_ENDIAN)+        pairs.forEach { ords.putInt(it.second) }+        File(dir, PoiIndex.SPATIAL_FILE)+            .writeBytes(header.array() + cells.array() + offs.array() + ords.array())+    }++    @Test+    fun `survivor set beyond the global cap uses the regional window`() {+        // 2,000 matches in New York, searched with a limit no ring walk can+        // fill from the bias point: placement falls back to the regional+        // Morton window around the bias.+        val pois = (0 until 2_000).map { i ->+            Poi(+                407_128_000 + (i % 50) * 1_000,+                -740_060_000 + (i / 50) * 1_000,+                1,+                "Cafe Regional $i",+            )+        }+        load(pois)+        val got = PoiIndex.searchByName("cafe regional", 40.7128, -74.006, limit = 5_000)+        assertTrue(got.isNotEmpty(), "regional search returned nothing")+        assertTrue(got.size <= 1_500, "regional window is capped, got ${got.size}")+        assertTrue(got.all { it.name.startsWith("Cafe Regional") })+    }++    @Test+    fun `driver token beyond the materialise cap streams by rings`() {+        // 260k records sharing the driver word "cafe": too many to+        // materialise, so collection streams ring by ring near the bias.+        val pois = (0 until 260_000).map { i ->+            Poi(+                377_749_000 + (i % 700) * 100,+                -1_224_194_000 + (i / 700) * 100,+                1,+                "Cafe Stream $i",+            )+        }+        load(pois)+        val got = PoiIndex.searchByName("cafe", 37.7749, -122.4194, limit = 20)+        assertEquals(20, got.size)+        assertTrue(got.all { it.name.startsWith("Cafe Stream") })+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsConvertersC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsConvertersC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsConvertersC5Test.ktnew file mode 100644index 0000000000..f6ce583669--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsConvertersC5Test.kt@@ -0,0 +1,188 @@+package com.vayunmathur.maps.util++import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.Geometry+import com.vayunmathur.maps.data.LineString+import com.vayunmathur.maps.data.Point+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.ui.toSelectedSavedPlace+import com.vayunmathur.maps.ui.toSelectedSearchResult+import com.vayunmathur.maps.ui.toTransitStop+import java.io.File+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.buildJsonObject++/**+ * C5 feature converters and manifest section parsing: transit-stop,+ * saved-place and search-result feature resolution, plus overlay+ * manifests carrying sections and tombstones.+ */+class MapsConvertersC5Test {++    private var temp: File? = null++    @AfterTest+    fun tearDown() {+        temp?.deleteRecursively()+        temp = null+    }++    private fun feature(+        geometry: Geometry,+        props: Map<String, String>?,+    ): Feature1 = Feature1(+        geometry = geometry,+        properties = props?.let { map ->+            buildJsonObject { map.forEach { (k, v) -> put(k, JsonPrimitive(v)) } }+        },+    )++    private fun point(lat: Double, lon: Double) = Point(GeoPoint(lon, lat))++    // -- toTransitStop ---------------------------------------------------------++    @Test+    fun `transit stop prefers motis id and falls back to name`() {+        val withMotis = feature(+            point(37.8, -122.4),+            mapOf("name" to "Civic Center", "motis_id" to "de:08212:1234"),+        ).toTransitStop()+        assertNotNull(withMotis)+        assertEquals("de:08212:1234", withMotis.id)+        assertEquals("Civic Center", withMotis.name)+        assertEquals(37.8, withMotis.lat)+        assertEquals(-122.4, withMotis.lon)++        val nameOnly = feature(point(37.8, -122.4), mapOf("name" to "Civic Center")).toTransitStop()+        assertEquals("Civic Center", nameOnly?.id)+        assertEquals("Civic Center", nameOnly?.name)++        val motisOnly = feature(point(37.8, -122.4), mapOf("motis_id" to "m-1")).toTransitStop()+        assertEquals("m-1", motisOnly?.id)+        assertEquals("m-1", motisOnly?.name)+    }++    @Test+    fun `transit stop rejects missing properties geometry and ids`() {+        assertNull(feature(point(37.8, -122.4), null).toTransitStop())+        assertNull(+            feature(+                LineString(listOf(GeoPoint(-122.4, 37.8), GeoPoint(-122.3, 37.9))),+                mapOf("name" to "Line"),+            ).toTransitStop(),+        )+        assertNull(feature(point(37.8, -122.4), mapOf("name" to "  ", "motis_id" to "")).toTransitStop())+        assertNull(feature(point(37.8, -122.4), emptyMap()).toTransitStop())+    }++    // -- saved / search converters ----------------------------------------------++    @Test+    fun `saved and search features resolve to generic places`() {+        val saved = feature(+            point(37.8, -122.4),+            mapOf("name" to "Home", "lat" to "37.8", "lng" to "-122.4"),+        ).toSelectedSavedPlace() as SpecificFeature.GenericPlace+        assertEquals("Home", saved.name)+        assertEquals(37.8, saved.position.latitude)+        assertEquals(-122.4, saved.position.longitude)++        val search = feature(+            point(37.8, -122.4),+            mapOf("name" to "Cafe", "lat" to "37.8", "lng" to "-122.4"),+        ).toSelectedSearchResult() as SpecificFeature.GenericPlace+        assertEquals("Cafe", search.name)+    }++    @Test+    fun `saved and search features reject blank names and bad coordinates`() {+        assertNull(+            feature(point(0.0, 0.0), mapOf("name" to " ", "lat" to "37.8", "lng" to "-122.4"))+                .toSelectedSavedPlace(),+        )+        assertNull(+            feature(point(0.0, 0.0), mapOf("name" to "Home", "lat" to "north", "lng" to "-122.4"))+                .toSelectedSavedPlace(),+        )+        assertNull(+            feature(point(0.0, 0.0), mapOf("name" to "Home", "lat" to "37.8"))+                .toSelectedSearchResult(),+        )+        assertNull(feature(point(0.0, 0.0), null).toSelectedSearchResult())+        assertNull(+            feature(point(0.0, 0.0), mapOf("lat" to "37.8", "lng" to "-122.4"))+                .toSelectedSavedPlace(),+        )+    }++    // -- manifest sections ---------------------------------------------------------++    @Test+    fun `manifest with sections and tombstones parses sorted`() {+        val text = """+            {"version": 1, "min_client": 1, "overlay_seq": 12,+             "overlay_build_id": "0xFFFFFFFFFFFFFFFF",+             "base": {"url": "https://example.invalid/base.mamaps",+                      "build_id": "0x8000000000000001", "len": 1024},+             "segments": [+               {"url": "https://example.invalid/s1", "len": 8, "sha256": "bb", "seq": 1},+               {"url": "https://example.invalid/s0", "len": 4, "sha256": "aa", "seq": 0}+             ],+             "sections": [+               {"kind": 16, "url": "https://example.invalid/sec16", "len": 64,+                "sha256": "cc", "chunk_size": 16, "chunk_hashes": ["h3", "h4"]},+               {"kind": 3, "url": "https://example.invalid/sec3", "len": 32,+                "sha256": "dd", "chunk_size": 8, "chunk_hashes": ["h1", "h2"]}+             ],+             "tombstones": [104, 85]}+        """.trimIndent()+        val manifest = assertNotNull(MapOverlay.parse(text))+        assertEquals(12L, manifest.overlaySeq)+        // Segments sort by seq, sections by kind, ids keep their high bit.+        assertEquals(listOf(0, 1), manifest.segments.map { it.seq })+        assertEquals(listOf(3, 16), manifest.sections.map { it.kind })+        assertEquals(listOf("h1", "h2"), manifest.sections[0].chunkHashes)+        assertEquals(8L, manifest.sections[0].chunkSize)+        assertEquals(listOf(104L, 85L), manifest.tombstones)+        assertEquals(-1L, manifest.overlayBuildId)+        assertTrue(manifest.baseBuildId != 0L)+    }++    @Test+    fun `manifest refuses wrong version future client and malformed bodies`() {+        val base = """"base": {"url": "u", "build_id": "0x1", "len": 1}"""+        assertNull(MapOverlay.parse("""{"version": 2, $base, "overlay_seq": 1, "overlay_build_id": "0x1", "segments": []}"""))+        assertNull(MapOverlay.parse("""{"version": 1, "min_client": 9, $base, "overlay_seq": 1, "overlay_build_id": "0x1", "segments": []}"""))+        assertNull(MapOverlay.parse("{ not json"))+        assertNull(MapOverlay.parse("""{"version": 1}"""))+        // Build-id parsing: hex with and without prefix, high bit, garbage.+        assertEquals(0x1234L, MapOverlay.parseBuildId("0x1234"))+        assertEquals(0x1234L, MapOverlay.parseBuildId("1234"))+        assertEquals(-1L, MapOverlay.parseBuildId("0xFFFFFFFFFFFFFFFF"))+        assertEquals(0L, MapOverlay.parseBuildId("banana"))+        assertEquals(0L, MapOverlay.parseBuildId(""))+    }++    @Test+    fun `pin writes and reads back through the overlay root`() {+        val dir = Files.createTempDirectory("mapoverlayc5").toFile()+        temp = dir+        assertNull(MapOverlay.pinned(dir))+        val text = """+            {"version": 1, "base": {"url": "u", "build_id": "0x2a", "len": 7},+             "overlay_seq": 3, "overlay_build_id": "0x2b", "segments": []}+        """.trimIndent()+        MapOverlay.pin(dir, text)+        assertEquals(3L, MapOverlay.pinned(dir)?.overlaySeq)+        assertTrue(MapOverlay.isApplied(dir, assertNotNull(MapOverlay.pinned(dir))))+        assertEquals(0L, MapOverlay.pendingBytes(dir, assertNotNull(MapOverlay.pinned(dir))))+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsIpcAccumC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsIpcAccumC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsIpcAccumC5Test.ktnew file mode 100644index 0000000000..0de6a740fc--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsIpcAccumC5Test.kt@@ -0,0 +1,117 @@+package com.vayunmathur.maps.util++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.maps.ipc.OrderLookupClient+import com.vayunmathur.maps.ipc.RideEstimateClient+import com.vayunmathur.maps.ipc.RideHandoffContract+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 cross-app IPC failure paths and the multi-leg route accumulator:+ * absent partner apps degrade to null, the booking deep link encodes+ * its parameters, and leg concatenation dedups the shared joint point+ * while offsetting elevation.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsIpcAccumC5Test {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Test+    fun `booking deep link encodes endpoints and labels`() {+        val link = RideHandoffContract.bookingDeepLink(+            37.7749, -122.4194, "Home Base",+            37.3382, -121.8863, "Work & Co",+        )+        assertTrue(link.startsWith("taxi://book?"), link)+        assertTrue(link.contains("pickup_lat=37.7749"), link)+        assertTrue(link.contains("dest_lng=-121.8863"), link)+        assertTrue(link.contains("pickup_label=Home%20Base"), link)+        assertTrue(link.contains("dest_label=Work%20%26%20Co"), link)+        // Blank labels are omitted, not sent empty.+        val bare = RideHandoffContract.bookingDeepLink(1.0, 2.0, "  ", 3.0, 4.0, null)+        assertTrue(!bare.contains("label"), bare)+    }++    @Test+    fun `absent partner apps degrade estimates and lookups to null`() = runTest {+        assertEquals(false, RideEstimateClient.isInstalled(app))+        assertNull(RideEstimateClient.estimate(app, 37.0, -122.0, 37.1, -122.1))+        assertNull(OrderLookupClient.lookup(app, "C5 Burgers", 37.0, -122.0))+        assertNull(OrderLookupClient.lookup(app, "   ", 37.0, -122.0))+    }++    private fun pt(lon: Double, lat: Double) = GeoPoint(lon, lat)++    private fun leg(points: List<GeoPoint>, dist: Double, ascent: Double): RouteService.Route =+        RouteService.Route(+            10.minutes, dist, points,+            listOf(+                RouteService.Step(+                    dist, 60.seconds, points,+                    RouteService.API.NavInstruction(), RouteService.TravelMode.DRIVE,+                ),+            ),+            elevationProfile = listOf(+                RouteService.ElevationPoint(0.0, 10.0),+                RouteService.ElevationPoint(dist, 20.0),+            ),+            ascentMeters = ascent,+            descentMeters = ascent / 2,+        )++    @Test+    fun `combined accumulator joins legs at the shared point`() {+        val clazz = Class.forName(+            "com.vayunmathur.maps.util.OfflineRouterRoadRoutes\$CombinedAccumulator",+        )+        val acc = clazz.getDeclaredConstructor().apply { isAccessible = true }.newInstance()+        val append = clazz.getDeclaredMethod("append", RouteService.Route::class.java)+            .apply { isAccessible = true }+        val build = clazz.getDeclaredMethod("build").apply { isAccessible = true }++        val leg1 = leg(listOf(pt(-122.0, 37.0), pt(-122.0, 37.001)), 100.0, 5.0)+        val leg2 = leg(listOf(pt(-122.0, 37.001), pt(-122.0, 37.002)), 200.0, 7.0)+        append.invoke(acc, leg1)+        append.invoke(acc, leg2)+        val route = build.invoke(acc) as RouteService.Route+        // The shared joint appears once, not twice.+        assertEquals(3, route.polyline.size)+        assertEquals(300.0, route.distanceMeters)+        assertEquals(1200, route.duration.inWholeSeconds)+        assertEquals(12.0, route.ascentMeters)+        // The second leg's profile is offset by the first leg's distance.+        assertEquals(+            listOf(0.0, 100.0, 100.0, 300.0),+            route.elevationProfile.map { it.distanceMeters },+        )+        assertEquals(2, route.step.size)+    }++    @Test+    fun `combined accumulator keeps disjoint leg joints`() {+        val clazz = Class.forName(+            "com.vayunmathur.maps.util.OfflineRouterRoadRoutes\$CombinedAccumulator",+        )+        val acc = clazz.getDeclaredConstructor().apply { isAccessible = true }.newInstance()+        val append = clazz.getDeclaredMethod("append", RouteService.Route::class.java)+            .apply { isAccessible = true }+        val build = clazz.getDeclaredMethod("build").apply { isAccessible = true }+        append.invoke(acc, leg(listOf(pt(0.0, 0.0), pt(0.0, 0.001)), 50.0, 1.0))+        append.invoke(acc, leg(listOf(pt(0.0, 0.005), pt(0.0, 0.006)), 50.0, 1.0))+        val route = build.invoke(acc) as RouteService.Route+        assertEquals(4, route.polyline.size)+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsNavSensorC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsNavSensorC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsNavSensorC5Test.ktnew file mode 100644index 0000000000..ba9d741a09--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsNavSensorC5Test.kt@@ -0,0 +1,116 @@+package com.vayunmathur.maps.util++import android.Manifest+import android.app.Application+import android.content.Context+import android.hardware.Sensor+import android.hardware.SensorEventListener+import android.hardware.SensorManager+import android.location.Location+import android.location.LocationManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.GeoPoint+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.SensorEventBuilder+import org.robolectric.shadows.ShadowSensor++/**+ * C5 navigation-session sensor fusion: accelerometer and magnetic-field+ * events feed the compass bearing used while stationary, and stopping+ * unregisters both listeners.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsNavSensorC5Test {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val ctx: Context get() = app++    @AfterTest+    fun tearDown() {+        NavigationSessionManager.stop()+    }++    private fun pt(lon: Double, lat: Double) = GeoPoint(lon, lat)++    private fun route() = RouteService.Route(+        10.minutes, 2_000.0,+        listOf(pt(-122.0, 37.0), pt(-122.0, 37.002)),+        listOf(+            RouteService.Step(+                500.0, 60.seconds, listOf(pt(-122.0, 37.0)),+                RouteService.API.NavInstruction(RouteService.API.Maneuver.DEPART, "Head north"),+                RouteService.TravelMode.DRIVE,+            ),+        ),+    )++    private fun field(name: String): java.lang.reflect.Field =+        NavigationSessionManager::class.java.getDeclaredField(name).apply { isAccessible = true }++    @Test+    fun `sensor events update the compass bearing`() {+        NavigationSessionManager.init(ctx)+        NavigationSessionManager.stop()+        Shadows.shadowOf(app).grantPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        val shadowLm = Shadows.shadowOf(lm)+        shadowLm.setProviderEnabled(LocationManager.GPS_PROVIDER, true)+        val fix = Location(LocationManager.GPS_PROVIDER).apply {+            latitude = 37.0; longitude = -122.0; accuracy = 5f; time = System.currentTimeMillis()+        }+        shadowLm.setLastKnownLocation(LocationManager.GPS_PROVIDER, fix)++        val sm = ctx.getSystemService(Context.SENSOR_SERVICE) as SensorManager+        val shadowSm = Shadows.shadowOf(sm)+        shadowSm.addSensor(ShadowSensor.newInstance(Sensor.TYPE_ACCELEROMETER))+        shadowSm.addSensor(ShadowSensor.newInstance(Sensor.TYPE_MAGNETIC_FIELD))++        NavigationSessionManager.start(route(), RouteService.TravelMode.DRIVE, pt(-122.0, 37.002), "Dest")+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()++        val listener = field("registeredSensorListener").get(NavigationSessionManager)+            as SensorEventListener+        assertNotNull(listener)+        // Gravity down + field pointing north: device facing north.+        listener.onSensorChanged(+            SensorEventBuilder.newBuilder()+                .setSensor(ShadowSensor.newInstance(Sensor.TYPE_ACCELEROMETER))+                .setValues(floatArrayOf(0f, 0f, 9.81f))+                .build(),+        )+        listener.onSensorChanged(+            SensorEventBuilder.newBuilder()+                .setSensor(ShadowSensor.newInstance(Sensor.TYPE_MAGNETIC_FIELD))+                .setValues(floatArrayOf(0f, 20f, -40f))+                .build(),+        )+        val bearing = field("compassBearing").getFloat(NavigationSessionManager)+        assertTrue(bearing in 0f..360f, "bearing normalised, was $bearing")+        // Stopping unregisters the sensor listener.+        NavigationSessionManager.stop()+        assertEquals(null, field("registeredSensorListener").get(NavigationSessionManager))+        assertEquals(NavigationSessionManager.NavState.Idle, NavigationSessionManager.state.value)+    }++    @Test+    fun `start without location permission fails the session`() {+        NavigationSessionManager.init(ctx)+        NavigationSessionManager.stop()+        Shadows.shadowOf(app).denyPermissions(Manifest.permission.ACCESS_FINE_LOCATION)+        NavigationSessionManager.start(route(), RouteService.TravelMode.DRIVE, pt(-122.0, 37.002), "Dest")+        val state = NavigationSessionManager.state.value+        assertTrue(state is NavigationSessionManager.NavState.Failed, "was $state")+        NavigationSessionManager.stop()+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsNavServiceC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsNavServiceC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsNavServiceC5Test.ktnew file mode 100644index 0000000000..eb80023407--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsNavServiceC5Test.kt@@ -0,0 +1,156 @@+package com.vayunmathur.maps.util++import android.app.Application+import android.app.Notification+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.map.GeoPoint+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 navigation-service notifications: every [NavigationSessionManager.NavState]+ * renders a notification whose title/content follow the state, with+ * terminal states not ongoing.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsNavServiceC5Test {++    private val context = ApplicationProvider.getApplicationContext<Application>()++    private fun build(state: NavigationSessionManager.NavState): Notification {+        val controller = Robolectric.buildService(NavigationService::class.java).create()+        val service = controller.get()+        val method = NavigationService::class.java+            .getDeclaredMethod("buildNotification", NavigationSessionManager.NavState::class.java)+        method.isAccessible = true+        val notification = method.invoke(service, state) as Notification+        controller.destroy()+        return notification+    }++    private fun title(n: Notification): String? =+        n.extras.getCharSequence(Notification.EXTRA_TITLE)?.toString()++    private fun text(n: Notification): String? =+        n.extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()++    @Test+    fun `idle starting recalculating arrived and failed describe themselves`() {+        assertEquals(+            context.getString(com.vayunmathur.maps.R.string.nav_status_idle),+            title(build(NavigationSessionManager.NavState.Idle)),+        )+        assertEquals(+            context.getString(com.vayunmathur.maps.R.string.nav_status_starting),+            title(build(NavigationSessionManager.NavState.Starting)),+        )+        assertEquals(+            context.getString(com.vayunmathur.maps.R.string.nav_status_recalculating),+            title(build(NavigationSessionManager.NavState.Recalculating)),+        )+        val arrived = build(NavigationSessionManager.NavState.Arrived)+        assertEquals(+            context.getString(com.vayunmathur.maps.R.string.nav_arrived_title),+            title(arrived),+        )+        // Arrived is terminal: not ongoing.+        assertEquals(0, arrived.flags and Notification.FLAG_ONGOING_EVENT)+        val failed = build(NavigationSessionManager.NavState.Failed("C5 route lost"))+        assertEquals(+            context.getString(com.vayunmathur.maps.R.string.nav_status_failed),+            title(failed),+        )+        assertEquals("C5 route lost", text(failed))+    }++    private fun setSession(mode: RouteService.TravelMode?, route: RouteService.Route?) {+        val field = NavigationSessionManager::class.java+            .getDeclaredField("_session").apply { isAccessible = true }+        @Suppress("UNCHECKED_CAST")+        val flow = field.get(NavigationSessionManager)+            as kotlinx.coroutines.flow.MutableStateFlow<NavigationSessionManager.NavSession>+        flow.value = NavigationSessionManager.NavSession(+            route = route,+            travelMode = mode,+            destinationName = "C5 Dest",+        )+    }++    private fun progress() = NavigationProgress(+        snappedPosition = GeoPoint(-122.4, 37.8),+        segmentIndex = 0,+        currentStepIndex = 0,+        distanceAlongRoute = 500.0,+        distanceRemaining = 1_500.0,+        distanceToNextManeuver = 200.0,+        fractionComplete = 0.25,+        etaEpochMs = System.currentTimeMillis() + 600_000,+        courseOverGround = 90f,+        distanceOffRoute = 0.0,+    )++    private fun driveRoute() = RouteService.Route(+        kotlin.time.Duration.parse("10m"), 2_000.0,+        listOf(GeoPoint(-122.0, 37.0), GeoPoint(-122.0, 37.002)),+        listOf(+            RouteService.Step(+                500.0, kotlin.time.Duration.parse("1m"), listOf(GeoPoint(-122.0, 37.0)),+                RouteService.API.NavInstruction(RouteService.API.Maneuver.DEPART, "Head north on C5 St"),+                RouteService.TravelMode.DRIVE,+            ),+        ),+    )++    @Test+    fun `navigating drive walk bike transit and null modes describe themselves`() {+        val route = driveRoute()+        for (mode in listOf(+            RouteService.TravelMode.DRIVE,+            RouteService.TravelMode.WALK,+            RouteService.TravelMode.BICYCLE,+            RouteService.TravelMode.TRANSIT,+            null,+        )) {+            setSession(mode, route)+            val n = build(NavigationSessionManager.NavState.Navigating(progress()))+            assertNotNull(title(n), "title for mode $mode")+            assertTrue(n.flags and Notification.FLAG_ONGOING_EVENT != 0, "ongoing for $mode")+        }+        // Drive titles come from the current step's instruction.+        setSession(RouteService.TravelMode.DRIVE, route)+        assertEquals(+            "Head north on C5 St",+            title(build(NavigationSessionManager.NavState.Navigating(progress()))),+        )+        // Out-of-range step index falls back to the destination title.+        setSession(RouteService.TravelMode.DRIVE, route)+        val beyond = progress().copy(currentStepIndex = 9)+        assertNotNull(title(build(NavigationSessionManager.NavState.Navigating(beyond))))+    }++    @Test+    fun `navigating notification carries progress and stays ongoing`() {+        val progress = NavigationProgress(+            snappedPosition = GeoPoint(-122.4, 37.8),+            segmentIndex = 0,+            currentStepIndex = 0,+            distanceAlongRoute = 500.0,+            distanceRemaining = 1_500.0,+            distanceToNextManeuver = 200.0,+            fractionComplete = 0.25,+            etaEpochMs = System.currentTimeMillis() + 600_000,+            courseOverGround = 90f,+            distanceOffRoute = 0.0,+        )+        val n = build(NavigationSessionManager.NavState.Navigating(progress))+        assertNotNull(title(n))+        assertTrue(n.flags and Notification.FLAG_ONGOING_EVENT != 0, "navigating stays ongoing")+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsOverlayRebaseC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsOverlayRebaseC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsOverlayRebaseC5Test.ktnew file mode 100644index 0000000000..33595c4832--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsOverlayRebaseC5Test.kt@@ -0,0 +1,170 @@+package com.vayunmathur.maps.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import androidx.work.workDataOf+import java.io.File+import java.net.InetAddress+import java.net.ServerSocket+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.util.concurrent.TimeUnit+import kotlin.concurrent.thread+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * C5 overlay rebase: a manifest whose empty segment list pins a new base+ * downloads that base from the given URL, swaps it in, drops the old+ * overlay stack, and pins the new manifest; a rebased file whose build+ * id disagrees is refused without touching the old base.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MapsOverlayRebaseC5Test {++    companion object {+        // The host JVM routes HTTP through the corp forward proxy, which+        // cannot reach this test's loopback server.+        @JvmStatic+        @org.junit.BeforeClass+        fun bypassProxyForLoopback() {+            System.setProperty("http.nonProxyHosts", "127.0.0.1|localhost")+            System.setProperty("https.nonProxyHosts", "127.0.0.1|localhost")+        }+    }++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val root: File get() = ctx.getExternalFilesDir(null)!!+    private val origFetcher = MapOverlayWorker.manifestFetcher+    private var server: ServerSocket? = null++    @AfterTest+    fun tearDown() {+        MapOverlayWorker.manifestFetcher = origFetcher+        server?.close()+        server = null+        cleanRoot()+    }++    private fun cleanRoot() {+        File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).delete()+        File(root, "${MapTileCache.BASEMAP_ARCHIVE_FILE}.next").delete()+        File(root, "${MapTileCache.BASEMAP_ARCHIVE_FILE}.prev").delete()+        File(root, MapOverlay.OVERLAY_ROOT).deleteRecursively()+    }++    private fun baseBytes(buildId: Long, size: Int = 64): ByteArray {+        val bytes = ByteArray(size)+        ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putLong(16, buildId)+        return bytes+    }++    private fun plantBase(buildId: Long = 0x10) {+        val f = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE)+        f.parentFile?.mkdirs()+        f.writeBytes(baseBytes(buildId))+    }++    /** Serves [body] once per connection on a loopback port. */+    private fun serve(body: ByteArray): Int {+        val socket = ServerSocket(0, 50, InetAddress.getByName("127.0.0.1"))+        server = socket+        thread(isDaemon = true) {+            while (!socket.isClosed) {+                runCatching {+                    val client = socket.accept()+                    // Consume the request line + headers.+                    val input = client.getInputStream().bufferedReader()+                    while (true) {+                        val line = input.readLine()+                        if (line.isNullOrEmpty()) break+                    }+                    val out = client.getOutputStream()+                    out.write(+                        ("HTTP/1.1 200 OK\r\nContent-Length: ${body.size}\r\n" ++                            "Content-Type: application/octet-stream\r\n\r\n").toByteArray(),+                    )+                    out.write(body)+                    out.flush()+                    client.close()+                }+            }+        }+        return socket.localPort+    }++    private fun manifest(seq: Long, baseBuild: String, baseLen: Long, baseUrl: String) = """+        {"version": 1, "min_client": 1, "overlay_seq": $seq, "overlay_build_id": "0x2a",+         "base": {"url": "$baseUrl", "build_id": "$baseBuild", "len": $baseLen},+         "segments": []}+    """.trimIndent()++    private fun runWorker(): ListenableWorker.Result =+        TestListenableWorkerBuilder<MapOverlayWorker>(ctx)+            .setInputData(workDataOf("manifest_url" to "https://example.invalid/manifest.json"))+            .build()+            .startWork()+            .get(180, TimeUnit.SECONDS)++    @Test+    fun `rebase downloads the new base swaps it in and pins`() = runBlocking {+        cleanRoot(); plantBase(0x10)+        val port = serve(baseBytes(0x20))+        val text = manifest(9, "0x20", 64, "http://127.0.0.1:$port/base.mamaps")+        MapOverlayWorker.manifestFetcher = { text }+        assertEquals(ListenableWorker.Result.success(), runWorker())+        // The live base is now the new build, and the manifest is pinned.+        val live = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE)+        val id = ByteBuffer.wrap(live.readBytes()).order(ByteOrder.LITTLE_ENDIAN).getLong(16)+        assertEquals(0x20L, id)+        assertEquals(9L, MapOverlay.pinned(root)?.overlaySeq)+        assertTrue(!File(root, "${MapTileCache.BASEMAP_ARCHIVE_FILE}.next").exists())+        assertTrue(!File(root, "${MapTileCache.BASEMAP_ARCHIVE_FILE}.prev").exists())+    }++    @Test+    fun `missing base skips and unparseable manifest succeeds without pinning`() = runBlocking {+        cleanRoot()+        MapOverlayWorker.manifestFetcher = { "not json at all" }+        // No base archive: the worker skips before fetching.+        assertEquals(ListenableWorker.Result.success(), runWorker())+        plantBase(0x10)+        MapOverlayWorker.manifestFetcher = { "not json at all" }+        // A base exists but the manifest does not parse: success, no pin.+        assertEquals(ListenableWorker.Result.success(), runWorker())+        assertEquals(null, MapOverlay.pinned(root))+        MapOverlayWorker.manifestFetcher = { null }+        // An unfetchable manifest retries.+        assertEquals(ListenableWorker.Result.retry(), runWorker())+    }++    @Test+    fun `rebase with a mismatched downloaded build is refused`() = runBlocking {+        cleanRoot(); plantBase(0x10)+        // Server says the new base is 0x20 but sends 0x99 bytes.+        val port = serve(baseBytes(0x99))+        val text = manifest(9, "0x20", 64, "http://127.0.0.1:$port/base.mamaps")+        MapOverlayWorker.manifestFetcher = { text }+        assertEquals(ListenableWorker.Result.success(), runWorker())+        val live = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE)+        val id = ByteBuffer.wrap(live.readBytes()).order(ByteOrder.LITTLE_ENDIAN).getLong(16)+        assertEquals(0x10L, id, "old base untouched after a refused rebase")+    }++    @Test+    fun `rebase download failure retries`() = runBlocking {+        cleanRoot(); plantBase(0x10)+        val text = manifest(9, "0x20", 64, "http://127.0.0.1:1/base.mamaps")+        MapOverlayWorker.manifestFetcher = { text }+        assertEquals(ListenableWorker.Result.retry(), runWorker())+    }+}
maps/src/test/java/com/vayunmathur/maps/util/MapsPoiLocalityC5Test.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapsPoiLocalityC5Test.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapsPoiLocalityC5Test.ktnew file mode 100644index 0000000000..17aadf672a--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapsPoiLocalityC5Test.kt@@ -0,0 +1,273 @@+package com.vayunmathur.maps.util++import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * C5 locality integration: a full synthetic side-file stack (index, names,+ * spatial grid, word index, region links, attribute blobs, admin table)+ * driving [PoiIndex.localityAt] through the hierarchy walk, the+ * boundary-city vote, and the own-address fallback.+ */+class MapsPoiLocalityC5Test {++    private var temp: File? = null++    @AfterTest+    fun tearDown() {+        temp?.deleteRecursively()+        temp = null+    }++    private data class Poi(+        val latE7: Int,+        val lonE7: Int,+        val type: Int,+        val name: String,+        val region: Long,+        val city: String?,+    )++    private val cellE7 = 200_000++    private fun tag(relation: Long): Long = (relation shl 2) or 3L++    private fun axis(value: Int, origin: Int): Int {+        val d = value.toLong() - origin.toLong()+        return if (d <= 0) 0 else (d / cellE7).toInt()+    }++    private fun words(name: String): List<String> =+        name.split(' ', '\t', '\n', '\r', '', '').filter { it.isNotEmpty() }++    // Boundary ids: a district inside a city inside a state inside a country,+    // plus a second boundary with no admin row at all (vote fallback).+    private val district = tag(100)+    private val city = tag(101)+    private val state = tag(102)+    private val country = tag(103)+    private val votable = tag(200)++    private fun load(pois: List<Poi>) {+        val dir = Files.createTempDirectory("poiloc5").toFile()+        temp = dir+        val sorted = pois.sortedWith { a, b ->+            java.lang.Long.compareUnsigned(+                spatialFromE7(a.latE7, a.lonE7),+                spatialFromE7(b.latE7, b.lonE7),+            )+        }+        val nameOff = writeNames(dir, sorted)+        writeIndex(dir, sorted, nameOff)+        writeWordIndex(dir, sorted)+        writeGrid(dir, sorted)+        writeRegion(dir, sorted)+        writeAttrs(dir, sorted)+        writeAdmin(dir)+        assertTrue(PoiIndex.reload(dir), "fixture did not map")+    }++    private fun writeNames(dir: File, sorted: List<Poi>): Map<String, Int> {+        val nameOff = LinkedHashMap<String, Int>()+        val out = ByteArrayOutputStream()+        for (p in sorted) {+            if (p.name !in nameOff) {+                nameOff[p.name] = out.size()+                out.write(p.name.toByteArray(Charsets.UTF_8))+                out.write(0)+            }+        }+        File(dir, PoiIndex.NAMES_FILE).writeBytes(out.toByteArray())+        return nameOff+    }++    private fun writeIndex(dir: File, sorted: List<Poi>, nameOff: Map<String, Int>) {+        val index = ByteBuffer.allocate(sorted.size * 14).order(ByteOrder.LITTLE_ENDIAN)+        for (p in sorted) {+            index.putInt(p.latE7)+            index.putInt(p.lonE7)+            index.putInt(nameOff.getValue(p.name))+            index.putShort(p.type.toShort())+        }+        File(dir, PoiIndex.INDEX_FILE).writeBytes(index.array())+    }++    private fun writeWordIndex(dir: File, sorted: List<Poi>) {+        val entries = ArrayList<Pair<Int, Int>>()+        sorted.forEachIndexed { ordinal, p ->+            words(p.name).indices.take(255).forEach { entries.add(ordinal to it) }+        }+        entries.sortWith(+            com

Diff truncated.