Modern Apps git

← Modern-Apps.git

maps: live turn-by-turn navigation mode (WIP, still buggy)

Commit
4ea78424f4d6e9c987905f71c217f7116bd39738
Author
Vayun Mathur <[email protected]>
When
2026-05-30 03:45 UTC (6 months ago)
Parents
19888a0

Diff

maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex e2a270bae1..aab5e79a93 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -6,6 +6,10 @@      <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+    <!-- Navigation foreground service requires the LOCATION subtype on Android 14+. -->+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />+    <!-- Required on Android 13+ to show the navigation notification. -->+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> @@ -30,6 +34,14 @@                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>++        <!-- Live navigation foreground service. Owns the ongoing+             progress notification and keeps GPS streaming while the+             app is backgrounded or the screen is off. -->+        <service+            android:name=".util.NavigationService"+            android:foregroundServiceType="location"+            android:exported="false" />     </application>  </manifest>\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 2e472aec38..4d522e444f 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -2,6 +2,7 @@ package com.vayunmathur.maps  import android.Manifest import android.content.Context+import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent@@ -91,7 +92,20 @@ class MainActivity : ComponentActivity() {                     Triple("https://data.vayunmathur.com/road_names.bin", "road_names.bin", getString(R.string.downloading_road_data))                 )) {                     val db = remember { buildAmenityDatabase(this@MainActivity) }-                    PermissionsChecker(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), getString(R.string.grant_location_permission)) {+                    val perms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                        // POST_NOTIFICATIONS is runtime-grantable on API 33++                        // and required for the navigation foreground-service+                        // notification to actually display (otherwise the+                        // service runs invisibly and the user can't End Trip+                        // from outside the app).+                        arrayOf(+                            Manifest.permission.ACCESS_FINE_LOCATION,+                            Manifest.permission.POST_NOTIFICATIONS,+                        )+                    } else {+                        arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)+                    }+                    PermissionsChecker(perms, getString(R.string.grant_location_permission)) {                         Navigation(db)                     }                 }
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex f0c09ecdee..890d5a6ddf 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -1,10 +1,16 @@ package com.vayunmathur.maps.ui+import android.content.Intent+import android.os.Build import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.ListItem@@ -14,17 +20,29 @@ import androidx.compose.material3.Tab import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.util.round import com.vayunmathur.maps.R import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.util.NavigationService+import com.vayunmathur.maps.util.NavigationSessionManager import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SelectedFeatureViewModel  @Composable-fun BottomSheetContent(viewModel: SelectedFeatureViewModel, selectedFeature: SpecificFeature?, setSelectedFeature: (SpecificFeature?) -> Unit, route: Map<RouteService.TravelMode, RouteService.RouteType?>?, selectedRouteType: RouteService.TravelMode, setSelectedRouteType: (RouteService.TravelMode) -> Unit, inactiveNavigation: SpecificFeature.Route?) {+fun BottomSheetContent(+    viewModel: SelectedFeatureViewModel,+    selectedFeature: SpecificFeature?,+    setSelectedFeature: (SpecificFeature?) -> Unit,+    route: Map<RouteService.TravelMode, RouteService.RouteType?>?,+    selectedRouteType: RouteService.TravelMode,+    setSelectedRouteType: (RouteService.TravelMode) -> Unit,+    inactiveNavigation: SpecificFeature.Route?,+    navState: NavigationSessionManager.NavState = NavigationSessionManager.NavState.Idle,+) {     when (selectedFeature) {         is SpecificFeature.Admin0Label -> {             Column {@@ -95,19 +113,72 @@ fun BottomSheetContent(viewModel: SelectedFeatureViewModel, selectedFeature: Spe                             }                         }                     }-                    val route = route[selectedRouteType]-                    if(route != null) {-                        if(route !is RouteService.EmptyRoute) {-                            ListItem({ Text(route.duration.toString()) }, supportingContent = {-                                Text(stringResource(R.string.distance_km, (route.distanceMeters / 1000.0).round(2)))+                    val routeForMode = route[selectedRouteType]+                    if(routeForMode != null) {+                        if(routeForMode !is RouteService.EmptyRoute) {+                            ListItem({ Text(routeForMode.duration.toString()) }, supportingContent = {+                                Text(stringResource(R.string.distance_km, (routeForMode.distanceMeters / 1000.0).round(2)))                             })+                            // "Start Navigation" only when we have a concrete+                            // Route (steps + polyline) and aren't already in+                            // an active navigation session.+                            //+                            // We also hide the button for TRANSIT: the+                            // navigation engine snaps GPS to the route+                            // polyline and computes ETA from progress along+                            // it, which doesn't model trains/buses well, and+                            // mid-trip recalc would replace transit steps+                            // with walking steps. Users can still see the+                            // transit step list; we just don't offer to+                            // "drive" them through it.+                            val lastWaypoint = selectedFeature.waypoints.lastOrNull()+                            val canStart = routeForMode is RouteService.Route &&+                                    navState is NavigationSessionManager.NavState.Idle &&+                                    selectedRouteType != RouteService.TravelMode.TRANSIT &&+                                    lastWaypoint != null+                            if (routeForMode is RouteService.Route &&+                                navState is NavigationSessionManager.NavState.Idle &&+                                selectedRouteType != RouteService.TravelMode.TRANSIT+                            ) {+                                val context = LocalContext.current+                                Button(+                                    onClick = {+                                        if (lastWaypoint == null) return@Button+                                        val destPos = lastWaypoint.position+                                        val destName = lastWaypoint.name+                                        val intent = Intent(context, NavigationService::class.java)+                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+                                            context.startForegroundService(intent)+                                        } else {+                                            context.startService(intent)+                                        }+                                        NavigationSessionManager.init(context)+                                        NavigationSessionManager.start(+                                            route = routeForMode,+                                            mode = selectedRouteType,+                                            destination = destPos,+                                            destinationLabel = destName,+                                        )+                                    },+                                    enabled = canStart,+                                    modifier = Modifier+                                        .fillMaxWidth()+                                        .padding(horizontal = 16.dp, vertical = 8.dp),+                                    colors = ButtonDefaults.buttonColors(+                                        containerColor = MaterialTheme.colorScheme.primary,+                                        contentColor = MaterialTheme.colorScheme.onPrimary,+                                    ),+                                ) {+                                    Text(stringResource(R.string.nav_action_start))+                                }+                            }                             Spacer(Modifier.height(8.dp))                         }                         LazyColumn(verticalArrangement = Arrangement.spacedBy(2.dp)) {-                            when (route) {+                            when (routeForMode) {                                 is RouteService.Route -> {-                                    itemsIndexed(route.step) { idx, it ->-                                        Card(shape = verticalShape(idx, route.step.size)) {+                                    itemsIndexed(routeForMode.step) { idx, it ->+                                        Card(shape = verticalShape(idx, routeForMode.step.size)) {                                             ListItem({                                                 Text(it.navInstruction.instructions)                                             }, leadingContent = {
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 36cde4f1be..123181fe3e 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -180,6 +180,14 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     // --- ROUTE COMPUTATION ---     val route by viewModel.routes.collectAsState(null) +    // --- NAVIGATION SESSION ---+    val navState by com.vayunmathur.maps.util.NavigationSessionManager.state.collectAsState()+    val isNavigating = navState !is com.vayunmathur.maps.util.NavigationSessionManager.NavState.Idle+    var autoFollow by remember { mutableStateOf(true) }+    var lastProgrammaticMoveMs by remember { mutableStateOf(0L) }+    val activeRoute = com.vayunmathur.maps.util.NavigationSessionManager.currentRoute+    val navProgress = (navState as? com.vayunmathur.maps.util.NavigationSessionManager.NavState.Navigating)?.progress+     // --- UI & BOTTOM SHEET STATE ---     var allowProgrammaticHide by retain { mutableStateOf(false) } @@ -213,9 +221,46 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     var selectedRouteType by retain { mutableStateOf(RouteService.TravelMode.DRIVE) }      // --- RENDER ---+    // While actively navigating we don't want the bottom sheet to slide up+    // automatically; the in-screen overlay is the primary nav UI.+    LaunchedEffect(isNavigating) {+        if (isNavigating) {+            hide()+        }+    }++    // Camera follow: animate to snapped position / bearing whenever we get+    // a new progress sample AND the user hasn't panned away.+    LaunchedEffect(navProgress, autoFollow) {+        val p = navProgress ?: return@LaunchedEffect+        if (!autoFollow) return@LaunchedEffect+        lastProgrammaticMoveMs = System.currentTimeMillis()+        camera.animateTo(+            camera.position.copy(+                target = p.snappedPosition,+                bearing = p.courseOverGround.toDouble(),+                tilt = 60.0,+                zoom = 17.0,+            ),+            kotlin.time.Duration.parse("800ms"),+        )+    }++    // Detect user-initiated camera moves: if isCameraMoving becomes true+    // outside the ~1.2s window after our own animateTo, treat it as a pan+    // and disable auto-follow until the user taps Recenter.+    LaunchedEffect(camera.isCameraMoving, isNavigating) {+        if (!isNavigating) return@LaunchedEffect+        if (camera.isCameraMoving &&+            System.currentTimeMillis() - lastProgrammaticMoveMs > 1_200+        ) {+            autoFollow = false+        }+    }+     BottomSheetScaffold({         Column(Modifier.padding(horizontal = 16.dp).padding(bottom = 48.dp, top = 8.dp)) {-            BottomSheetContent(viewModel, selectedFeature, { viewModel.set(it) }, route, selectedRouteType, { selectedRouteType = it }, inactiveNavigation)+            BottomSheetContent(viewModel, selectedFeature, { viewModel.set(it) }, route, selectedRouteType, { selectedRouteType = it }, inactiveNavigation, navState)         }     }, Modifier, scaffoldState, 170.dp) { paddingValues ->         Scaffold(Modifier.padding(top = paddingValues.calculateTopPadding()), topBar = {@@ -248,12 +293,20 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                         listOf("${it}_base", "${it}_hybrid")                                     }.toSet()                                 ) ?: emptyList()-                                // parse() may do network (Wikidata) + Room — do it off Main.-                                val listedFeatures = withContext(Dispatchers.IO) {-                                    features.mapNotNull { runCatching { parse(it, db) }.getOrNull() }+                                // parse() may do network (Wikidata) + Room+                                // per feature. queryRenderedFeatures returns+                                // one Feature PER LAYER at the tap point —+                                // often 2-3 — and we only use the first+                                // parseable result. Stop at the first hit+                                // instead of doing every Wikidata round-trip+                                // serially in the foreground.+                                val firstFeature = withContext(Dispatchers.IO) {+                                    features.firstNotNullOfOrNull { raw ->+                                        runCatching { parse(raw, db) }.getOrNull()+                                    }                                 } -                                listedFeatures.firstOrNull()?.let {+                                firstFeature?.let {                                     if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(                                         selectedFeature as SpecificFeature.Route                                     )@@ -263,8 +316,8 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                             }                             ClickResult.Pass                         }-                    ) {-                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing)+                ) {+                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress)                     }                 } @@ -373,6 +426,24 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         }                     )                 }++                // Live navigation overlay (top maneuver card, bottom ETA strip,+                // recenter FAB, arrival card). Hidden when nav is Idle.+                NavigationOverlay(+                    navState = navState,+                    steps = activeRoute?.step ?: emptyList(),+                    autoFollow = autoFollow,+                    onRecenter = { autoFollow = true },+                    onEndTrip = {+                        com.vayunmathur.maps.util.NavigationSessionManager.stop()+                        context.stopService(android.content.Intent(context, com.vayunmathur.maps.util.NavigationService::class.java))+                        autoFollow = true+                    },+                    onDismissArrival = {+                        com.vayunmathur.maps.util.NavigationSessionManager.stop()+                        context.stopService(android.content.Intent(context, com.vayunmathur.maps.util.NavigationService::class.java))+                    },+                )             }         }     }
maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.ktindex 20e3331f16..a22f07b6f2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -49,7 +49,8 @@ fun MyMapLayers(     route: RouteService.RouteType?,     styleJson: String?,     userPosition: Position,-    userBearing: Float+    userBearing: Float,+    navProgress: com.vayunmathur.maps.util.NavigationProgress? = null, ) {     val trafficVersion by OfflineRouter.trafficVersion.collectAsState()     val context = LocalContext.current@@ -228,43 +229,15 @@ fun MyMapLayers(                     }                     is SpecificFeature.Route -> {                         if (route != null) {-                            LaunchedEffect(route, routeSource, styleJson) {+                            LaunchedEffect(+                                route, routeSource, styleJson,+                                navProgress?.segmentIndex,+                                navProgress?.distanceAlongRoute?.let { (it / 5.0).toInt() }+                            ) {                                 if (route is RouteService.Route) {-                                    val features: List<Feature1> =-                                        route.step.filter { it.polyline.size >= 2 }.map {-                                            val color =-                                                if (it.travelMode ==-                                                    RouteService.TravelMode-                                                        .DRIVE-                                                ) {-                                                    when {-                                                        it.speedRatio < 0.5 ->-                                                            "#F44336" // Red-                                                        it.speedRatio < 0.9 ->-                                                            "#FFC107" // Amber/Yellow-                                                        else -> "#4CAF50" // Green-                                                    }-                                                } else if (it.travelMode == RouteService.TravelMode.TRANSIT) {-                                                    val feed = it.transitDetails?.feedName-                                                    if (feed != null) {-                                                        com.vayunmathur.maps.util.GTFSProvider.getRouteColor(context, feed, it.transitDetails.transitLine.name) ?: "#FF0000"-                                                    } else {-                                                        "#FF0000"-                                                    }-                                                } else "#1710F1"--                                            Feature1(-                                                LineString(it.polyline),-                                                JsonObject(-                                                    mapOf(-                                                        "route-color" to-                                                            JsonPrimitive(-                                                                color-                                                            )-                                                    )-                                                )-                                            )-                                        }+                                    val features: List<Feature1> = buildRouteFeatures(+                                        route, context, navProgress+                                    )                                     routeSource.setData(                                         GeoJsonData.Features(FeatureCollection(features))                                     )@@ -309,3 +282,150 @@ private fun createInvertedMask(countryFeature: Feature1): Feature1 {     val donutGeometry = Polygon(listOf(worldOuterRing) + holes)     return Feature(geometry = donutGeometry, properties = countryFeature.properties) }++/**+ * Compute the per-step `route-color` for the static (non-navigating) case.+ * Driving uses traffic-aware red/amber/green, transit uses the GTFS feed+ * color when available, walk/bike fall through to a single blue.+ */+private fun staticColorFor(+    step: RouteService.Step,+    context: android.content.Context,+): String {+    return when (step.travelMode) {+        RouteService.TravelMode.DRIVE -> when {+            step.speedRatio < 0.5 -> "#F44336" // Red+            step.speedRatio < 0.9 -> "#FFC107" // Amber/Yellow+            else -> "#4CAF50"                  // Green+        }+        RouteService.TravelMode.TRANSIT -> {+            val feed = step.transitDetails?.feedName+            if (feed != null) {+                com.vayunmathur.maps.util.GTFSProvider.getRouteColor(+                    context, feed, step.transitDetails.transitLine.name+                ) ?: "#FF0000"+            } else "#FF0000"+        }+        else -> "#1710F1"+    }+}++/** Color shown for the portion of the route the user has already traveled. */+private const val TRAVELED_GRAY = "#9E9E9E"++/**+ * Build the GeoJSON `Feature` list for the route polyline.+ *+ * When [navProgress] is null this returns one feature per [Step] with the+ * mode-aware static color.+ *+ * When [navProgress] is non-null the polyline is split at the snapped point+ * so that:+ *  - steps strictly before the current step get the traveled-gray color+ *  - the current step is split: portion behind the snap → gray; portion+ *    ahead → original mode color+ *  - steps strictly after keep their original color+ *+ * Splitting at the segment level requires matching the snapped segment+ * index (which is into the FULL `route.polyline`) to the corresponding+ * vertex inside the current step's local polyline. The math here is the+ * mirror of [com.vayunmathur.maps.util.PolylineIndex]'s `stepRanges`+ * construction (cursor walk; steps share endpoints).+ */+private fun buildRouteFeatures(+    route: RouteService.Route,+    context: android.content.Context,+    navProgress: com.vayunmathur.maps.util.NavigationProgress?,+): List<Feature1> {+    if (navProgress == null) {+        return route.step.filter { it.polyline.size >= 2 }.map { step ->+            Feature1(+                LineString(step.polyline),+                JsonObject(mapOf("route-color" to JsonPrimitive(staticColorFor(step, context))))+            )+        }+    }++    val currentStepIdx = navProgress.currentStepIndex+    val snappedSegIdx = navProgress.segmentIndex // index into route.polyline+    val snappedPos = navProgress.snappedPosition++    val out = mutableListOf<Feature1>()+    // Walk the full polyline alongside the steps the same way PolylineIndex+    // builds stepRanges, so we know the vertex range for each step.+    var cursor = 0+    for ((stepIdx, step) in route.step.withIndex()) {+        val stepLen = step.polyline.size+        if (stepLen < 2) {+            // Nothing to render for a degenerate step. Cursor stays where it+            // was (mirrors PolylineIndex's `ranges.add(cursor..cursor)` /+            // skipping the cursor advance).+            continue+        }+        val first = cursor+        val last = (first + stepLen - 1).coerceAtMost(route.polyline.size - 1)+        val color = staticColorFor(step, context)++        when {+            stepIdx < currentStepIdx -> {+                // Entirely behind: gray.+                out += Feature1(+                    LineString(step.polyline),+                    JsonObject(mapOf("route-color" to JsonPrimitive(TRAVELED_GRAY)))+                )+            }+            stepIdx > currentStepIdx -> {+                // Entirely ahead: original color.+                out += Feature1(+                    LineString(step.polyline),+                    JsonObject(mapOf("route-color" to JsonPrimitive(color)))+                )+            }+            snappedSegIdx < first -> {+                // Snap fell on an earlier step than our step-index math+                // attributed to this step (e.g. brief off-by-one near a+                // boundary, or a glitchy GPS fix). Treat the whole step as+                // ahead rather than fabricating a gray spur from a snapped+                // position that isn't on this step's segments.+                out += Feature1(+                    LineString(step.polyline),+                    JsonObject(mapOf("route-color" to JsonPrimitive(color)))+                )+            }+            snappedSegIdx > last -> {+                // Snap fell on a later step. Treat the whole step as behind.+                out += Feature1(+                    LineString(step.polyline),+                    JsonObject(mapOf("route-color" to JsonPrimitive(TRAVELED_GRAY)))+                )+            }+            else -> {+                // The active step: split at the snap point. snappedSegIdx is+                // guaranteed in [first, last] by the two guards above.+                val localSnapVertex = snappedSegIdx - first+                // Behind portion: vertices 0..localSnapVertex, with the+                // snapped position appended so the gray ends exactly under+                // the user.+                val behindVertices = step.polyline.subList(0, localSnapVertex + 1).toMutableList()+                behindVertices.add(snappedPos)+                if (behindVertices.size >= 2) {+                    out += Feature1(+                        LineString(behindVertices),+                        JsonObject(mapOf("route-color" to JsonPrimitive(TRAVELED_GRAY)))+                    )+                }+                // Ahead portion: snapped position, then remaining vertices.+                val aheadVertices = mutableListOf(snappedPos)+                aheadVertices.addAll(step.polyline.subList(localSnapVertex + 1, stepLen))+                if (aheadVertices.size >= 2) {+                    out += Feature1(+                        LineString(aheadVertices),+                        JsonObject(mapOf("route-color" to JsonPrimitive(color)))+                    )+                }+            }+        }+        cursor = last+    }+    return out+}
maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.ktnew file mode 100644index 0000000000..e1ef70c34f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt@@ -0,0 +1,358 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.WindowInsets+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.layout.systemBars+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.layout.windowInsetsPadding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Button+import androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.material3.ExtendedFloatingActionButton+import androidx.compose.material3.FilledTonalButton+import androidx.compose.material3.Icon+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.shadow+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.maps.R+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.RouteService+import com.vayunmathur.maps.util.formatDistance+import com.vayunmathur.maps.util.formatEta+import kotlin.math.roundToInt++/**+ * Full-screen overlay drawn on top of [MaplibreMap] while navigation is+ * active. Renders the Google-Maps-style top maneuver card, bottom ETA strip,+ * a recenter FAB when the user has panned away from the snapped position,+ * and an arrival/failure card for terminal states.+ *+ * Hidden when state is [NavigationSessionManager.NavState.Idle] — caller is+ * responsible for only rendering this composable inside a `Box` overlay.+ */+@Composable+fun NavigationOverlay(+    navState: NavigationSessionManager.NavState,+    steps: List<RouteService.Step>,+    autoFollow: Boolean,+    onRecenter: () -> Unit,+    onEndTrip: () -> Unit,+    onDismissArrival: () -> Unit,+) {+    if (navState is NavigationSessionManager.NavState.Idle) return++    Box(Modifier.fillMaxSize()) {+        // ---- Top maneuver card ----+        when (navState) {+            is NavigationSessionManager.NavState.Navigating -> {+                ManeuverCard(+                    progress = navState.progress,+                    steps = steps,+                    modifier = Modifier+                        .align(Alignment.TopCenter)+                        .windowInsetsPadding(WindowInsets.statusBars)+                        .padding(horizontal = 12.dp, vertical = 8.dp)+                )+            }+            NavigationSessionManager.NavState.Starting -> {+                StatusCard(+                    text = stringResource(R.string.nav_status_starting),+                    showProgress = true,+                    modifier = Modifier+                        .align(Alignment.TopCenter)+                        .windowInsetsPadding(WindowInsets.statusBars)+                        .padding(horizontal = 12.dp, vertical = 8.dp)+                )+            }+            NavigationSessionManager.NavState.Recalculating -> {+                StatusCard(+                    text = stringResource(R.string.nav_off_route),+                    showProgress = true,+                    modifier = Modifier+                        .align(Alignment.TopCenter)+                        .windowInsetsPadding(WindowInsets.statusBars)+                        .padding(horizontal = 12.dp, vertical = 8.dp)+                )+            }+            is NavigationSessionManager.NavState.Failed -> {+                FailureCard(+                    reason = navState.reason,+                    onDismiss = onDismissArrival,+                    modifier = Modifier+                        .align(Alignment.TopCenter)+                        .windowInsetsPadding(WindowInsets.statusBars)+                        .padding(horizontal = 12.dp, vertical = 8.dp)+                )+            }+            else -> {}+        }++        // ---- Recenter FAB ----+        if (navState is NavigationSessionManager.NavState.Navigating && !autoFollow) {+            ExtendedFloatingActionButton(+                onClick = onRecenter,+                modifier = Modifier+                    .align(Alignment.CenterEnd)+                    .padding(16.dp),+                icon = {+                    Icon(+                        painterResource(R.drawable.location_on_24px),+                        contentDescription = null,+                    )+                },+                text = { Text(stringResource(R.string.nav_action_recenter)) }+            )+        }++        // ---- Bottom ETA strip / arrival card ----+        when (navState) {+            is NavigationSessionManager.NavState.Navigating -> {+                EtaStrip(+                    progress = navState.progress,+                    onEndTrip = onEndTrip,+                    modifier = Modifier+                        .align(Alignment.BottomCenter)+                        .fillMaxWidth()+                        .windowInsetsPadding(WindowInsets.systemBars)+                )+            }+            NavigationSessionManager.NavState.Arrived -> {+                ArrivalCard(+                    onDismiss = onDismissArrival,+                    modifier = Modifier+                        .align(Alignment.BottomCenter)+                        .fillMaxWidth()+                        .windowInsetsPadding(WindowInsets.systemBars)+                        .padding(16.dp)+                )+            }+            else -> {}+        }+    }+}++@Composable+private fun ManeuverCard(+    progress: NavigationProgress,+    steps: List<RouteService.Step>,+    modifier: Modifier = Modifier,+) {+    val currentStep = steps.getOrNull(progress.currentStepIndex)+    val nextStep = steps.getOrNull(progress.currentStepIndex + 1)+    // Per plan: we count down to the NEXT step's maneuver. The instruction+    // shown is the next maneuver's instruction; the current step's text is+    // the "you're currently on" peek line below.+    val primary = nextStep ?: currentStep+    val primaryInstruction = primary?.navInstruction?.instructions.orEmpty()+    val primaryIcon = primary?.navInstruction?.maneuver?.icon()+    val distanceText = formatDistance(progress.distanceToNextManeuver)++    Card(+        modifier = modifier+            .fillMaxWidth()+            .shadow(8.dp, RoundedCornerShape(16.dp)),+        shape = RoundedCornerShape(16.dp),+        colors = CardDefaults.cardColors(+            containerColor = MaterialTheme.colorScheme.primaryContainer,+            contentColor = MaterialTheme.colorScheme.onPrimaryContainer,+        ),+    ) {+        Row(+            modifier = Modifier.padding(16.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            if (primaryIcon != null) {+                Icon(+                    painterResource(primaryIcon),+                    contentDescription = null,+                    modifier = Modifier.size(56.dp),+                    tint = MaterialTheme.colorScheme.onPrimaryContainer,+                )+                Spacer(Modifier.width(16.dp))+            }+            Column(Modifier.weight(1f)) {+                Text(+                    distanceText,+                    fontSize = 28.sp,+                    fontWeight = FontWeight.Bold,+                )+                Text(+                    primaryInstruction,+                    fontSize = 16.sp,+                    fontWeight = FontWeight.Medium,+                )+                if (nextStep != null && currentStep != null && currentStep !== primary) {+                    val secondary = steps.getOrNull(progress.currentStepIndex + 2)+                    if (secondary != null) {+                        Spacer(Modifier.height(4.dp))+                        Text(+                            "Then: ${secondary.navInstruction.instructions}",+                            fontSize = 12.sp,+                            color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f),+                        )+                    }+                }+            }+        }+    }+}++@Composable+private fun StatusCard(+    text: String,+    showProgress: Boolean,+    modifier: Modifier = Modifier,+) {+    Card(+        modifier = modifier.fillMaxWidth(),+        shape = RoundedCornerShape(16.dp),+    ) {+        Column(Modifier.padding(16.dp)) {+            Text(text, fontWeight = FontWeight.Medium)+            if (showProgress) {+                Spacer(Modifier.height(8.dp))+                LinearProgressIndicator(Modifier.fillMaxWidth())+            }+        }+    }+}++@Composable+private fun EtaStrip(+    progress: NavigationProgress,+    onEndTrip: () -> Unit,+    modifier: Modifier = Modifier,+) {+    val etaText = formatEta(progress.etaEpochMs)+    val remainingDistance = formatDistance(progress.distanceRemaining)+    val remainingMinutes = (((progress.etaEpochMs - System.currentTimeMillis()).coerceAtLeast(0L)) / 60_000L).toInt()++    Card(+        modifier = modifier,+        shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),+        colors = CardDefaults.cardColors(+            containerColor = MaterialTheme.colorScheme.surface,+        ),+    ) {+        Row(+            modifier = Modifier+                .fillMaxWidth()+                .padding(horizontal = 16.dp, vertical = 12.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            Column(Modifier.weight(1f)) {+                Text(+                    etaText,+                    fontSize = 20.sp,+                    fontWeight = FontWeight.Bold,+                )+                Text(+                    "$remainingMinutes min · $remainingDistance",+                    fontSize = 14.sp,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+            Button(+                onClick = onEndTrip,+                colors = ButtonDefaults.buttonColors(+                    containerColor = MaterialTheme.colorScheme.errorContainer,+                    contentColor = MaterialTheme.colorScheme.onErrorContainer,+                ),+            ) {+                Text(stringResource(R.string.nav_action_end))+            }+        }+    }+}++@Composable+private fun FailureCard(+    reason: String,+    onDismiss: () -> Unit,+    modifier: Modifier = Modifier,+) {+    Card(+        modifier = modifier.fillMaxWidth(),+        shape = RoundedCornerShape(16.dp),+        colors = CardDefaults.cardColors(+            containerColor = MaterialTheme.colorScheme.errorContainer,+            contentColor = MaterialTheme.colorScheme.onErrorContainer,+        ),+    ) {+        Column(+            Modifier.padding(16.dp).fillMaxWidth(),+        ) {+            Text(+                stringResource(R.string.nav_status_failed),+                fontWeight = FontWeight.Bold,+            )+            Spacer(Modifier.height(4.dp))+            Text(reason)+            Spacer(Modifier.height(12.dp))+            Row(+                Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.End,+            ) {+                FilledTonalButton(onClick = onDismiss) {+                    Text(stringResource(R.string.nav_arrived_dismiss))+                }+            }+        }+    }+}++@Composable+private fun ArrivalCard(+    onDismiss: () -> Unit,+    modifier: Modifier = Modifier,+) {+    Card(+        modifier = modifier,+        shape = RoundedCornerShape(16.dp),+        colors = CardDefaults.cardColors(+            containerColor = MaterialTheme.colorScheme.tertiaryContainer,+            contentColor = MaterialTheme.colorScheme.onTertiaryContainer,+        ),+    ) {+        Column(+            Modifier.padding(20.dp).fillMaxWidth(),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            Text(+                stringResource(R.string.nav_arrived_title),+                fontSize = 22.sp,+                fontWeight = FontWeight.Bold,+                textAlign = TextAlign.Center,+            )+            Spacer(Modifier.height(12.dp))+            FilledTonalButton(onClick = onDismiss) {+                Text(stringResource(R.string.nav_arrived_dismiss))+            }+        }+    }+}
maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.ktnew file mode 100644index 0000000000..360659ae90--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt@@ -0,0 +1,355 @@+package com.vayunmathur.maps.util++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import com.vayunmathur.maps.MainActivity+import com.vayunmathur.maps.R+import com.vayunmathur.maps.util.RouteService.TravelMode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.datetime.Instant+import kotlinx.datetime.TimeZone+import kotlinx.datetime.format+import kotlinx.datetime.format.Padding+import kotlinx.datetime.toLocalDateTime+import kotlin.math.roundToInt++/**+ * Foreground service that owns the lifetime of a navigation session.+ *+ * Modeled on `findfamily/.../LocationTrackingService`: a `Service` (not+ * `LifecycleService`) with a `SupervisorJob`-scoped `serviceScope` collects+ * [NavigationSessionManager.state] and updates a persistent ongoing+ * notification (the Android equivalent of an iOS "live activity"). The+ * service also feeds [NavigationTts] so voice cues fire even when the app+ * is backgrounded.+ *+ * Started via `startForegroundService(Intent(this, NavigationService::class.java))`+ * from the "Start Navigation" button. Stopped by either:+ *   - the user tapping "End" in the in-app overlay+ *   - the user tapping the "End" notification action+ *   - the navigation session reaching [NavigationSessionManager.NavState.Arrived]+ */+class NavigationService : Service() {++    private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private var collectorJob: Job? = null+    private var lastNotificationUpdateMs: Long = 0L++    override fun onCreate() {+        super.onCreate()+        NavigationSessionManager.init(this)+        NavigationTts.init(this)+        Log.i(TAG, "onCreate")+    }++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        if (intent?.action == ACTION_STOP) {+            Log.i(TAG, "ACTION_STOP")+            stopSelfAndSession()+            return START_NOT_STICKY+        }++        startForeground(+            NOTIFICATION_ID,+            buildNotification(NavigationSessionManager.state.value),+            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+                ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION+            } else {+                0+            }+        )++        // One collector for the lifetime of the service: pushes state into+        // both the notification (throttled) and the TTS engine.+        collectorJob?.cancel()+        collectorJob = serviceScope.launch {+            NavigationSessionManager.state.collect { state ->+                handleState(state)+            }+        }+        return START_STICKY+    }++    override fun onDestroy() {+        Log.i(TAG, "onDestroy")+        collectorJob?.cancel()+        NavigationTts.shutdown()+        // Defensive cleanup for the case where the system kills the service+        // (low memory / task removed) without going through our own+        // stopSelfAndSession() path. Without this the singleton would stay+        // in Navigating with a dead location listener, and the next time+        // the user opens the app the overlay would re-appear with stale data.+        NavigationSessionManager.stop()+        serviceScope.cancel()+        super.onDestroy()+    }++    override fun onTaskRemoved(rootIntent: Intent?) {+        // If the user swipes the app away from recents while navigating,+        // tear down rather than leave the singleton (and the persistent+        // notification) orphaned.+        Log.i(TAG, "onTaskRemoved — stopping navigation session")+        stopSelfAndSession()+        super.onTaskRemoved(rootIntent)+    }++    override fun onBind(intent: Intent?): IBinder? = null++    // ----------------------------------------------------------------+    // State -> notification / TTS dispatch+    // ----------------------------------------------------------------++    private fun handleState(state: NavigationSessionManager.NavState) {+        when (state) {+            is NavigationSessionManager.NavState.Navigating -> {+                val route = NavigationSessionManager.currentRoute+                if (route != null) {+                    NavigationTts.onProgressUpdate(state.progress, route.step)+                }+                maybeUpdateNotification(state)+            }+            NavigationSessionManager.NavState.Arrived -> {+                updateNotificationNow(state)+                // Tear down after a short delay so the UI / notification can+                // settle on the Arrived state visibly.+                serviceScope.launch {+                    kotlinx.coroutines.delay(8_000)+                    stopSelfAndSession()+                }+            }+            is NavigationSessionManager.NavState.Failed -> {+                updateNotificationNow(state)+                // Auto-cleanup Failed too — the overlay shows the reason for+                // a few seconds before the service tears itself down. Without+                // this the user could be left with a dismissable notification+                // that they tap (or swipe away) and the singleton stays+                // "Failed" with no way to clear it short of force-stopping+                // the app.+                serviceScope.launch {+                    kotlinx.coroutines.delay(8_000)+                    stopSelfAndSession()+                }+            }+            else -> {+                updateNotificationNow(state)+            }+        }+    }++    private fun maybeUpdateNotification(state: NavigationSessionManager.NavState) {+        val now = System.currentTimeMillis()+        if (now - lastNotificationUpdateMs >= NOTIFICATION_THROTTLE_MS) {+            lastNotificationUpdateMs = now+            updateNotificationNow(state)+        }+    }++    private fun updateNotificationNow(state: NavigationSessionManager.NavState) {+        val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager+        nm.notify(NOTIFICATION_ID, buildNotification(state))+    }++    // ----------------------------------------------------------------+    // Notification building+    // ----------------------------------------------------------------++    private fun ensureChannel() {+        val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager+        if (nm.getNotificationChannel(CHANNEL_ID) != null) return+        val channel = NotificationChannel(+            CHANNEL_ID,+            getString(R.string.nav_channel_name),+            NotificationManager.IMPORTANCE_LOW+        ).apply {+            description = getString(R.string.nav_channel_desc)+            setSound(null, null)+            enableVibration(false)+        }+        nm.createNotificationChannel(channel)+    }++    private fun buildNotification(state: NavigationSessionManager.NavState): Notification {+        ensureChannel()+        val tapIntent = PendingIntent.getActivity(+            this, 0,+            Intent(this, MainActivity::class.java).apply {+                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)+            },+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT+        )+        val stopIntent = PendingIntent.getService(+            this, 1,+            Intent(this, NavigationService::class.java).apply { action = ACTION_STOP },+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT+        )++        val mode = NavigationSessionManager.travelMode+        val destLabel = NavigationSessionManager.destinationName ?: getString(R.string.nav_default_destination)++        val (title, content, progressPercent, smallIcon) = describe(state, mode, destLabel)++        val builder = NotificationCompat.Builder(this, CHANNEL_ID)+            .setContentTitle(title)+            .setContentText(content)+            .setSmallIcon(smallIcon)+            .setOngoing(state !is NavigationSessionManager.NavState.Arrived &&+                        state !is NavigationSessionManager.NavState.Failed)+            .setSilent(true)+            .setOnlyAlertOnce(true)+            .setContentIntent(tapIntent)+            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)+            .addAction(0, getString(R.string.nav_action_end), stopIntent)++        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+            builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)+        }++        progressPercent?.let { p -> builder.setProgress(100, p, false) }+        return builder.build()+    }++    private data class NotificationInfo(+        val title: String,+        val content: String,+        val progressPercent: Int?,+        val smallIcon: Int,+    )++    private fun describe(+        state: NavigationSessionManager.NavState,+        mode: TravelMode?,+        destLabel: String,+    ): NotificationInfo {+        val defaultIcon = R.drawable.location_on_24px+        return when (state) {+            NavigationSessionManager.NavState.Idle -> NotificationInfo(+                getString(R.string.nav_status_idle), "", null, defaultIcon+            )+            NavigationSessionManager.NavState.Starting -> NotificationInfo(+                getString(R.string.nav_status_starting),+                getString(R.string.nav_destination_format, destLabel),+                null, defaultIcon+            )+            NavigationSessionManager.NavState.Recalculating -> NotificationInfo(+                getString(R.string.nav_status_recalculating),+                getString(R.string.nav_destination_format, destLabel),+                null, defaultIcon+            )+            NavigationSessionManager.NavState.Arrived -> NotificationInfo(+                getString(R.string.nav_status_arrived),+                destLabel,+                100, defaultIcon+            )+            is NavigationSessionManager.NavState.Failed -> NotificationInfo(+                getString(R.string.nav_status_failed),+                state.reason,+                null, defaultIcon+            )+            is NavigationSessionManager.NavState.Navigating -> {+                val p = state.progress+                val percent = (p.fractionComplete * 100).roundToInt().coerceIn(0, 100)+                val distRemaining = formatDistance(p.distanceRemaining)+                val etaText = formatEta(p.etaEpochMs)+                val route = NavigationSessionManager.currentRoute+                val currentStep = route?.step?.getOrNull(p.currentStepIndex)+                val maneuverIcon = currentStep?.navInstruction?.maneuver?.icon() ?: defaultIcon+                when (mode) {+                    TravelMode.DRIVE -> {+                        val title = currentStep?.navInstruction?.instructions?.takeIf { it.isNotBlank() }+                            ?: getString(R.string.nav_destination_format, destLabel)+                        val content = getString(+                            R.string.nav_drive_content_format,+                            formatDistance(p.distanceToNextManeuver),+                            etaText,+                        )+                        NotificationInfo(title, content, percent, maneuverIcon)+                    }+                    TravelMode.WALK -> NotificationInfo(+                        getString(R.string.nav_walk_title_format, destLabel),+                        getString(R.string.nav_progress_content_format, percent, distRemaining, etaText),+                        percent, defaultIcon+                    )+                    TravelMode.BICYCLE -> NotificationInfo(+                        getString(R.string.nav_bike_title_format, destLabel),+                        getString(R.string.nav_progress_content_format, percent, distRemaining, etaText),+                        percent, defaultIcon+                    )+                    TravelMode.TRANSIT -> {+                        val transitTitle = currentStep?.transitDetails?.transitLine?.name+                            ?.takeIf { it.isNotBlank() }+                            ?: currentStep?.navInstruction?.instructions+                            ?: getString(R.string.nav_transit_title_default, destLabel)+                        NotificationInfo(+                            transitTitle,+                            getString(R.string.nav_progress_content_format, percent, distRemaining, etaText),+                            percent, defaultIcon+                        )+                    }+                    null -> NotificationInfo(+                        getString(R.string.nav_destination_format, destLabel),+                        getString(R.string.nav_progress_content_format, percent, distRemaining, etaText),+                        percent, defaultIcon+                    )+                }+            }+        }+    }++    private fun stopSelfAndSession() {+        NavigationSessionManager.stop()+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {+            stopForeground(STOP_FOREGROUND_REMOVE)+        } else {+            @Suppress("DEPRECATION")+            stopForeground(true)+        }+        stopSelf()+    }++    companion object {+        private const val TAG = "NavigationService"+        private const val CHANNEL_ID = "navigation_channel"+        private const val NOTIFICATION_ID = 4242+        private const val NOTIFICATION_THROTTLE_MS = 2_000L+        const val ACTION_STOP = "com.vayunmathur.maps.navigation.STOP"+    }+}++/**+ * Format a distance in meters as a short user-facing string.+ * - "<X m" under 1 km+ * - "X.Y km" otherwise (one decimal)+ */+internal fun formatDistance(meters: Double): String {+    if (meters < 1000.0) return "${meters.roundToInt()} m"+    val km = meters / 1000.0+    return "%.1f km".format(km)+}++/** Format epoch-ms as local HH:mm AM/PM. */+internal fun formatEta(etaEpochMs: Long): String {+    val instant = Instant.fromEpochMilliseconds(etaEpochMs)+    val local = instant.toLocalDateTime(TimeZone.currentSystemDefault())+    val fmt = kotlinx.datetime.LocalDateTime.Format {+        amPmHour(Padding.NONE)+        chars(":")+        minute()+        chars(" ")+        amPmMarker("AM", "PM")+    }+    return local.format(fmt)+}
maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.ktnew file mode 100644index 0000000000..2fd2917a36--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationSessionManager.kt@@ -0,0 +1,400 @@+package com.vayunmathur.maps.util++import android.Manifest+import android.annotation.SuppressLint+import android.content.Context+import android.content.pm.PackageManager+import android.hardware.Sensor+import android.hardware.SensorEvent+import android.hardware.SensorEventListener+import android.hardware.SensorManager+import android.location.Location+import android.location.LocationListener+import android.location.LocationManager+import android.os.Bundle+import android.util.Log+import androidx.core.content.ContextCompat+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.util.RouteService.TravelMode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import org.maplibre.spatialk.geojson.Position+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Process-global state machine for an in-progress navigation session.+ *+ * Mirrors the pattern used by `findfamily/.../UwbSessionManager`: a singleton+ * `object` owns the entire lifecycle, exposes a [StateFlow] for any observer+ * (UI, foreground service notification), and is fed by [NavigationService]+ * which keeps the process alive while the user navigates.+ *+ * Why a singleton (not a ViewModel-scoped owner): the user expects driving+ * navigation to continue when the app is backgrounded or the screen turns off+ * (foreground service requirement), and to survive activity recreation+ * (rotation, system-initiated kills). A ViewModel can't do either.+ */+object NavigationSessionManager {++    private const val TAG = "NavSession"++    /** Distance (m) off the polyline before we start considering "off-route". */+    private const val OFF_ROUTE_THRESHOLD_M = 50.0++    /** How long we must remain off-route before auto-recalculating (ms). */+    private const val OFF_ROUTE_DEBOUNCE_MS = 5_000L++    /** Minimum gap between consecutive recalc attempts (ms). */+    private const val RECALC_COOLDOWN_MS = 15_000L++    /** Distance (m) below which we consider the user "arrived". */+    private const val ARRIVAL_RADIUS_M = 30.0++    /** Speed (m/s) above which we trust GPS course-over-ground for bearing. */+    private const val GPS_COURSE_MIN_SPEED_MPS = 1.0f++    /** UI / notification state for the navigation session. */+    sealed interface NavState {+        data object Idle : NavState+        data object Starting : NavState+        data class Navigating(val progress: NavigationProgress) : NavState+        data object Recalculating : NavState+        data object Arrived : NavState+        data class Failed(val reason: String) : NavState+    }++    private val _state: MutableStateFlow<NavState> = MutableStateFlow(NavState.Idle)+    val state: StateFlow<NavState> = _state.asStateFlow()++    /** Travel mode for the active session (or last session). Used by UI/notification. */+    @Volatile var travelMode: TravelMode? = null+        private set++    /** Human-readable destination shown in the notification. */+    @Volatile var destinationName: String? = null+        private set++    /** The active route (snapshot used by UI for step list / polyline split). */+    @Volatile var currentRoute: RouteService.Route? = null+        private set++    private val initialized = AtomicBoolean(false)+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private lateinit var appContext: Context++    private var polylineIndex: PolylineIndex? = null+    private var destination: Position? = null+    private var lastSegmentIndex: Int = 0+    private var offRouteSinceMs: Long? = null+    private var lastRecalcMs: Long = 0L+    private var recalcAttempts: Int = 0+    private var locationJob: Job? = null+    private var recalcJob: Job? = null++    // Location/compass source. We don't reuse FrameworkLocationManager because+    // navigation needs the raw Location for speed-based bearing selection,+    // which FrameworkLocationManager doesn't expose.+    private var locationManager: LocationManager? = null+    private var sensorManager: SensorManager? = null+    private var registeredLocationListener: LocationListener? = null+    private var registeredSensorListener: SensorEventListener? = null++    /** Compass-derived heading (from sensor fusion). */+    @Volatile private var compassBearing: Float = 0f++    fun init(context: Context) {+        if (!initialized.compareAndSet(false, true)) return+        appContext = context.applicationContext+        Log.i(TAG, "init")+    }++    /**+     * Begin navigating along [route] in [mode]. [destination] is used for+     * off-route recalculation. [destinationLabel] populates the notification.+     */+    fun start(+        route: RouteService.Route,+        mode: TravelMode,+        destination: Position,+        destinationLabel: String,+    ) {+        if (!initialized.get()) {+            Log.w(TAG, "start() called before init()")+            return+        }+        if (_state.value !is NavState.Idle && _state.value !is NavState.Failed) {+            Log.w(TAG, "start() called while already in state ${_state.value}; ignoring")+            return+        }+        Log.i(TAG, "start(mode=$mode, label=$destinationLabel, steps=${route.step.size}, dist=${route.distanceMeters})")+        currentRoute = route+        travelMode = mode+        destinationName = destinationLabel+        this.destination = destination+        polylineIndex = PolylineIndex(route)+        lastSegmentIndex = 0+        offRouteSinceMs = null+        recalcAttempts = 0+        _state.value = NavState.Starting+        startLocationCollection()+    }++    /** End the navigation session. Cancels jobs, stops location, resets state. */+    fun stop() {+        Log.i(TAG, "stop")+        locationJob?.cancel(); locationJob = null+        recalcJob?.cancel(); recalcJob = null+        stopLocationCollection()+        // Drop TTS bookkeeping so a follow-up start() doesn't suppress+        // threshold cues whose stepIndex happens to collide with the old+        // route's. NavigationService.shutdown() also fully tears down TTS+        // when the service is destroyed; this is the in-process equivalent+        // for stop-without-service-teardown paths.+        NavigationTts.reset()+        polylineIndex = null+        currentRoute = null+        travelMode = null+        destinationName = null+        destination = null+        lastSegmentIndex = 0+        offRouteSinceMs = null+        _state.value = NavState.Idle+    }++    // ----------------------------------------------------------------+    // Location / sensor wiring+    // ----------------------------------------------------------------++    @SuppressLint("MissingPermission")+    private fun startLocationCollection() {+        // Hard gate on ACCESS_FINE_LOCATION — without it requestLocationUpdates+        // throws SecurityException.+        if (ContextCompat.checkSelfPermission(+                appContext,+                Manifest.permission.ACCESS_FINE_LOCATION+            ) != PackageManager.PERMISSION_GRANTED+        ) {+            _state.value = NavState.Failed("Location permission not granted")+            return+        }++        if (locationManager == null) {+            locationManager = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager+        }+        if (sensorManager == null) {+            sensorManager = appContext.getSystemService(Context.SENSOR_SERVICE) as SensorManager+        }++        val lm = locationManager!!+        val sm = sensorManager!!++        val locListener = object : LocationListener {+            override fun onLocationChanged(location: Location) {+                handleLocation(location)+            }+            @Deprecated("Required by old LocationListener interface; status callbacks are no longer delivered on API 29+.")+            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}+        }+        registeredLocationListener = locListener+        runCatching {+            if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {+                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, locListener)+            }+            if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {+                lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 0f, locListener)+            }+        }.onFailure { Log.e(TAG, "requestLocationUpdates failed", it) }++        // Compass fusion for the stationary case (start-of-route, traffic stop).+        val sensorListener = object : SensorEventListener {+            private val accel = FloatArray(3)+            private val mag = FloatArray(3)+            private val rot = FloatArray(9)+            private val angles = FloatArray(3)+            override fun onSensorChanged(event: SensorEvent) {+                when (event.sensor.type) {+                    Sensor.TYPE_ACCELEROMETER -> event.values.copyInto(accel)+                    Sensor.TYPE_MAGNETIC_FIELD -> event.values.copyInto(mag)+                }+                if (SensorManager.getRotationMatrix(rot, null, accel, mag)) {+                    SensorManager.getOrientation(rot, angles)+                    val az = Math.toDegrees(angles[0].toDouble()).toFloat()+                    compassBearing = (az + 360f) % 360f+                }+            }+            override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}+        }+        registeredSensorListener = sensorListener+        sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.also {+            sm.registerListener(sensorListener, it, SensorManager.SENSOR_DELAY_UI)+        }+        sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)?.also {+            sm.registerListener(sensorListener, it, SensorManager.SENSOR_DELAY_UI)+        }++        // Seed an initial fix from the last known location so the UI doesn't+        // sit on Starting until the next GPS tick.+        runCatching {+            val last = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)+                ?: lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)+            last?.let { handleLocation(it) }+        }+    }++    private fun stopLocationCollection() {+        registeredLocationListener?.let { listener ->+            runCatching { locationManager?.removeUpdates(listener) }+        }+        registeredLocationListener = null+        registeredSensorListener?.let { listener ->+            runCatching { sensorManager?.unregisterListener(listener) }+        }+        registeredSensorListener = null+    }++    // ----------------------------------------------------------------+    // Per-fix processing+    // ----------------------------------------------------------------++    private fun handleLocation(location: Location) {+        // Once we've Arrived (or hit a terminal Failed state) we want fixes+        // to stop driving the state machine — otherwise normal GPS jitter+        // (±10 m around the destination) flicks the user back into+        // Navigating and re-enqueues the service's 8s self-stop timer.+        if (_state.value is NavState.Arrived || _state.value is NavState.Failed) return++        val index = polylineIndex ?: return+        val position = Position(longitude = location.longitude, latitude = location.latitude)+        val snap = index.snap(position, lastSegmentIndex)+        lastSegmentIndex = snap.segmentIndex++        val bearing = chooseBearing(location)+        val progress = index.deriveProgress(snap, courseOverGround = bearing)++        // Arrival check first — once arrived, stop processing and let the UI+        // show its end-of-trip card before being torn down.+        if (progress.distanceRemaining <= ARRIVAL_RADIUS_M) {+            _state.value = NavState.Arrived+            // Drop the location subscription so subsequent fixes can't+            // un-arrive us. The service's auto-cleanup timer takes over.+            stopLocationCollection()+            return+        }++        // Off-route detection + debounced recalc. Skip for transit — a+        // train/bus rider is genuinely "off" the polyline most of the+        // trip (tunnels, GPS drift inside a vehicle), and a recalc would+        // replace the planned transit route with a walking route mid-trip.+        val now = System.currentTimeMillis()+        if (travelMode != TravelMode.TRANSIT && snap.distanceOffRoute > OFF_ROUTE_THRESHOLD_M) {+            val since = offRouteSinceMs ?: run {+                offRouteSinceMs = now+                now+            }+            val elapsed = now - since+            val canRecalc = (now - lastRecalcMs) >= RECALC_COOLDOWN_MS && recalcAttempts < 3+            if (elapsed >= OFF_ROUTE_DEBOUNCE_MS && canRecalc && _state.value !is NavState.Recalculating) {+                triggerRecalculate(position)+                return+            }+        } else {+            offRouteSinceMs = null+        }++        _state.value = NavState.Navigating(progress)+    }++    private fun chooseBearing(location: Location): Float = when {+        location.hasBearing() && location.hasSpeed() && location.speed >= GPS_COURSE_MIN_SPEED_MPS ->+            location.bearing+        else -> compassBearing+    }++    // ----------------------------------------------------------------+    // Off-route recalculation+    // ----------------------------------------------------------------++    private fun triggerRecalculate(from: Position) {+        val dest = destination ?: return+        val mode = travelMode ?: return+        Log.i(TAG, "off-route; recalculating from $from to $dest (attempt ${recalcAttempts + 1})")+        _state.value = NavState.Recalculating+        recalcAttempts+++        lastRecalcMs = System.currentTimeMillis()+        recalcJob?.cancel()+        recalcJob = scope.launch {+            val newRoute = runCatching {+                // Wrap the existing destination + current pos into a Route+                // request the same way the bottom sheet does.+                val fromFeature = SpecificFeature.GenericPlace(+                    name = "From",+                    phone = null,+                    website = null,+                    openingHours = null,+                    position = from,+                )+                val toFeature = SpecificFeature.GenericPlace(+                    name = destinationName ?: "Destination",+                    phone = null,+                    website = null,+                    openingHours = null,+                    position = dest,+                )+                val routeFeature = SpecificFeature.Route(listOf(fromFeature, toFeature))++                // Prefer the offline router; fall back to the online service.+                // OfflineRouter.getRoute returns a Route (or throws); it+                // doesn't return EmptyRoute, so a non-null offline result is+                // a usable route.+                val offline = runCatching {+                    OfflineRouter.getRoute(appContext, routeFeature, from, mode)+                }.getOrNull()+                if (offline != null) {+                    offline+                } else {+                    RouteService.computeRoute(routeFeature, from, mode)+                }+            }.getOrNull()++            if (newRoute == null) {+                Log.w(TAG, "recalc failed")+                if (recalcAttempts >= 3) {+                    _state.value = NavState.Failed("Could not recalculate route")+                } else {+                    // Don't immediately rip the user back to Failed — drop+                    // back into Navigating on the old route; the next off-route+                    // window may succeed.+                    offRouteSinceMs = null+                }+                return@launch+            }++            // If the user reached the destination while the recalc was in+            // flight, drop the recalc result on the floor — otherwise we'd+            // overwrite the (still-valid) Arrived state with a fresh,+            // longer route and the user would be "un-arrived".+            if (_state.value is NavState.Arrived) {+                Log.i(TAG, "recalc completed but user already arrived; discarding new route")+                return@launch+            }++            // Swap in the new polyline. Reset state for the new shape.+            currentRoute = newRoute+            polylineIndex = PolylineIndex(newRoute)+            lastSegmentIndex = 0+            offRouteSinceMs = null+            recalcAttempts = 0+            NavigationTts.reset()+            // The location listener is still running; the next fix will move+            // us into Navigating on the new route.+            Log.i(TAG, "recalc succeeded; new route ${newRoute.distanceMeters}m / ${newRoute.step.size} steps")+        }+    }+}
maps/src/main/java/com/vayunmathur/maps/util/NavigationTts.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationTts.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationTts.ktnew file mode 100644index 0000000000..82c4c31a6f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationTts.kt@@ -0,0 +1,187 @@+package com.vayunmathur.maps.util++import android.content.Context+import android.media.AudioAttributes+import android.media.AudioFocusRequest+import android.media.AudioManager+import android.os.Build+import android.speech.tts.TextToSpeech+import android.speech.tts.UtteranceProgressListener+import android.util.Log+import com.vayunmathur.maps.util.RouteService.Step+import java.util.Locale+import java.util.UUID+import java.util.concurrent.atomic.AtomicBoolean++/**+ * Voice-guidance scheduler for navigation. Wraps Android's [TextToSpeech].+ *+ * Plays each step's instruction at three distance thresholds before the+ * maneuver (1 km, 300 m, 100 m), plus an immediate cue when the user+ * transitions onto a new step. Each (stepIndex, threshold) is announced at+ * most once until [reset] is called (e.g. on route recalculation).+ *+ * Lives as a top-level singleton so the foreground service and any UI can+ * share a single TTS engine without re-initializing it on every navigation+ * start.+ */+object NavigationTts {++    private const val TAG = "NavTts"++    private val initialized = AtomicBoolean(false)+    private var tts: TextToSpeech? = null+    private var audioManager: AudioManager? = null+    private var focusRequest: AudioFocusRequest? = null++    /** Stepwise record of which distance thresholds we've already announced. */+    private val announced: MutableMap<Int, MutableSet<Int>> = mutableMapOf()++    /** Track the last announced step so we know to fire a step-transition cue. */+    @Volatile private var lastAnnouncedStepIndex: Int = -1++    /**+     * Outstanding TTS utterances currently being played or queued. Used to+     * keep AudioFocus held across rapidly-fired back-to-back cues — we only+     * abandon focus when the queue actually drains, not after the FIRST+     * utterance's onDone fires.+     */+    private val outstandingUtterances = java.util.concurrent.atomic.AtomicInteger(0)++    /** Thresholds (m) — must be in descending order. */+    private val thresholdsMeters = intArrayOf(1000, 300, 100)++    fun init(context: Context) {+        if (!initialized.compareAndSet(false, true)) return+        audioManager = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager+        tts = TextToSpeech(context.applicationContext) { status ->+            if (status == TextToSpeech.SUCCESS) {+                tts?.language = Locale.getDefault()+                tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {+                    override fun onStart(utteranceId: String?) {}+                    override fun onDone(utteranceId: String?) { onUtteranceFinished() }+                    @Deprecated("Old API")+                    override fun onError(utteranceId: String?) { onUtteranceFinished() }+                    override fun onError(utteranceId: String?, errorCode: Int) { onUtteranceFinished() }+                })+                Log.i(TAG, "TTS initialized")+            } else {+                Log.w(TAG, "TTS init failed: status=$status")+            }+        }+    }++    /** Called from the utterance listener: only abandon focus when no more are pending. */+    private fun onUtteranceFinished() {+        if (outstandingUtterances.decrementAndGet() <= 0) {+            // Reset to 0 in case of decrement-below-zero from spurious callbacks.+            outstandingUtterances.set(0)+            abandonFocus()+        }+    }++    fun shutdown() {+        if (!initialized.compareAndSet(true, false)) return+        runCatching { tts?.stop() }+        runCatching { tts?.shutdown() }+        tts = null+        outstandingUtterances.set(0)+        abandonFocus()+        audioManager = null+        focusRequest = null+        announced.clear()+        lastAnnouncedStepIndex = -1+    }++    /** Drop all announcement bookkeeping (call on recalc or stop). */+    fun reset() {+        announced.clear()+        lastAnnouncedStepIndex = -1+        runCatching { tts?.stop() }+        // tts.stop() doesn't necessarily fire onDone for queued utterances,+        // so manually clear the in-flight counter and drop focus.+        outstandingUtterances.set(0)+        abandonFocus()+    }++    /**+     * Called from the navigation service every time progress updates. Decides+     * whether to fire a new announcement.+     */+    fun onProgressUpdate(progress: NavigationProgress, steps: List<Step>) {+        val stepIdx = progress.currentStepIndex+        if (stepIdx !in steps.indices) return++        // Step transition: speak the new step's instruction immediately.+        if (stepIdx != lastAnnouncedStepIndex && lastAnnouncedStepIndex >= 0) {+            val instr = steps[stepIdx].navInstruction.instructions+            if (instr.isNotBlank()) speak(instr)+            // Mark all thresholds for the new step as already-considered so+            // we don't immediately re-fire the 1000m cue while the user is+            // still close to the maneuver.+            announced.getOrPut(stepIdx) { mutableSetOf() }+        }+        lastAnnouncedStepIndex = stepIdx++        // Threshold-based cues for the NEXT step's maneuver (not the current+        // step's start). distanceToNextManeuver counts down to step (idx+1).+        val nextIdx = stepIdx + 1+        if (nextIdx !in steps.indices) return++        val nextInstr = steps[nextIdx].navInstruction.instructions+        if (nextInstr.isBlank()) return++        val alreadyAnnounced = announced.getOrPut(nextIdx) { mutableSetOf() }+        for (threshold in thresholdsMeters) {+            if (progress.distanceToNextManeuver <= threshold && threshold !in alreadyAnnounced) {+                val phrase = phraseFor(threshold, nextInstr)+                speak(phrase)+                alreadyAnnounced.add(threshold)+                // Only fire one threshold per update — if multiple cross at+                // once (e.g. very short step), the next update picks them up.+                break+            }+        }+    }++    private fun phraseFor(thresholdMeters: Int, instruction: String): String = when {+        thresholdMeters >= 1000 -> "In ${thresholdMeters / 1000} kilometer${if (thresholdMeters / 1000 == 1) "" else "s"}, $instruction"+        thresholdMeters >= 100 -> "In $thresholdMeters meters, $instruction"+        else -> "Now, $instruction"+    }++    private fun speak(text: String) {+        val engine = tts ?: return+        if (!requestFocus()) return+        outstandingUtterances.incrementAndGet()+        engine.speak(text, TextToSpeech.QUEUE_ADD, null, UUID.randomUUID().toString())+    }++    private fun requestFocus(): Boolean {+        val am = audioManager ?: return false+        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+            val req = focusRequest ?: AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK)+                .setAudioAttributes(+                    AudioAttributes.Builder()+                        .setUsage(AudioAttributes.USAGE_ASSISTANCE_NAVIGATION_GUIDANCE)+                        .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)+                        .build()+                )+                .build().also { focusRequest = it }+            am.requestAudioFocus(req) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED+        } else {+            @Suppress("DEPRECATION")+            am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED+        }+    }++    private fun abandonFocus() {+        val am = audioManager ?: return+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+            focusRequest?.let { am.abandonAudioFocusRequest(it) }+        } else {+            @Suppress("DEPRECATION")+            am.abandonAudioFocus(null)+        }+    }+}
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex be99c42708..82ecf44ee8 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -499,12 +499,76 @@ object OfflineRouter {                             )                         } +                // Coalesce consecutive maneuvers that stay on the same road.+                // The native router can emit a chain of small "slight left /+                // slight right" entries along a curving stretch of road+                // (e.g. El Camino Real bending through Palo Alto) where+                // the road name never changes — visually that's "stay on+                // the same road", not a series of turns. Merge those into+                // a single step whose polyline + distance + duration is the+                // sum of the merged steps.+                val coalescedSteps = mutableListOf<RouteService.Step>()+                for (step in processedSteps) {+                    val prev = coalescedSteps.lastOrNull()+                    // Smart-cast prev to non-null in the merge branch by+                    // gating on prev != null first.+                    if (prev != null &&+                        prev.travelMode == step.travelMode &&+                        step.travelMode != RouteService.TravelMode.TRANSIT &&+                        step.navInstruction.maneuver in NON_TURNING_MANEUVERS &&+                        // Road name unchanged (instruction text is+                        // road-name-templated, so equal strings ⇒ same road).+                        sameRoadName(prev.navInstruction.instructions, step.navInstruction.instructions)+                    ) {+                        coalescedSteps[coalescedSteps.lastIndex] = prev.copy(+                            distanceMeters = prev.distanceMeters + step.distanceMeters,+                            staticDuration = prev.staticDuration + step.staticDuration,+                            polyline = mergePolylines(prev.polyline, step.polyline),+                        )+                    } else {+                        coalescedSteps.add(step)+                    }+                }+                 RouteService.Route(                         duration =-                                processedSteps.sumOf { it.staticDuration.inWholeSeconds }.seconds,-                        distanceMeters = processedSteps.sumOf { it.distanceMeters },+                                coalescedSteps.sumOf { it.staticDuration.inWholeSeconds }.seconds,+                        distanceMeters = coalescedSteps.sumOf { it.distanceMeters },                         polyline = fullPolyline,-                        step = processedSteps+                        step = coalescedSteps                 )             }++    /**+     * Maneuvers that we treat as "still on the same road" when their+     * instruction text doesn't change between steps. A SHARP turn or a+     * RAMP / FORK / MERGE / ROUNDABOUT is always a real maneuver even if+     * the road name happens to match.+     */+    private val NON_TURNING_MANEUVERS = setOf(+        RouteService.API.Maneuver.STRAIGHT,+        RouteService.API.Maneuver.TURN_SLIGHT_LEFT,+        RouteService.API.Maneuver.TURN_SLIGHT_RIGHT,+        RouteService.API.Maneuver.NAME_CHANGE,+        RouteService.API.Maneuver.MANEUVER_UNSPECIFIED,+    )++    /**+     * Two adjacent maneuvers are considered "on the same road" when the+     * instruction strings match. Instruction text is templated from the+     * road name (see the maneuver_* string templates), so identical+     * instruction strings ⇒ same road.+     */+    private fun sameRoadName(prev: String, curr: String): Boolean =+        prev.isNotBlank() && prev == curr++    /** Concatenate two step polylines, skipping the duplicate join point. */+    private fun mergePolylines(+        a: List<org.maplibre.spatialk.geojson.Position>,+        b: List<org.maplibre.spatialk.geojson.Position>,+    ): List<org.maplibre.spatialk.geojson.Position> {+        if (a.isEmpty()) return b+        if (b.isEmpty()) return a+        return if (a.last() == b.first()) a + b.drop(1) else a + b+    } }
maps/src/main/java/com/vayunmathur/maps/util/PolylineProgress.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PolylineProgress.kt b/maps/src/main/java/com/vayunmathur/maps/util/PolylineProgress.ktnew file mode 100644index 0000000000..9c7c5f25bd--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PolylineProgress.kt@@ -0,0 +1,302 @@+package com.vayunmathur.maps.util++import com.vayunmathur.maps.util.RouteService.Route+import com.vayunmathur.maps.util.RouteService.Step+import org.maplibre.spatialk.geojson.Position+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.max+import kotlin.math.min+import kotlin.math.sqrt++/**+ * Pure-Kotlin geometry + progress engine for navigation.+ *+ * All distances are in meters. Position uses lon-first per+ * [org.maplibre.spatialk.geojson.Position] convention.+ *+ * There is no Android dependency here so the file is trivially unit-testable+ * and is shared between the foreground service ([NavigationSessionManager])+ * and any UI that needs to derive per-step progress.+ */++private const val EARTH_RADIUS_M = 6_371_008.8+private const val DEG_TO_RAD = PI / 180.0++/**+ * Cheap equirectangular distance approximation. Plenty accurate for the+ * route-snapping workload (a few thousand vertices at <= ~tens of km,+ * sampled at 1 Hz). Avoids the trig overhead of full haversine.+ */+fun equirectangularDistance(a: Position, b: Position): Double {+    val midLatRad = (a.latitude + b.latitude) * 0.5 * DEG_TO_RAD+    val dxMeters = (b.longitude - a.longitude) * DEG_TO_RAD * EARTH_RADIUS_M * cos(midLatRad)+    val dyMeters = (b.latitude - a.latitude) * DEG_TO_RAD * EARTH_RADIUS_M+    return sqrt(dxMeters * dxMeters + dyMeters * dyMeters)+}++/** Project [p] onto segment [a]-[b] in local-meters tangent plane. */+fun projectOntoSegment(p: Position, a: Position, b: Position): SegmentProjection {+    // Use a tangent plane centered on segment midpoint.+    val midLatRad = (a.latitude + b.latitude) * 0.5 * DEG_TO_RAD+    val mPerLon = DEG_TO_RAD * EARTH_RADIUS_M * cos(midLatRad)+    val mPerLat = DEG_TO_RAD * EARTH_RADIUS_M++    val ax = 0.0+    val ay = 0.0+    val bx = (b.longitude - a.longitude) * mPerLon+    val by = (b.latitude - a.latitude) * mPerLat+    val px = (p.longitude - a.longitude) * mPerLon+    val py = (p.latitude - a.latitude) * mPerLat++    val segLenSq = bx * bx + by * by+    val fraction = if (segLenSq <= 0.0) 0.0+    else ((px - ax) * bx + (py - ay) * by) / segLenSq+    val clamped = fraction.coerceIn(0.0, 1.0)++    val projX = ax + clamped * bx+    val projY = ay + clamped * by+    val dx = px - projX+    val dy = py - projY+    val perpDistMeters = sqrt(dx * dx + dy * dy)++    val projLon = a.longitude + (projX / mPerLon)+    val projLat = a.latitude + (projY / mPerLat)+    return SegmentProjection(+        fraction = clamped,+        projectedPosition = Position(projLon, projLat),+        perpendicularDistance = perpDistMeters+    )+}++data class SegmentProjection(+    val fraction: Double,+    val projectedPosition: Position,+    val perpendicularDistance: Double,+)++/**+ * Precomputed prefix sums and per-step index ranges for a [Route]. Built once+ * per route so the per-GPS-fix snap is O(window) instead of O(full route).+ */+class PolylineIndex(val route: Route) {+    /** Number of vertices in the full route polyline. */+    val vertexCount: Int = route.polyline.size++    /** Number of segments = vertexCount - 1 (or 0 for degenerate routes). */+    val segmentCount: Int = max(0, vertexCount - 1)++    /** Cumulative distance to the start of each vertex; [0] = 0.0. */+    val cumulativeDistances: DoubleArray = DoubleArray(vertexCount)++    /** Length of each segment (segment i goes from polyline[i] to polyline[i+1]). */+    private val segmentLengths: DoubleArray = DoubleArray(segmentCount)++    /** For each [Step], the vertex range it occupies in the full polyline. */+    val stepRanges: List<IntRange>++    /** Total route distance in meters. */+    val totalDistance: Double+        get() = if (vertexCount > 0) cumulativeDistances.last() else 0.0++    init {+        for (i in 0 until segmentCount) {+            val len = equirectangularDistance(route.polyline[i], route.polyline[i + 1])+            segmentLengths[i] = len+            cumulativeDistances[i + 1] = cumulativeDistances[i] + len+        }++        // Match each step's polyline back to the full polyline by walking+        // forward — the existing route builder concatenates steps end-to-end+        // and deduplicates shared endpoints (see OfflineRouter.getRoute).+        //+        // INVARIANT: route.polyline MUST be the concatenation of+        // step[i].polyline with shared endpoints deduplicated. OfflineRouter+        // produces this; RouteService.computeRoute also rebuilds the+        // polyline this way (see RouteService for the rebuild call) so the+        // index ranges below are valid for both offline and online routes.+        val ranges = mutableListOf<IntRange>()+        var cursor = 0+        for (step in route.step) {+            val stepLen = step.polyline.size+            if (stepLen == 0) {+                ranges.add(cursor..cursor)+                continue+            }+            val first = cursor+            val last = min(vertexCount - 1, cursor + stepLen - 1)+            ranges.add(first..last)+            // The next step's first vertex is the previous step's last vertex+            // (shared join point), so advance by stepLen - 1.+            cursor = last+        }+        stepRanges = ranges+    }++    /**+     * Snap [position] onto the route. [lastSegmentIndex] biases the search to+     * the segments around the last known snap so we don't accidentally jump+     * back to a closer-but-stale earlier segment when the route doubles back+     * or loops. Falls back to a full search if the windowed search produces+     * a clearly-bad result (perpendicular distance > 200 m AND the window+     * didn't reach a boundary).+     */+    fun snap(+        position: Position,+        lastSegmentIndex: Int = 0,+        windowRadius: Int = 30,+    ): SnapResult {+        if (segmentCount == 0) {+            return SnapResult(+                segmentIndex = 0,+                fraction = 0.0,+                snappedPosition = route.polyline.firstOrNull() ?: position,+                distanceOffRoute = 0.0,+                distanceAlongRoute = 0.0,+            )+        }+        val start = max(0, lastSegmentIndex - windowRadius)+        val end = min(segmentCount - 1, lastSegmentIndex + windowRadius)+        val windowed = bestSnapInRange(position, start, end)+        val touchesBoundary = (start == 0) || (end == segmentCount - 1)+        return if (!touchesBoundary && windowed.distanceOffRoute > 200.0) {+            // Window probably missed the actual nearest segment (long+            // tunnel, big U-turn, GPS jump). Fall back to a full scan.+            bestSnapInRange(position, 0, segmentCount - 1)+        } else {+            windowed+        }+    }++    private fun bestSnapInRange(position: Position, from: Int, to: Int): SnapResult {+        var bestIdx = from+        var bestProj = projectOntoSegment(position, route.polyline[from], route.polyline[from + 1])+        for (i in (from + 1)..to) {+            val proj = projectOntoSegment(position, route.polyline[i], route.polyline[i + 1])+            if (proj.perpendicularDistance < bestProj.perpendicularDistance) {+                bestIdx = i+                bestProj = proj+            }+        }+        val along = cumulativeDistances[bestIdx] + bestProj.fraction * segmentLengths[bestIdx]+        return SnapResult(+            segmentIndex = bestIdx,+            fraction = bestProj.fraction,+            snappedPosition = bestProj.projectedPosition,+            distanceOffRoute = bestProj.perpendicularDistance,+            distanceAlongRoute = along,+        )+    }++    /**+     * Find the index of the [Step] that the given **segment** belongs to.+     *+     * Care is required: [stepRanges] are *closed vertex ranges with shared+     * endpoints* (step i ends at the same vertex step i+1 starts on). A+     * segment with index `s` runs from vertex `s` to vertex `s + 1`, so:+     *  - step `i` (for i < last step) owns segments `range.first .. range.last - 1`+     *  - the last step owns segments `range.first .. range.last`+     *+     * If we instead asked "which vertex range contains segment s", the shared+     * boundary vertex would attribute the first segment of every step to the+     * previous step — producing a one-segment lag on every step transition+     * (maneuver card reads "0 m, turn left" while the user is already on the+     * new road, TTS step-transition cue fires late, etc.).+     */+    fun stepIndexForSegment(segmentIndex: Int): Int {+        for ((i, range) in stepRanges.withIndex()) {+            val ownedLast = if (i == stepRanges.lastIndex) range.last else range.last - 1+            if (segmentIndex <= ownedLast) return i+        }+        return stepRanges.lastIndex.coerceAtLeast(0)+    }++    /**+     * Distance from the start of the route to the start of step [stepIndex]+     * (i.e. cumulative distance to that step's first vertex).+     */+    fun cumulativeDistanceToStepStart(stepIndex: Int): Double {+        val range = stepRanges.getOrNull(stepIndex) ?: return totalDistance+        return cumulativeDistances.getOrNull(range.first) ?: totalDistance+    }++    /**+     * Distance from start of route to the END of step [stepIndex] (= start+     * of step + step.distanceMeters approximation via the index ranges).+     */+    fun cumulativeDistanceToStepEnd(stepIndex: Int): Double {+        val range = stepRanges.getOrNull(stepIndex) ?: return totalDistance+        return cumulativeDistances.getOrNull(range.last) ?: totalDistance+    }+}++/** Single per-fix snap result. */+data class SnapResult(+    val segmentIndex: Int,+    val fraction: Double,+    val snappedPosition: Position,+    val distanceOffRoute: Double,+    val distanceAlongRoute: Double,+)++/**+ * Everything a UI / notification needs to render the current state of an+ * in-progress navigation session.+ */+data class NavigationProgress(+    val snappedPosition: Position,+    val segmentIndex: Int,+    val currentStepIndex: Int,+    val distanceAlongRoute: Double,+    val distanceRemaining: Double,+    val distanceToNextManeuver: Double,+    val fractionComplete: Double,+    /** ETA as Unix epoch milliseconds. */+    val etaEpochMs: Long,+    val courseOverGround: Float,+    val distanceOffRoute: Double,+)++/**+ * Build a [NavigationProgress] from a [SnapResult] and the static [Route].+ * [courseOverGround] is the bearing the camera should face (GPS course when+ * moving, compass when stationary — picked upstream).+ */+fun PolylineIndex.deriveProgress(+    snap: SnapResult,+    courseOverGround: Float,+    nowEpochMs: Long = System.currentTimeMillis(),+): NavigationProgress {+    val currentStepIndex = stepIndexForSegment(snap.segmentIndex)+    val nextStepStart = if (currentStepIndex + 1 < route.step.size) {+        cumulativeDistanceToStepStart(currentStepIndex + 1)+    } else {+        totalDistance+    }+    val distanceToNextManeuver = (nextStepStart - snap.distanceAlongRoute).coerceAtLeast(0.0)+    val distanceRemaining = (totalDistance - snap.distanceAlongRoute).coerceAtLeast(0.0)+    val fractionComplete = if (totalDistance > 0.0) {+        (snap.distanceAlongRoute / totalDistance).coerceIn(0.0, 1.0)+    } else {+        0.0+    }+    // ETA from the remaining fraction of the route's static duration. Cheap+    // approximation that doesn't require traffic data here.+    val remainingDurationMs = if (totalDistance > 0.0) {+        (route.duration.inWholeMilliseconds * (1.0 - fractionComplete)).toLong()+    } else {+        0L+    }+    return NavigationProgress(+        snappedPosition = snap.snappedPosition,+        segmentIndex = snap.segmentIndex,+        currentStepIndex = currentStepIndex,+        distanceAlongRoute = snap.distanceAlongRoute,+        distanceRemaining = distanceRemaining,+        distanceToNextManeuver = distanceToNextManeuver,+        fractionComplete = fractionComplete,+        etaEpochMs = nowEpochMs + remainingDurationMs,+        courseOverGround = courseOverGround,+        distanceOffRoute = snap.distanceOffRoute,+    )+}
maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.ktindex 345bb55fde..7b28c5ded5 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/RouteService.kt@@ -35,20 +35,43 @@ object RouteService {                 body = request             ) +            val steps = serverRoute.step.map { step ->+                Step(+                    distanceMeters = step.distanceMeters,+                    staticDuration = Duration.parse(step.staticDuration),+                    polyline = step.polyline.map { Position(it.longitude, it.latitude) },+                    navInstruction = step.navInstruction,+                    travelMode = step.travelMode,+                    transitDetails = step.transitDetails+                )+            }+            // Rebuild the full polyline from concatenated step polylines+            // (de-duplicating the shared join vertex between steps). The+            // server's `polyline` field is decoded independently and isn't+            // guaranteed to be vertex-for-vertex aligned to the step+            // polylines (different simplification / rounding). PolylineIndex+            // (the navigation snap engine) relies on the route polyline being+            // exactly the step concatenation so its per-step vertex ranges+            // line up; mismatches there cause wrong ETAs / step-transitions.+            val rebuiltPolyline = mutableListOf<Position>()+            for (step in steps) {+                if (step.polyline.isEmpty()) continue+                if (rebuiltPolyline.isEmpty()) {+                    rebuiltPolyline.addAll(step.polyline)+                } else {+                    val first = step.polyline.first()+                    if (rebuiltPolyline.last() == first) {+                        rebuiltPolyline.addAll(step.polyline.drop(1))+                    } else {+                        rebuiltPolyline.addAll(step.polyline)+                    }+                }+            }             return Route(                 duration = Duration.parse(serverRoute.duration),                 distanceMeters = serverRoute.distanceMeters,-                polyline = serverRoute.polyline.map { Position(it.longitude, it.latitude) },-                step = serverRoute.step.map { step ->-                    Step(-                        distanceMeters = step.distanceMeters,-                        staticDuration = Duration.parse(step.staticDuration),-                        polyline = step.polyline.map { Position(it.longitude, it.latitude) },-                        navInstruction = step.navInstruction,-                        travelMode = step.travelMode,-                        transitDetails = step.transitDetails-                    )-                }+                polyline = rebuiltPolyline,+                step = steps,             )         } catch (e: Exception) {             e.printStackTrace()
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 5c2e380bd4..d0b9426688 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -90,4 +90,26 @@     <string name="travel_mode_bicycle">Bicycle</string>     <string name="travel_mode_drive">Drive</string>     <string name="travel_mode_transit">Transit</string>++    <!-- Navigation Service / Notification -->+    <string name="nav_channel_name">Navigation</string>+    <string name="nav_channel_desc">Live turn-by-turn navigation</string>+    <string name="nav_default_destination">your destination</string>+    <string name="nav_destination_format">To %1$s</string>+    <string name="nav_status_idle">Ready to navigate</string>+    <string name="nav_status_starting">Starting navigation…</string>+    <string name="nav_status_recalculating">Recalculating route…</string>+    <string name="nav_status_arrived">You have arrived</string>+    <string name="nav_status_failed">Navigation stopped</string>+    <string name="nav_action_end">End</string>+    <string name="nav_action_recenter">Recenter</string>+    <string name="nav_action_start">Start Navigation</string>+    <string name="nav_drive_content_format">%1$s · ETA %2$s</string>+    <string name="nav_walk_title_format">Walking to %1$s</string>+    <string name="nav_bike_title_format">Biking to %1$s</string>+    <string name="nav_transit_title_default">Transit to %1$s</string>+    <string name="nav_progress_content_format">%1$d%% · %2$s left · ETA %3$s</string>+    <string name="nav_arrived_title">You have arrived</string>+    <string name="nav_arrived_dismiss">Dismiss</string>+    <string name="nav_off_route">Off route — recalculating…</string> </resources>\ No newline at end of file