maps: local .mamaps, transit vehicles, elevation profile, intent IPC
- Commit
86fc72623b867a7464f07387f1ea73a7d6fde163- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-10 05:19 UTC (2 months ago)
- Parents
e650d53
Diff
fooddelivery/src/main/AndroidManifest.xml
diff --git a/fooddelivery/src/main/AndroidManifest.xml b/fooddelivery/src/main/AndroidManifest.xmlindex a1e6ea6f7e..825837ec1a 100644--- a/fooddelivery/src/main/AndroidManifest.xml+++ b/fooddelivery/src/main/AndroidManifest.xml@@ -37,10 +37,10 @@ </intent-filter> </activity> - <provider- android:name=".ipc.OrderLookupProvider"- android:authorities="com.vayunmathur.fooddelivery.orderlookup"+ <activity+ android:name=".intents.OrderLookupIntent" android:exported="true"+ android:theme="@android:style/Theme.NoDisplay" android:permission="com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS" /> <service
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/OrderLookupIntent.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/OrderLookupIntent.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/OrderLookupIntent.ktnew file mode 100644index 0000000000..5a57bba529--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/intents/OrderLookupIntent.kt@@ -0,0 +1,93 @@+package com.vayunmathur.fooddelivery.intents++import com.vayunmathur.fooddelivery.api.BitesApi+import com.vayunmathur.fooddelivery.data.Merchant+import com.vayunmathur.fooddelivery.ipc.OrderLookupContract+import com.vayunmathur.fooddelivery.platform.AppInit+import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult+import com.vayunmathur.library.util.AssistantIntent+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.serializer+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt++/**+ * Exported, signature-guarded lookup that answers "can I order from this restaurant?" for a+ * co-signed app (the maps place sheet).+ *+ * Replaces the old `OrderLookupProvider` cursor: a live catalog match is time-varying data, so a+ * request/response [AssistantIntent] fits it better than a ContentProvider. It fetches the merchant+ * catalog near the queried point ([BitesApi.getMerchants]) and does a tolerant name-normalise ++ * proximity match, returning the nearest match within [MATCH_RADIUS_METERS] as `available=true`+ * with its id and `fooddelivery://restaurant/<id>` deep link, or `available=false` otherwise.+ * A network/parse failure degrades to a not-orderable result rather than crossing the binder.+ *+ * Guarded by `com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS` in the manifest.+ */+@OptIn(InternalSerializationApi::class)+class OrderLookupIntent : AssistantIntent<OrderLookupRequest, OrderLookupResult>(+ serializer<OrderLookupRequest>(),+ serializer<OrderLookupResult>(),+) {+ override suspend fun performCalculation(input: OrderLookupRequest): OrderLookupResult {+ val match = try {+ findMatch(input)+ } catch (_: Exception) {+ null+ }+ return if (match != null) {+ OrderLookupResult(true, match.id, OrderLookupContract.deepLink(match.id))+ } else {+ OrderLookupResult(false, 0, "")+ }+ }++ private suspend fun findMatch(input: OrderLookupRequest): Merchant? {+ val target = normalize(input.name.trim())+ if (target.isEmpty()) return null++ // This can run in a cold fooddelivery process; the trust bundle + saved auth token are+ // warmed up off the main thread by AppInit (idempotent), which we await before the fetch.+ AppInit.start(applicationContext)+ AppInit.awaitReady()+ val merchants = BitesApi.getMerchants(input.lat, input.lng)+ if (merchants.isEmpty()) return null++ // Keep only merchants that are plausibly the same place: close enough AND whose normalised+ // name matches (equal / prefix / containment). Pick the nearest such candidate.+ return merchants+ .mapNotNull { m ->+ val d = haversineMeters(input.lat, input.lng, m.latitude, m.longitude)+ if (d <= MATCH_RADIUS_METERS && nameMatches(target, normalize(m.name))) m to d else null+ }+ .minByOrNull { it.second }+ ?.first+ }++ private fun nameMatches(a: String, b: String): Boolean {+ if (a.isEmpty() || b.isEmpty()) return false+ return a == b || a.contains(b) || b.contains(a)+ }++ /** Lowercase and strip everything but a–z/0–9 so "Joe's Café" ≈ "joes cafe". */+ private fun normalize(s: String): String =+ s.lowercase().replace(Regex("[^a-z0-9]"), "")++ private fun haversineMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {+ val r = 6_371_000.0+ val dLat = Math.toRadians(lat2 - lat1)+ val dLon = Math.toRadians(lon2 - lon1)+ val a = sin(dLat / 2) * sin(dLat / 2) ++ cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *+ sin(dLon / 2) * sin(dLon / 2)+ return r * 2 * atan2(sqrt(a), sqrt(1 - a))+ }++ companion object {+ /** How close a merchant must be to the queried point to be the same place. */+ private const val MATCH_RADIUS_METERS = 800.0+ }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.ktindex 8678dbef51..b9f5c7690a 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupContract.kt@@ -1,40 +1,17 @@ package com.vayunmathur.fooddelivery.ipc /**- * Wire contract for the cross-app "is this restaurant orderable?" lookup exposed- * by [OrderLookupProvider].+ * Wire contract for the `fooddelivery://restaurant/<id>` cross-app deep link that opens a specific+ * merchant's order page (e.g. from the maps place-sheet "Order" button, or returned by+ * `com.vayunmathur.fooddelivery.intents.OrderLookupIntent`). *- * A co-signed app (the maps app) queries the provider with a restaurant name +- * lat/lng (+ optional address) and gets back a single row telling it whether the- * place is orderable on this app and, if so, the deep link that opens its order- * page. The provider is gated by [PERMISSION] (signature-level), so only apps- * signed with the same key can read it; the two apps deliberately do NOT share a- * module — maps keeps its own byte-for-byte mirror of these constants.+ * The "is this restaurant orderable?" lookup that used to live here as a signature-guarded+ * ContentProvider is now the `OrderLookupIntent`+ * [AssistantIntent][com.vayunmathur.library.util.AssistantIntent] — a request/response fits+ * time-varying catalog data better than a cursor. Only the deep link remains here; it is parsed on+ * the way in by [com.vayunmathur.fooddelivery.MainActivity]. */ object OrderLookupContract {- /** Authority of the exported orderable-lookup [android.content.ContentProvider]. */- const val AUTHORITY = "com.vayunmathur.fooddelivery.orderlookup"-- /** Signature-level permission required to read the provider. */- const val PERMISSION = "com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS"-- /** Single query path: content://<AUTHORITY>/lookup?name=&lat=&lng=&address= */- const val PATH_LOOKUP = "lookup"-- // ---- query parameters (caller → provider) ----- const val PARAM_NAME = "name"- const val PARAM_LAT = "lat"- const val PARAM_LNG = "lng"- const val PARAM_ADDRESS = "address"-- // ---- result columns (provider → caller) ----- /** Int 1/0: whether a tolerant name+proximity match was found and is orderable. */- const val COL_ORDERABLE = "orderable"- /** Int: the matched merchant id (0 when not orderable). */- const val COL_RESTAURANT_ID = "restaurant_id"- /** String: deep link opening the matched merchant's order page ("" when not orderable). */- const val COL_DEEP_LINK = "deep_link_uri"- // ---- deep link (open a specific restaurant's order page) ---- const val DEEP_LINK_SCHEME = "fooddelivery" const val DEEP_LINK_HOST = "restaurant"
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.ktdeleted file mode 100644index c879f1788f..0000000000--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ipc/OrderLookupProvider.kt+++ /dev/null@@ -1,156 +0,0 @@-package com.vayunmathur.fooddelivery.ipc--import android.content.ContentProvider-import android.content.ContentValues-import android.database.Cursor-import android.database.MatrixCursor-import android.net.Uri-import com.vayunmathur.fooddelivery.api.BitesApi-import com.vayunmathur.fooddelivery.data.Merchant-import com.vayunmathur.fooddelivery.platform.AppInit-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.ExperimentalCoroutinesApi-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.async-import kotlinx.coroutines.runBlocking-import kotlinx.coroutines.withTimeoutOrNull-import kotlin.math.atan2-import kotlin.math.cos-import kotlin.math.sin-import kotlin.math.sqrt--/**- * Exported, signature-guarded lookup that answers "can I order from this- * restaurant?" for a co-signed app (the maps place sheet). See- * [OrderLookupContract].- *- * A caller queries `content://<AUTHORITY>/lookup?name=&lat=&lng=(&address=)`;- * the provider fetches the merchant catalog near that point ([BitesApi.getMerchants])- * and does a tolerant name-normalise + proximity match against it. It always- * returns exactly one row:- * - a match within [MATCH_RADIUS_METERS] whose normalised name matches →- * `orderable=1`, the merchant id, and its `fooddelivery://restaurant/<id>` deep link;- * - otherwise → `orderable=0` (empty id/deep link).- *- * Everything is wrapped so a network/parse failure degrades to a not-orderable- * row rather than throwing across the binder — the caller then simply shows no- * Order button.- */-@OptIn(ExperimentalCoroutinesApi::class)-class OrderLookupProvider : ContentProvider() {-- override fun onCreate(): Boolean {- // A provider is created on the main thread before Application.onCreate and before- // any Activity, so kick the network/token warm-up off to a background thread and- // return immediately rather than paying for it here. [findMatch] awaits it.- val ctx = context ?: return false- AppInit.start(ctx)- return true- }-- override fun query(- uri: Uri,- projection: Array<out String>?,- selection: String?,- selectionArgs: Array<out String>?,- sortOrder: String?,- ): Cursor {- val cursor = MatrixCursor(- arrayOf(- OrderLookupContract.COL_ORDERABLE,- OrderLookupContract.COL_RESTAURANT_ID,- OrderLookupContract.COL_DEEP_LINK,- )- )- val match = try {- findMatch(uri)- } catch (_: Exception) {- null- }- if (match != null) {- cursor.addRow(arrayOf<Any?>(1, match.id, OrderLookupContract.deepLink(match.id)))- } else {- cursor.addRow(arrayOf<Any?>(0, 0, ""))- }- return cursor- }-- private fun findMatch(uri: Uri): Merchant? {- val name = uri.getQueryParameter(OrderLookupContract.PARAM_NAME)?.trim().orEmpty()- val lat = uri.getQueryParameter(OrderLookupContract.PARAM_LAT)?.toDoubleOrNull()- val lng = uri.getQueryParameter(OrderLookupContract.PARAM_LNG)?.toDoubleOrNull()- if (name.isBlank() || lat == null || lng == null) return null-- val target = normalize(name)- if (target.isEmpty()) return null-- // This runs on a binder thread out of a 16-strong pool, and the request underneath- // can take the engine's full 30s connect / 60s read budget (three times over, if the- // auth path retries). Bound the wait: query() degrades to orderable=0 on a null match,- // so giving up is strictly better than holding the transaction open. The fetch runs on- // a scope of its own — cancelling a coroutine parked in a blocking socket read does not- // unblock it, so the timeout has to sit on a separate, cancellable suspension point.- val fetch = lookupScope.async {- AppInit.awaitReady()- BitesApi.getMerchants(lat, lng)- }- val merchants = runBlocking {- withTimeoutOrNull(LOOKUP_TIMEOUT_MS) { fetch.await() }- }- if (merchants == null) fetch.cancel()- if (merchants.isNullOrEmpty()) return null-- // Keep only merchants that are plausibly the same place: close enough AND- // whose normalised name matches (equal / prefix / containment). Pick the- // nearest such candidate.- return merchants- .mapNotNull { m ->- val d = haversineMeters(lat, lng, m.latitude, m.longitude)- if (d <= MATCH_RADIUS_METERS && nameMatches(target, normalize(m.name))) m to d else null- }- .minByOrNull { it.second }- ?.first- }-- private fun nameMatches(a: String, b: String): Boolean {- if (a.isEmpty() || b.isEmpty()) return false- return a == b || a.contains(b) || b.contains(a)- }-- /** Lowercase and strip everything but a–z/0–9 so "Joe's Café" ≈ "joes cafe". */- private fun normalize(s: String): String =- s.lowercase().replace(Regex("[^a-z0-9]"), "")-- private fun haversineMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {- val r = 6_371_000.0- val dLat = Math.toRadians(lat2 - lat1)- val dLon = Math.toRadians(lon2 - lon1)- val a = sin(dLat / 2) * sin(dLat / 2) +- cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *- sin(dLon / 2) * sin(dLon / 2)- return r * 2 * atan2(sqrt(a), sqrt(1 - a))- }-- override fun getType(uri: Uri): String? = null- override fun insert(uri: Uri, values: ContentValues?): Uri? = null- override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0- override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0-- companion object {- /** How close a merchant must be to the queried point to be the same place. */- private const val MATCH_RADIUS_METERS = 800.0-- /** Total budget for warm-up plus catalog fetch on the binder thread. */- private const val LOOKUP_TIMEOUT_MS = 3_000L-- private val lookupScope =- CoroutineScope(SupervisorJob() + Dispatchers.IO.limitedParallelism(MAX_INFLIGHT_LOOKUPS))-- /**- * A timed-out fetch keeps its thread until the engine's own timeouts fire, so cap how- * many can be in flight rather than letting a chatty caller drain [Dispatchers.IO].- */- private const val MAX_INFLIGHT_LOOKUPS = 4- }-}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.ktindex b60980fb0e..2025906760 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/AppInit.kt@@ -20,9 +20,9 @@ import java.util.concurrent.atomic.AtomicBoolean * initialises an SSLContext, and the saved auth token has to be read out of * SharedPreferences and JSON-decoded — none of which may happen on the main thread or a * binder thread. Both process entry points ([com.vayunmathur.fooddelivery.FoodDeliveryApplication]- * and [com.vayunmathur.fooddelivery.ipc.OrderLookupProvider], which is created first) call- * [start], which is idempotent; anything that needs the token or the pinned trust anchors- * awaits [awaitReady] from a coroutine instead of blocking.+ * and [com.vayunmathur.fooddelivery.intents.OrderLookupIntent], which may launch into a cold+ * process) call [start], which is idempotent; anything that needs the token or the pinned trust+ * anchors awaits [awaitReady] from a coroutine instead of blocking. */ object AppInit {
library/src/main/java/com/vayunmathur/library/intents/fooddelivery/OrderLookupData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/fooddelivery/OrderLookupData.kt b/library/src/main/java/com/vayunmathur/library/intents/fooddelivery/OrderLookupData.ktnew file mode 100644index 0000000000..38b43bb037--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/fooddelivery/OrderLookupData.kt@@ -0,0 +1,30 @@+package com.vayunmathur.library.intents.fooddelivery++import kotlinx.serialization.Serializable++/**+ * Shared wire DTOs for fooddelivery's cross-app order-lookup+ * [AssistantIntent][com.vayunmathur.library.util.AssistantIntent]+ * (`com.vayunmathur.fooddelivery.intents.OrderLookupIntent`), answered for a co-signed caller (the+ * maps place sheet). This replaces the old `content://com.vayunmathur.fooddelivery.orderlookup/lookup`+ * cursor: a ContentProvider is the wrong shape for a live, time-varying catalog match.+ */+@Serializable+data class OrderLookupRequest(+ val name: String,+ val lat: Double,+ val lng: Double,+ val address: String? = null,+)++/**+ * @property available whether a tolerant name+proximity match was found and is orderable.+ * @property merchantId matched merchant id (0 when not orderable).+ * @property deepLink `fooddelivery://restaurant/<id>` opening the matched order page ("" when not orderable).+ */+@Serializable+data class OrderLookupResult(+ val available: Boolean,+ val merchantId: Int,+ val deepLink: String,+)
library/src/main/java/com/vayunmathur/library/intents/maps/DirectionsData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/maps/DirectionsData.kt b/library/src/main/java/com/vayunmathur/library/intents/maps/DirectionsData.ktnew file mode 100644index 0000000000..958c92060d--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/maps/DirectionsData.kt@@ -0,0 +1,58 @@+package com.vayunmathur.library.intents.maps++import kotlinx.serialization.Serializable++/**+ * Shared wire types for maps' `DirectionsIntent`+ * [AssistantIntent][com.vayunmathur.library.util.AssistantIntent] — a co-signed caller (the+ * taxi app) asks maps to plan a route and gets back the polyline and the per-segment colouring+ * inputs it needs to draw the route inside its own `VectorMap` the way maps draws it.+ *+ * These are plain `@Serializable` doubles: [com.vayunmathur.library.map.GeoPoint] is not+ * serializable, so coordinates cross the process boundary as lat/lng pairs and the caller+ * rebuilds `GeoPoint`s on the far side.+ */+@Serializable+data class DirectionsRequest(+ val fromLat: Double,+ val fromLng: Double,+ val toLat: Double,+ val toLng: Double,+ /**+ * Travel mode, matching `RouteService.TravelMode` case-insensitively (`drive`, `transit`,+ * `walk`, `bicycle`). Anything unrecognised is planned as driving — the taxi caller only+ * ever asks for a driving route.+ */+ val mode: String,+)++/**+ * A planned route: the full [polyline] for framing, the coloured [segments] for drawing, and+ * the trip totals.+ *+ * An empty [polyline]/[segments] means no route could be planned (e.g. the pack cannot route+ * the pair) — the caller draws nothing rather than treating it as an error.+ */+@Serializable+data class DirectionsResult(+ val polyline: List<DirectionsLatLng>,+ val segments: List<DirectionsSegment>,+ val distanceMeters: Double,+ val durationSeconds: Double,+)++/** A single coordinate, lat/lng, the serializable stand-in for a `GeoPoint`. */+@Serializable+data class DirectionsLatLng(val lat: Double, val lng: Double)++/**+ * One coloured run of the route: its own [points] and the traffic [speedRatio] that decides+ * its colour. This mirrors the per-step split maps' `RouteOverlayBuilder` produces, so the+ * caller colours each run by the same red/amber/green congestion ramp maps uses+ * (`< 0.5` jam, `< 0.9` slow, else free).+ */+@Serializable+data class DirectionsSegment(+ val points: List<DirectionsLatLng>,+ val speedRatio: Double,+)
library/src/main/java/com/vayunmathur/library/intents/taxi/RideEstimateData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/taxi/RideEstimateData.kt b/library/src/main/java/com/vayunmathur/library/intents/taxi/RideEstimateData.ktnew file mode 100644index 0000000000..391ef3a3b0--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/taxi/RideEstimateData.kt@@ -0,0 +1,31 @@+package com.vayunmathur.library.intents.taxi++import kotlinx.serialization.Serializable++/**+ * Shared wire DTOs for taxi's cross-app ride-estimate [AssistantIntent][com.vayunmathur.library.util.AssistantIntent]+ * (`com.vayunmathur.taxi.intents.RideEstimateIntent`), answered for a co-signed caller (the maps+ * route sheet). This replaces the old `content://com.vayunmathur.taxi.ridelookup/estimate` cursor:+ * a ContentProvider is the wrong shape for a live, time-varying quote.+ */+@Serializable+data class RideEstimateRequest(+ val pickupLat: Double,+ val pickupLng: Double,+ val destLat: Double,+ val destLng: Double,+ val pickupLabel: String? = null,+ val destLabel: String? = null,+)++/**+ * @property available whether a live quote was found for the trip.+ * @property fareEstimate formatted fare (e.g. "$12.50" or "$12.50 – $15.00"); "" when unavailable.+ * @property etaMinutes pickup ETA in minutes; -1 when unknown/unavailable.+ */+@Serializable+data class RideEstimateResult(+ val available: Boolean,+ val fareEstimate: String,+ val etaMinutes: Int,+)
library/src/test/java/com/vayunmathur/library/intents/IpcDtoRoundTripTest.kt
diff --git a/library/src/test/java/com/vayunmathur/library/intents/IpcDtoRoundTripTest.kt b/library/src/test/java/com/vayunmathur/library/intents/IpcDtoRoundTripTest.ktnew file mode 100644index 0000000000..7ba0843bbe--- /dev/null+++ b/library/src/test/java/com/vayunmathur/library/intents/IpcDtoRoundTripTest.kt@@ -0,0 +1,107 @@+package com.vayunmathur.library.intents++import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult+import com.vayunmathur.library.intents.taxi.RideEstimateRequest+import com.vayunmathur.library.intents.taxi.RideEstimateResult+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * The WS-C cross-app IPC DTOs travel as JSON strings over the `AssistantIntent` ResultReceiver+ * binder (encoded by the host, decoded by the maps client). These assert each type survives a+ * JSON round-trip unchanged — including the nullable `*Label` / `address` fields both present and+ * absent, since those are what an optional query parameter maps to.+ */+class IpcDtoRoundTripTest {++ private val json = Json++ @Test+ fun rideEstimateRequest_roundTrips_withLabels() {+ val original = RideEstimateRequest(+ pickupLat = 37.7749, pickupLng = -122.4194,+ destLat = 34.0522, destLng = -118.2437,+ pickupLabel = "Home", destLabel = "Work",+ )+ val decoded = json.decodeFromString(+ RideEstimateRequest.serializer(),+ json.encodeToString(RideEstimateRequest.serializer(), original),+ )+ assertEquals(original, decoded)+ }++ @Test+ fun rideEstimateRequest_roundTrips_withoutLabels() {+ val original = RideEstimateRequest(+ pickupLat = 1.0, pickupLng = 2.0, destLat = 3.0, destLng = 4.0,+ )+ val decoded = json.decodeFromString(+ RideEstimateRequest.serializer(),+ json.encodeToString(RideEstimateRequest.serializer(), original),+ )+ assertEquals(original, decoded)+ assertEquals(null, decoded.pickupLabel)+ assertEquals(null, decoded.destLabel)+ }++ @Test+ fun rideEstimateResult_roundTrips_available() {+ val original = RideEstimateResult(available = true, fareEstimate = "$12.50 – $15.00", etaMinutes = 4)+ val decoded = json.decodeFromString(+ RideEstimateResult.serializer(),+ json.encodeToString(RideEstimateResult.serializer(), original),+ )+ assertEquals(original, decoded)+ }++ @Test+ fun rideEstimateResult_roundTrips_unavailable() {+ val original = RideEstimateResult(available = false, fareEstimate = "", etaMinutes = -1)+ val decoded = json.decodeFromString(+ RideEstimateResult.serializer(),+ json.encodeToString(RideEstimateResult.serializer(), original),+ )+ assertEquals(original, decoded)+ }++ @Test+ fun orderLookupRequest_roundTrips_withAndWithoutAddress() {+ val withAddress = OrderLookupRequest(name = "Joe's Café", lat = 10.0, lng = 20.0, address = "1 Main St")+ val withoutAddress = OrderLookupRequest(name = "Joe's Café", lat = 10.0, lng = 20.0)+ assertEquals(+ withAddress,+ json.decodeFromString(+ OrderLookupRequest.serializer(),+ json.encodeToString(OrderLookupRequest.serializer(), withAddress),+ ),+ )+ val decodedWithout = json.decodeFromString(+ OrderLookupRequest.serializer(),+ json.encodeToString(OrderLookupRequest.serializer(), withoutAddress),+ )+ assertEquals(withoutAddress, decodedWithout)+ assertEquals(null, decodedWithout.address)+ }++ @Test+ fun orderLookupResult_roundTrips_orderableAndNot() {+ val orderable = OrderLookupResult(available = true, merchantId = 42, deepLink = "fooddelivery://restaurant/42")+ val notOrderable = OrderLookupResult(available = false, merchantId = 0, deepLink = "")+ assertEquals(+ orderable,+ json.decodeFromString(+ OrderLookupResult.serializer(),+ json.encodeToString(OrderLookupResult.serializer(), orderable),+ ),+ )+ assertEquals(+ notOrderable,+ json.decodeFromString(+ OrderLookupResult.serializer(),+ json.encodeToString(OrderLookupResult.serializer(), notOrderable),+ ),+ )+ }+}
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex 66564cbec8..75a365ea45 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -33,6 +33,12 @@ <package android:name="com.vayunmathur.taxi" /> </queries> + <!-- Guards the exported DirectionsIntent so only same-signature installs (the taxi app)+ can ask maps to plan a route. -->+ <permission+ android:name="com.vayunmathur.maps.permissions.ACCESS_MAPS"+ android:protectionLevel="signature" />+ <application android:largeHeap="true"@@ -83,6 +89,12 @@ </intent-filter> </activity> + <activity+ android:name=".intents.DirectionsIntent"+ android:exported="true"+ android:theme="@android:style/Theme.NoDisplay"+ android:permission="com.vayunmathur.maps.permissions.ACCESS_MAPS" />+ <service android:name=".util.NavigationService" android:foregroundServiceType="location"
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 5f1d1dac66..d1be243bcc 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -19,6 +19,7 @@ import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.OfflineAware import com.vayunmathur.library.ui.PermissionsChecker import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.IntentLauncher import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack@@ -31,6 +32,7 @@ import com.vayunmathur.maps.ui.SavedPlacesPage import com.vayunmathur.maps.ui.settings.MapSettingsPage import com.vayunmathur.maps.data.MapPreferences import com.vayunmathur.maps.data.ThemeMode+import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.NavigationService import com.vayunmathur.maps.util.NavigationSessionManager@@ -50,6 +52,15 @@ import java.io.File class MainActivity : ComponentActivity() { + companion object {+ private const val TAG = "MapsIntent"++ // Hosts the cross-app AssistantIntent client for maps (mirrors taxi/openassistant+ // MainActivity.intentLauncher). WS-C's RideEstimate/OrderLookup clients launch taxi's+ // and fooddelivery's intents through this.+ lateinit var intentLauncher: IntentLauncher+ }+ // Same instances the Compose tree gets via viewModel() (both resolve to this // Activity's ViewModelStore), so an external geo:/maps/navigation intent handled // here shows up in the map UI: selecting a place opens its bottom pane, and a@@ -62,6 +73,7 @@ class MainActivity : ComponentActivity() { // FIRST_PARTY: data.vayunmathur.com tiles + amenities + api.vayunmathur.com -> ISRG+GTS NetworkClient.init(this, TrustBundle.FIRST_PARTY) enableEdgeToEdge()+ intentLauncher = IntentLauncher(this) // Reclaim the ~44 MB bundled basemap copied into filesDir by older // builds; the basemap now streams live and is cached on demand. File(filesDir, "world_z0-6.pmtiles").delete()@@ -103,7 +115,15 @@ class MainActivity : ComponentActivity() { // a device that ends up without them is slow rather than broken. Triple("https://data.vayunmathur.com/poi_spatial.bin", "poi_spatial.bin", getString(R.string.downloading_poi_data)), Triple("https://data.vayunmathur.com/poi_name_index.bin", "poi_name_index.bin", getString(R.string.downloading_poi_data)),- Triple("https://data.vayunmathur.com/world.transit", "world.transit", getString(R.string.downloading_transit_data))+ Triple("https://data.vayunmathur.com/world.transit", "world.transit", getString(R.string.downloading_transit_data)),+ // The basemap itself. It used to be range-requested for the life of the+ // install, which made every pan over cold ground a network round trip and+ // the map unusable off-grid; fetched once it is a plain file the renderer+ // mmaps. Same hosting hazard as the sidecars above, and a much larger one+ // here: this entry gates app start, so the URL must be live before the+ // version ships. An `adb push` to the same filename satisfies the gate,+ // which is how a locally built archive is sideloaded.+ Triple(MapTileCache.BASEMAP_ARCHIVE_URL, MapTileCache.BASEMAP_ARCHIVE_FILE, getString(R.string.downloading_basemap)) )) { val perms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { // POST_NOTIFICATIONS is runtime-grantable on API 33+@@ -264,10 +284,6 @@ class MainActivity : ComponentActivity() { name = name, phone = null, website = null, openingHours = null, position = GeoPoint(lng, lat), )-- companion object {- private const val TAG = "MapsIntent"- } } @Serializable
maps/src/main/java/com/vayunmathur/maps/intents/DirectionsIntent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/intents/DirectionsIntent.kt b/maps/src/main/java/com/vayunmathur/maps/intents/DirectionsIntent.ktnew file mode 100644index 0000000000..9c29e5d396--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/intents/DirectionsIntent.kt@@ -0,0 +1,87 @@+package com.vayunmathur.maps.intents++import com.vayunmathur.library.intents.maps.DirectionsLatLng+import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.maps.DirectionsResult+import com.vayunmathur.library.intents.maps.DirectionsSegment+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.util.OfflineRouter+import com.vayunmathur.maps.util.RouteService+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.serializer++/**+ * Answers a co-signed caller's request to plan a route, exported as a signature-guarded+ * (`com.vayunmathur.maps.permissions.ACCESS_MAPS`) NoDisplay+ * [AssistantIntent][com.vayunmathur.library.util.AssistantIntent].+ *+ * The route is planned by the same on-device [OfflineRouter.getRouteForMode] the app itself+ * uses, and mapped to a [DirectionsResult] carrying the polyline plus the per-step traffic+ * [speedRatio][RouteService.Step.speedRatio] — the colour input the caller needs to draw the+ * route with maps' own red/amber/green congestion ramp (see maps' `RouteOverlayBuilder`).+ */+@OptIn(InternalSerializationApi::class)+class DirectionsIntent : AssistantIntent<DirectionsRequest, DirectionsResult>(+ serializer<DirectionsRequest>(),+ serializer<DirectionsResult>(),+) {+ override suspend fun performCalculation(input: DirectionsRequest): DirectionsResult {+ val start = GeoPoint(input.fromLng, input.fromLat)+ val end = GeoPoint(input.toLng, input.toLat)+ val request = SpecificFeature.Route(+ listOf(+ SpecificFeature.GenericPlace(+ name = "From",+ phone = null,+ website = null,+ openingHours = null,+ position = start,+ ),+ SpecificFeature.GenericPlace(+ name = "To",+ phone = null,+ website = null,+ openingHours = null,+ position = end,+ ),+ ),+ )+ val route = OfflineRouter.getRouteForMode(this, request, start, parseMode(input.mode))+ ?: return EMPTY+ return route.toDirectionsResult()+ }++ /**+ * Match the wire mode string onto [RouteService.TravelMode] case-insensitively. Anything+ * unrecognised routes as driving — the taxi caller only ever asks for a driving route, and+ * the road graph is the correct planner for it.+ */+ private fun parseMode(mode: String): RouteService.TravelMode =+ when (mode.trim().uppercase()) {+ "TRANSIT" -> RouteService.TravelMode.TRANSIT+ "WALK", "WALKING" -> RouteService.TravelMode.WALK+ "BICYCLE", "BIKE", "BICYCLING" -> RouteService.TravelMode.BICYCLE+ else -> RouteService.TravelMode.DRIVE+ }++ private fun RouteService.Route.toDirectionsResult(): DirectionsResult =+ DirectionsResult(+ polyline = polyline.map { DirectionsLatLng(it.latitude, it.longitude) },+ // One segment per step, mirroring RouteOverlayBuilder's non-navigating case, so the+ // caller can colour each run by its own traffic band. Degenerate steps are dropped.+ segments = step.filter { it.polyline.size >= 2 }.map { step ->+ DirectionsSegment(+ points = step.polyline.map { DirectionsLatLng(it.latitude, it.longitude) },+ speedRatio = step.speedRatio,+ )+ },+ distanceMeters = distanceMeters,+ durationSeconds = duration.inWholeSeconds.toDouble(),+ )++ private companion object {+ val EMPTY = DirectionsResult(emptyList(), emptyList(), 0.0, 0.0)+ }+}
maps/src/main/java/com/vayunmathur/maps/ipc/IntentLaunch.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ipc/IntentLaunch.kt b/maps/src/main/java/com/vayunmathur/maps/ipc/IntentLaunch.ktnew file mode 100644index 0000000000..4ee8a40c17--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ipc/IntentLaunch.kt@@ -0,0 +1,31 @@+package com.vayunmathur.maps.ipc++import android.content.Context+import com.vayunmathur.maps.MainActivity+import kotlinx.serialization.json.Json+import kotlinx.serialization.serializer++/**+ * Raised when the target app isn't installed, so callers can degrade to null (show no+ * cross-app option) instead of waiting for a result that never comes. Mirrors openassistant's+ * `MissingAppException`.+ */+class MissingAppException(val packageName: String) : Exception("App $packageName is not installed.")++/**+ * Bridges a suspend call to another app's [AssistantIntent][com.vayunmathur.library.util.AssistantIntent]+ * activity via maps' [MainActivity.intentLauncher] (mirrors openassistant's `launchIntent`). Decodes+ * the JSON reply for you and maps a missing package to [MissingAppException].+ */+suspend inline fun <reified In : Any, reified Out : Any> launchIntent(+ context: Context,+ packageName: String,+ className: String,+ input: In,+): Out {+ val out = MainActivity.intentLauncher.launch(+ context, packageName, className, serializer<In>(), input,+ )+ if (out == "package $packageName doesn't exist") throw MissingAppException(packageName)+ return Json.decodeFromString(serializer<Out>(), out)+}
maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt b/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.ktindex db6c934363..3f124c0b5d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ipc/OrderLookupClient.kt@@ -1,70 +1,49 @@ package com.vayunmathur.maps.ipc import android.content.Context-import android.net.Uri import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.produceState+import com.vayunmathur.library.intents.fooddelivery.OrderLookupRequest+import com.vayunmathur.library.intents.fooddelivery.OrderLookupResult import com.vayunmathur.maps.data.SpecificFeature-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext -/**- * Byte-for-byte mirror of fooddelivery's `OrderLookupContract`.- *- * As with the P18 family-location channel, the two apps deliberately do NOT share- * a module: the contract is just an authority, a signature permission and a- * handful of query-param / column names, so duplicating it here keeps maps- * decoupled from fooddelivery's source while still reading the same provider.- * Reading is gated by the signature permission [PERMISSION] (both MA apps share- * the signing key).- */-object OrderLookupContract {- const val AUTHORITY = "com.vayunmathur.fooddelivery.orderlookup"- const val PERMISSION = "com.vayunmathur.fooddelivery.permissions.ACCESS_ORDERS"- const val PATH_LOOKUP = "lookup"-- const val PARAM_NAME = "name"- const val PARAM_LAT = "lat"- const val PARAM_LNG = "lng"- const val PARAM_ADDRESS = "address"-- const val COL_ORDERABLE = "orderable"- const val COL_RESTAURANT_ID = "restaurant_id"- const val COL_DEEP_LINK = "deep_link_uri"-}+/** Package of the MA fooddelivery app. */+private const val FOODDELIVERY_PACKAGE = "com.vayunmathur.fooddelivery"+private const val ORDER_LOOKUP_CLASS = "com.vayunmathur.fooddelivery.intents.OrderLookupIntent" /** Result of an orderable lookup: whether it's orderable and, if so, its deep link. */ data class OrderInfo(val orderable: Boolean, val deepLinkUri: String?) /**- * Reads fooddelivery's exported orderable-lookup provider (see- * [OrderLookupContract]) for a place at [name] / [lat] / [lng].+ * Reads fooddelivery's exported orderable-lookup intent+ * (`com.vayunmathur.fooddelivery.intents.OrderLookupIntent`) for a place at [name] / [lat] / [lng]. *- * Absence handling is total: if fooddelivery isn't installed the authority- * resolves to no provider and the query returns null; if the signature- * permission isn't held it throws [SecurityException]; a malformed reply or any- * other failure is caught. In every one of those cases this returns null and the+ * Absence handling is total: if fooddelivery isn't installed the launch reports a missing package+ * ([MissingAppException]); if the signature permission isn't held it throws [SecurityException]; a+ * timeout or malformed reply throws too. In every one of those cases this returns null and the * caller simply shows no Order button — no crash. */ object OrderLookupClient {- fun lookup(context: Context, name: String, lat: Double, lng: Double, address: String? = null): OrderInfo? {+ suspend fun lookup(+ context: Context,+ name: String,+ lat: Double,+ lng: Double,+ address: String? = null,+ ): OrderInfo? { if (name.isBlank()) return null- val uri = Uri.parse("content://${OrderLookupContract.AUTHORITY}/${OrderLookupContract.PATH_LOOKUP}")- .buildUpon()- .appendQueryParameter(OrderLookupContract.PARAM_NAME, name)- .appendQueryParameter(OrderLookupContract.PARAM_LAT, lat.toString())- .appendQueryParameter(OrderLookupContract.PARAM_LNG, lng.toString())- .apply { if (!address.isNullOrBlank()) appendQueryParameter(OrderLookupContract.PARAM_ADDRESS, address) }- .build() return try {- context.contentResolver.query(uri, null, null, null, null)?.use { c ->- if (!c.moveToFirst()) return null- val orderable = c.getInt(c.getColumnIndexOrThrow(OrderLookupContract.COL_ORDERABLE)) == 1- if (!orderable) return OrderInfo(false, null)- val deepLink = c.getString(c.getColumnIndexOrThrow(OrderLookupContract.COL_DEEP_LINK))- ?.ifBlank { null }- OrderInfo(true, deepLink)+ val result: OrderLookupResult = launchIntent(+ context,+ FOODDELIVERY_PACKAGE,+ ORDER_LOOKUP_CLASS,+ OrderLookupRequest(name, lat, lng, address?.ifBlank { null }),+ )+ if (!result.available) {+ OrderInfo(false, null)+ } else {+ OrderInfo(true, result.deepLink.ifBlank { null }) } } catch (_: SecurityException) { null@@ -93,9 +72,8 @@ private fun isOrderableCandidate(feature: SpecificFeature.RoutableFeature, categ * For a selected restaurant/food place, resolve fooddelivery's order deep link * (or null if it isn't a food place, isn't orderable, or fooddelivery is absent). *- * The provider query runs on [Dispatchers.IO]; the state re-resolves whenever the- * selection or its enrichment category changes. Non-food places short-circuit- * without ever touching the provider.+ * The lookup runs off the main thread; the state re-resolves whenever the selection or its+ * enrichment category changes. Non-food places short-circuit without ever launching the intent. */ @Composable fun rememberOrderDeepLink(@@ -105,8 +83,8 @@ fun rememberOrderDeepLink( ): State<String?> = produceState<String?>(null, feature.name, feature.position, category) { value = null if (!isOrderableCandidate(feature, category)) return@produceState- val info = withContext(Dispatchers.IO) {- OrderLookupClient.lookup(context, feature.name, feature.position.latitude, feature.position.longitude)- }+ val info = OrderLookupClient.lookup(+ context, feature.name, feature.position.latitude, feature.position.longitude,+ ) value = info?.takeIf { it.orderable }?.deepLinkUri }
maps/src/main/java/com/vayunmathur/maps/ipc/RideEstimateClient.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ipc/RideEstimateClient.kt b/maps/src/main/java/com/vayunmathur/maps/ipc/RideEstimateClient.ktindex 62d59d32ce..3cc8a20d89 100644--- a/maps/src/main/java/com/vayunmathur/maps/ipc/RideEstimateClient.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ipc/RideEstimateClient.kt@@ -1,28 +1,26 @@ package com.vayunmathur.maps.ipc import android.content.Context-import android.net.Uri import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.produceState import androidx.core.net.toUri-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext+import com.vayunmathur.library.intents.taxi.RideEstimateRequest+import com.vayunmathur.library.intents.taxi.RideEstimateResult /**- * Byte-for-byte mirror of taxi's `RideHandoffContract`.+ * Byte-for-byte mirror of the deep-link half of taxi's `RideHandoffContract`. *- * As with the P18 family-location channel and the P19 order-lookup channel, the two apps- * deliberately do NOT share a module: the contract is just an authority, a signature permission,- * a deep-link shape and a handful of query-param / column names, so duplicating it here keeps maps- * decoupled from taxi's source while still reading the same provider and building the same deep- * link. Reading the provider is gated by the signature permission [PERMISSION] (both MA apps share- * the signing key).+ * The live fare/ETA estimate is now taxi's `RideEstimateIntent`+ * [AssistantIntent][com.vayunmathur.library.util.AssistantIntent] (read via [RideEstimateClient]);+ * only the `taxi://book` booking deep link — a separate fire-and-forget hand-off — lives here. As+ * with the P18 family-location and P19 order-lookup channels, the two apps deliberately do NOT+ * share a module: duplicating a scheme, host and a handful of param names keeps maps decoupled from+ * taxi's source while still building the same deep link. */ object RideHandoffContract {- const val AUTHORITY = "com.vayunmathur.taxi.ridelookup"- const val PERMISSION = "com.vayunmathur.taxi.permissions.ACCESS_RIDES"- const val PATH_ESTIMATE = "estimate"+ /** Package of the MA taxi app, for the Android 11+ package-visibility / installed check. */+ const val PACKAGE = "com.vayunmathur.taxi" const val PARAM_PICKUP_LAT = "pickup_lat" const val PARAM_PICKUP_LNG = "pickup_lng"@@ -31,16 +29,9 @@ object RideHandoffContract { const val PARAM_DEST_LNG = "dest_lng" const val PARAM_DEST_LABEL = "dest_label" - const val COL_AVAILABLE = "available"- const val COL_FARE_ESTIMATE = "fare_estimate"- const val COL_ETA_MINUTES = "eta_minutes"- const val DEEP_LINK_SCHEME = "taxi" const val DEEP_LINK_HOST = "book" - /** Package of the MA taxi app, for the Android 11+ package-visibility / installed check. */- const val PACKAGE = "com.vayunmathur.taxi"- /** Builds the `taxi://book?…` deep link that opens the taxi app with this trip pre-filled. */ fun bookingDeepLink( pickupLat: Double,@@ -68,15 +59,17 @@ data class RideEstimate( ) /**- * Reads taxi's exported ride-estimate provider (see [RideHandoffContract]) for an- * origin→destination.+ * Reads taxi's exported ride-estimate intent (`com.vayunmathur.taxi.intents.RideEstimateIntent`)+ * for an origin→destination. *- * Absence handling is total: if taxi isn't installed the authority resolves to no provider and the- * query returns null; if the signature permission isn't held it throws [SecurityException]; a- * malformed reply or any other failure is caught. In every one of those cases this returns null- * and the caller shows the launch-only option (or none) — no crash.+ * Absence handling is total: if taxi isn't installed the launch reports a missing package+ * ([MissingAppException]); if the signature permission isn't held it throws [SecurityException]; a+ * timeout or malformed reply throws too. In every one of those cases this returns null and the+ * caller shows the launch-only option (or none) — no crash. */ object RideEstimateClient {+ private const val CLASS_NAME = "com.vayunmathur.taxi.intents.RideEstimateIntent"+ /** Whether the MA taxi app is installed (so the option is worth offering at all). */ fun isInstalled(context: Context): Boolean = runCatching {@@ -84,7 +77,7 @@ object RideEstimateClient { context.packageManager.getPackageInfo(RideHandoffContract.PACKAGE, 0) }.isSuccess - fun estimate(+ suspend fun estimate( context: Context, pickupLat: Double, pickupLng: Double,@@ -93,27 +86,24 @@ object RideEstimateClient { pickupLabel: String? = null, destLabel: String? = null, ): RideEstimate? {- val uri = Uri.parse("content://${RideHandoffContract.AUTHORITY}/${RideHandoffContract.PATH_ESTIMATE}")- .buildUpon()- .appendQueryParameter(RideHandoffContract.PARAM_PICKUP_LAT, pickupLat.toString())- .appendQueryParameter(RideHandoffContract.PARAM_PICKUP_LNG, pickupLng.toString())- .appendQueryParameter(RideHandoffContract.PARAM_DEST_LAT, destLat.toString())- .appendQueryParameter(RideHandoffContract.PARAM_DEST_LNG, destLng.toString())- .apply {- if (!pickupLabel.isNullOrBlank()) appendQueryParameter(RideHandoffContract.PARAM_PICKUP_LABEL, pickupLabel)- if (!destLabel.isNullOrBlank()) appendQueryParameter(RideHandoffContract.PARAM_DEST_LABEL, destLabel)- }- .build() return try {- context.contentResolver.query(uri, null, null, null, null)?.use { c ->- if (!c.moveToFirst()) return null- val available = c.getInt(c.getColumnIndexOrThrow(RideHandoffContract.COL_AVAILABLE)) == 1- if (!available) return RideEstimate(false, null, null)- val fare = c.getString(c.getColumnIndexOrThrow(RideHandoffContract.COL_FARE_ESTIMATE))- ?.ifBlank { null }- val eta = c.getInt(c.getColumnIndexOrThrow(RideHandoffContract.COL_ETA_MINUTES))- .takeIf { it >= 0 }- RideEstimate(true, fare, eta)+ val result: RideEstimateResult = launchIntent(+ context,+ RideHandoffContract.PACKAGE,+ CLASS_NAME,+ RideEstimateRequest(+ pickupLat, pickupLng, destLat, destLng,+ pickupLabel?.ifBlank { null }, destLabel?.ifBlank { null },+ ),+ )+ if (!result.available) {+ RideEstimate(false, null, null)+ } else {+ RideEstimate(+ true,+ result.fareEstimate.ifBlank { null },+ result.etaMinutes.takeIf { it >= 0 },+ ) } } catch (_: SecurityException) { null@@ -139,7 +129,7 @@ fun rememberRideEstimate( ): State<RideEstimate?> = produceState<RideEstimate?>( null, pickupLat, pickupLng, destLat, destLng, pickupLabel, destLabel, ) {- value = withContext(Dispatchers.IO) {- RideEstimateClient.estimate(context, pickupLat, pickupLng, destLat, destLng, pickupLabel, destLabel)- }+ value = RideEstimateClient.estimate(+ context, pickupLat, pickupLng, destLat, destLng, pickupLabel, destLabel,+ ) }
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 f337430bc0..99d5a8e9ae 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -616,6 +616,7 @@ fun MapPage( onToggleNorthUp = { chrome.northUp = !chrome.northUp }, destinationName = navSession.destinationName, darkBasemap = darkMap,+ route = navSession.route, ) MapOverlays(
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.ktindex 676b9b0930..0e8323d4fc 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt@@ -80,6 +80,7 @@ fun NavigationOverlay( onToggleNorthUp: () -> Unit = {}, destinationName: String? = null, darkBasemap: Boolean = false,+ route: RouteService.Route? = null, modifier: Modifier = Modifier, ) { if (navState is NavigationSessionManager.NavState.Idle) return@@ -182,6 +183,7 @@ fun NavigationOverlay( steps = steps, currentStepIndex = navState.progress.currentStepIndex, onClose = { showSteps = false },+ route = route, // Insets before the clearance padding, matching the speedometer above. The // two were in opposite orders, which shifted them apart by the nav-bar // height on top of the clearance they already disagreed on.
maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.ktindex 7b8d23f4ff..40adb872ec 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt@@ -58,6 +58,7 @@ import com.vayunmathur.maps.data.google.PoiSection import com.vayunmathur.maps.data.timeFormat import com.vayunmathur.maps.util.SelectedFeatureViewModel import kotlinx.coroutines.launch+import kotlinx.datetime.DayOfWeek import kotlinx.datetime.TimeZone import kotlinx.datetime.format import kotlinx.datetime.toLocalDateTime@@ -116,16 +117,22 @@ private fun PlaceSheetContent( val selectedSection by viewModel.poiSection.collectAsState() val context = LocalContext.current - // Google wins on hours when it has them, and OSM fills in otherwise — including- // offline, where the fetch simply returns nothing (there is no connectivity- // check anywhere in this module, and none is needed: a failed request is- // indistinguishable from "no data", which is exactly the behaviour wanted).- val googleHours = poi?.hours.orEmpty()- val osmHours = openingHours?.takeIf { googleHours.isEmpty() }+ // OSM is the source of truth for the weekly schedule: it carries all seven days,+ // and it is what renders. Google's keyless scrape only ever returns *today* (see+ // GooglePoiDataSource.readHours), so it cannot be a schedule — it is a live+ // override for the single day it knows about. We hand that one day to OsmHours,+ // which swaps it into today's row (flagged "Live") and keeps the other six from+ // OSM. Only when OSM has nothing at all do we fall back to showing Google's lone+ // line through the enrichment's own hours section.+ //+ // There is no connectivity check anywhere in this module, and none is needed: a+ // failed request is indistinguishable from "no data", which is exactly the+ // behaviour wanted.+ val todayOverride = googleTodayHours(poi?.hours.orEmpty()) PlaceTabPanel( poi, resolvePoiSection(selectedSection, poi),- showGoogleHours = osmHours == null,+ showGoogleHours = openingHours == null, modifier = modifier, ) { // Departures (train/transit stations): resolve the nearest Transitous@@ -137,10 +144,28 @@ private fun PlaceSheetContent( RestaurantItem({ IconMenuBook() }, stringResource(R.string.menu_label)) { goto(context, it) } } address?.let { AddressRow(it) }- osmHours?.let { OsmHours(it) }+ openingHours?.let { OsmHours(it, todayOverride) } } } +/**+ * Google's lone "today" hours line reduced to (day, hours), or null if it sent nothing+ * usable.+ *+ * The scrape returns at most one entry, shaped `"Tuesday: 6 AM–10 PM"` — the day it+ * names is today (see GooglePoiDataSource.readHours). We key it by that named day rather+ * than by the device clock so a row only ever gets overridden by a line that actually+ * claims to be that day.+ */+private fun googleTodayHours(lines: List<String>): Pair<DayOfWeek, String>? {+ val line = lines.firstOrNull() ?: return null+ val dayName = line.substringBefore(':', "").trim()+ val hours = line.substringAfter(':', "").trim()+ if (hours.isEmpty()) return null+ val day = DayOfWeek.entries.firstOrNull { it.name.equals(dayName, ignoreCase = true) } ?: return null+ return day to hours+}+ /** * The panel below a place sheet's tab row: the keyless Google enrichment for whichever * section is selected, plus the OSM-derived rows on Details.@@ -222,7 +247,7 @@ internal fun RatingStars(rating: Double, modifier: Modifier = Modifier) { } @Composable-private fun OsmHours(openingHours: OpeningHours) {+private fun OsmHours(openingHours: OpeningHours, todayOverride: Pair<DayOfWeek, String>? = null) { var showDetails by remember { mutableStateOf(false) } val now = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())@@ -234,6 +259,7 @@ private fun OsmHours(openingHours: OpeningHours) { val opensAtStr = stringResource(R.string.opens_at, nextChangeTime.time.format(timeFormat)) val openColor = MaterialTheme.colorScheme.tertiary val closedColor = MaterialTheme.colorScheme.error+ val liveLabel = stringResource(R.string.poi_hours_live) val text = AnnotatedString.Builder().apply { if (isOpen) withStyle(SpanStyle(openColor)) { append(openStr) } else withStyle(SpanStyle(closedColor)) { append(closedStr) } append(" \u2022 ")@@ -252,10 +278,20 @@ private fun OsmHours(openingHours: OpeningHours) { Spacer(Modifier.padding(2.dp)) Card(shape = verticalShape(1, 2)) { for ((day, hours) in openingHours.openingHours()) {+ // Today's row shows Google's live value when it sent one, tagged so+ // the swap is visible; the other six stay straight off OSM.+ val live = todayOverride?.takeIf { it.first == day }?.second+ val trailing = if (live != null) {+ AnnotatedString.Builder().apply {+ append(live)+ append(" ")+ withStyle(SpanStyle(openColor)) { append(liveLabel) }+ }.toAnnotatedString()+ } else AnnotatedString(hours) ListItem( { Text(day.name.lowercase().firstLetterUppercase()) }, leadingContent = {},- trailingContent = { Text(hours) },+ trailingContent = { Text(trailing) }, colors = ListItemDefaults.colors(Color.Transparent), ) }
maps/src/main/java/com/vayunmathur/maps/ui/RouteLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RouteLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RouteLayer.ktdeleted file mode 100644index 7aa0e37909..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/ui/RouteLayer.kt+++ /dev/null@@ -1,213 +0,0 @@-package com.vayunmathur.maps.ui--import androidx.compose.foundation.Canvas-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.runtime.Composable-import androidx.compose.runtime.remember-import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.Path-import androidx.compose.ui.graphics.StrokeCap-import androidx.compose.ui.graphics.StrokeJoin-import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.platform.LocalDensity-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.map.CameraState-import com.vayunmathur.maps.data.Feature1-import com.vayunmathur.maps.data.LineString-import com.vayunmathur.maps.ui.theme.MapTokens-import com.vayunmathur.maps.ui.theme.toStyleHex-import com.vayunmathur.maps.util.NavigationProgress-import com.vayunmathur.maps.util.RouteService-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive--/**- * The route polyline, drawn as plain Compose over VectorMap.- *- * Was a GeoJSON source + `LineLayer` (data-driven `route-color`); the renderer has no- * vector-layer API, so each per-step segment is projected through library:map's Projection- * and drawn on a Canvas with the same 8 dp round-cap stroke. The segment-colouring logic- * (static mode colours + the travelled-gray split at the snapped point) is unchanged —- * only the last mile (GeoJSON → layer) became Canvas.- */-@Composable-fun RouteLayer(- route: RouteService.Route,- navProgress: NavigationProgress?,- tokens: MapTokens,- cameraState: CameraState,-) {- val density = LocalDensity.current- val segments = remember(- route, tokens,- navProgress?.segmentIndex,- navProgress?.distanceAlongRoute?.let { (it / 5.0).toInt() },- ) {- buildRouteFeatures(route, navProgress, tokens)- }- val projection = cameraState.projection ?: return- Canvas(Modifier.fillMaxSize()) {- val widthPx = with(density) { 8.dp.toPx() }- for (feature in segments) {- val line = feature.geometry as? LineString ?: continue- if (line.coordinates.size < 2) continue- val colorHex = (feature.properties?.get("route-color") as? JsonPrimitive)?.content- ?: continue- val path = Path()- line.coordinates.forEachIndexed { i, pos ->- val o = projection.screenLocationFromPosition(pos)- val px = with(density) { Offset(o.x.toPx(), o.y.toPx()) }- if (i == 0) path.moveTo(px.x, px.y) else path.lineTo(px.x, px.y)- }- drawPath(- path,- Color(runCatching { android.graphics.Color.parseColor(colorHex) }.getOrDefault(0xFF1710F1.toInt())),- style = Stroke(widthPx, cap = StrokeCap.Round, join = StrokeJoin.Round),- )- }- }-}--/**- * Compute the per-step `route-color` for the static (non-navigating) case.- * Driving uses traffic-aware red/amber/green, transit uses the line's own colour,- * walk/bike fall through to a single blue.- */-private fun staticColorFor(step: RouteService.Step, tokens: MapTokens): String {- return when (step.travelMode) {- RouteService.TravelMode.DRIVE -> when {- step.speedRatio < 0.5 -> tokens.traffic.jam.toStyleHex()- step.speedRatio < 0.9 -> tokens.traffic.slow.toStyleHex()- else -> tokens.traffic.free.toStyleHex()- }- // The colour the pack (or MOTIS) reported for this route, which is what- // the step-list badge already shows. This used to re-derive the colour- // through GTFSProvider instead, and that only knows the one feed bundled- // in the APK — so every downloaded pack fell through to the fallback and- // the whole map drew red while the badges were correct.- RouteService.TravelMode.TRANSIT ->- step.transitDetails?.transitLine?.color?.ifBlank { null }- ?: tokens.routeTransitFallback.toStyleHex()- else -> tokens.routeInert.toStyleHex()- }-}--/**- * Build the coloured segment 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,- navProgress: NavigationProgress?,- tokens: MapTokens,-): List<Feature1> {- val traveledGray = tokens.traffic.traveled.toStyleHex()- 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, tokens))))- )- }- }-- 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, tokens)-- when {- stepIdx < currentStepIdx -> {- // Entirely behind: gray.- out += Feature1(- LineString(step.polyline),- JsonObject(mapOf("route-color" to JsonPrimitive(traveledGray)))- )- }- 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(traveledGray)))- )- }- 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(traveledGray)))- )- }- // 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/map/MapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapLayers.ktindex 2fda187d9b..475663f7ff 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapLayers.kt@@ -2,78 +2,45 @@ package com.vayunmathur.maps.ui.map import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import com.vayunmathur.library.map.CameraState-import com.vayunmathur.maps.data.ParkingSpot-import com.vayunmathur.maps.data.SavedPlace-import com.vayunmathur.maps.data.SpecificFeature-import com.vayunmathur.maps.ipc.FamilyMember-import com.vayunmathur.maps.ui.FamilyLocationLayer-import com.vayunmathur.maps.ui.ParkingLayer import com.vayunmathur.maps.ui.RoadsLayer-import com.vayunmathur.maps.ui.RouteLayer import com.vayunmathur.maps.ui.SafetyLayer import com.vayunmathur.maps.ui.SatelliteLayer-import com.vayunmathur.maps.ui.SavedPlacesLayer-import com.vayunmathur.maps.ui.SearchResultLayer import com.vayunmathur.maps.ui.TransitStopsLayer-import com.vayunmathur.maps.ui.theme.mapTokens-import com.vayunmathur.maps.util.NavigationProgress import com.vayunmathur.maps.util.OfflineRouter-import com.vayunmathur.maps.util.RouteService-import com.vayunmathur.maps.util.SearchResult import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext /**- * The overlay layers over the Vulkan basemap: pins and the route polyline.+ * The overlay layers over the Vulkan basemap that are still plain Compose. *- * Everything here is plain Compose positioned through library:map's Projection — the- * renderer has no vector/raster layer API, so native map layers have nowhere to go.- * Per-pin hit-testing moved with them: MapSurface rebuilds the same features these draw- * and feeds them to [MapFeaturePicker].+ * The app's own **pins** (saved places, search results, family members, parking) are no longer+ * here: they moved into the renderer as billboarded markers ([com.vayunmathur.library.map.MapMarker],+ * pushed from [MapSurface]), which is what stopped them trailing the basemap on a pan or a tilt.+ * Their taps resolve through the renderer's id buffer+ * ([com.vayunmathur.library.map.Projection.pickMarker]), so the Compose hit-test that rebuilt them+ * is gone too — see [MapSurface]. *- * What still draws: saved places, search results, family members, the parking pin and the- * route polyline.+ * The user puck and the navigation route moved into the renderer earlier, for the same reason (see+ * [com.vayunmathur.library.map.UserPuck] and [com.vayunmathur.library.map.RouteOverlay]). *- * The user puck used to be here too and is now drawn by the renderer (see- * [com.vayunmathur.library.map.UserPuck]), which is what stopped it dragging behind a pan.- * The pins cannot follow it until their hit-testing can: they are picked against features- * [MapFeaturePicker] rebuilds in Compose, and moving the drawing without the picking would- * make them untappable. So during a pan they still lag the basemap, and so does the route.+ * What is still Compose here draws no pins, so none of it lags a pan: satellite imagery, and the+ * roads/safety/transit-stop overlays that remain **no-ops** until the renderer grows a vector+ * source-layer API (reported to lead — symbol-renderer owns that). The basemap draws its own road+ * network and ambient POIs regardless; POI taps arrive as `MapClick.poi`. *- * Deliberately NOT drawn (renderer gaps, reported to lead — symbol-renderer owns the- * renderer API): the baked `roads` overlay (casing/surface/probe), the Google traffic- * raster ([trafficEnabled] is kept so the toggle plumbing survives), the `safety` icons,- * the `transit_lines` overlay and the `transit_stops` pins. The basemap itself still draws- * its own road network; what is lost is the overlay styling plus the posted-limit probe.- *- * Ambient POIs are no longer here either, but for the opposite reason: the renderer draws- * them now, with icons, collision and per-kind zoom gating that a Compose overlay could not- * do. Their taps arrive as `MapClick.poi`, and a station still opens the departure board- * via `openNearestStop`.+ * Traffic is not here: the renderer draws the baked per-component layer, coloured from a table+ * [MapSurface] resolves from the theme and pushes in, gated by the traffic toggle. */ @Composable fun MapLayers(- selectedFeature: SpecificFeature?,- route: RouteService.RouteType?, cameraState: CameraState,- navProgress: NavigationProgress? = null,- searchResults: List<SearchResult> = emptyList(),- savedPlaces: List<SavedPlace> = emptyList(),- parkingSpot: ParkingSpot? = null,- familyMembers: List<FamilyMember> = emptyList(),- trafficEnabled: Boolean = true, satelliteEnabled: Boolean = false, safetyEnabled: Boolean = false, transitEnabled: Boolean = false,- // Which basemap palette is in play, for the route colours. Not derivable from a style- // JSON any more: there is no style JSON — the renderer takes a dark flag directly.- darkBasemap: Boolean = false, ) { val context = LocalContext.current- val tokens = remember(darkBasemap) { mapTokens(darkBasemap) } LaunchedEffect(Unit) { // OfflineRouter.initialize does asset-listing I/O — push to IO. The@@ -88,46 +55,15 @@ fun MapLayers( SatelliteLayer(satelliteEnabled) // Our own road rendering — no-op until the renderer can draw vector source-layers.- // Drawn FIRST among the vector overlays so every pin, line and highlight below sits- // on top of the roads once it lands. RoadsLayer() - // Traffic raster ([trafficEnabled]) — no-op: the keyless Google tiles have no raster- // layer to mount on. Toggle plumbing is kept so the sheet still works.- @Suppress("UNUSED_EXPRESSION")- trafficEnabled- // Safety / road-furniture layer. Gated on the toggle; no-op until the renderer can // draw vector source-layers. SafetyLayer(safetyEnabled) - // OSM transit-lines overlay — no-op until the renderer can draw vector source-layers.- // Harmless while the source-layer is absent.- @Suppress("UNUSED_EXPRESSION")- transitEnabled-- // Saved-place pins (Home / Work / starred list). Tap re-selects the- // place → PlaceSheet (Vela's SavedPin).- SavedPlacesLayer(savedPlaces, cameraState)-- // Live family-location pins, pushed by the findfamily bound- // service while the map is open. Tap → select the person → Directions.- FamilyLocationLayer(familyMembers, cameraState)-- // Parking pin. Tap → parking sheet (handled in MapSurface.onMapClick).- ParkingLayer(parkingSpot, cameraState)- if (transitEnabled) { // Baked GTFS stop pins. No-op until the renderer can draw vector source-layers; // tap a stop → live departure board (handled in MapSurface.onMapClick). TransitStopsLayer() }-- // Search-result pins — drawn above the- // ambient POI overlay so a query's hits stand out; tap re-selects.- SearchResultLayer(searchResults, cameraState)-- if (selectedFeature is SpecificFeature.Route && route is RouteService.Route) {- RouteLayer(route, navProgress, tokens, cameraState)- } }
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.ktindex efc06d9570..9de8391674 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt@@ -2,18 +2,28 @@ package com.vayunmathur.maps.ui.map import android.app.Activity import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.DpSize import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoBounds import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.library.map.LayerOptions+import com.vayunmathur.library.map.MapMarker import com.vayunmathur.library.map.MapOptions+import com.vayunmathur.library.map.MarkerIcon import com.vayunmathur.library.map.RegionLevel import com.vayunmathur.library.map.RegionMask+import com.vayunmathur.library.map.RouteOverlay+import com.vayunmathur.library.map.TrafficColorTable import com.vayunmathur.library.map.UserPuck import com.vayunmathur.library.map.VectorMap import com.vayunmathur.library.ui.FreeHeightSheetState@@ -30,13 +40,24 @@ import com.vayunmathur.maps.ui.SAVED_PLACE_LAYER_ID import com.vayunmathur.maps.ui.SEARCH_RESULT_LAYER_ID import com.vayunmathur.maps.ui.map.MapFeaturePicker.Companion.NATIVE_LABEL_LAYER_IDS import com.vayunmathur.maps.ui.map.MapFeaturePicker.Companion.toFeature1+import com.vayunmathur.maps.ui.theme.MapTokens+import com.vayunmathur.maps.ui.theme.mapTokens+import com.vayunmathur.maps.ui.toSelectedFamilyMember+import com.vayunmathur.maps.ui.toSelectedSavedPlace+import com.vayunmathur.maps.ui.toSelectedSearchResult+import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.OfflineRouter import com.vayunmathur.maps.util.PoiCategories import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SearchResult import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.TransitStopsViewModel+import com.vayunmathur.maps.util.visibleBoundsOrWorld+import kotlin.math.floor+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch /**@@ -77,27 +98,56 @@ fun MapSurface( modifier: Modifier = Modifier, ) { val coroutineScope = rememberCoroutineScope()- // DEBUG-only dev override so device-verifier can point the smoke test at a- // locally built archive (e.g. a freshly tiled california.mamaps). Release- // builds always use the prod default (null).+ // The archive the renderer opens: the copy on this device if there is one, else null,+ // which leaves the renderer streaming the published archive by range request. val context = LocalContext.current- val archivePath = remember(context) { resolveDevArchivePath(context) }+ val archivePath = remember(context) { resolveArchivePath(context) } // The renderer has carried a transit layer all along; :maps simply never asked for it, // so flipping the layers switch drew nothing but Compose stops. Remembered because // VulkanMapSurface keys a LaunchedEffect on this by equality and a fresh instance every // recomposition would churn it. val selectedCategory = chrome.selectedCategory- val mapOptions = remember(transitEnabled, selectedCategory) {+ val mapOptions = remember(transitEnabled, selectedCategory, trafficEnabled) { MapOptions( layerOptions = LayerOptions( poi = true, poiKinds = selectedCategory?.kinds.orEmpty(), transit = transitEnabled,+ // Gates the baked traffic layer's geometry (renderer layer 10). The colours+ // ride in separately via [trafficColors] below.+ traffic = trafficEnabled, ), ) } + // The live per-component colours: resolved from the current palette on the device (the+ // renderer only looks them up), pushed to the renderer as an id->ARGB table. Null when the+ // toggle is off or there is nothing to draw, which clears the overlay on the next frame —+ // the accumulated data stays cached in OfflineRouter so re-enabling is instant.+ val tokens = remember(darkBasemap) { mapTokens(darkBasemap) }+ val components by OfflineRouter.trafficComponents.collectAsState()+ val trafficColors = remember(components, tokens, trafficEnabled) {+ if (trafficEnabled) buildTrafficColorTable(components, tokens) else null+ }++ // The route, drawn inside the renderer's frame so it pans in lock-step with the basemap+ // (this is what retired the Compose `RouteLayer`). Recomputed on the same cadence that+ // layer used: on a route or palette change, and on the navigation bucket it keyed on+ // (`segmentIndex` + `distanceAlongRoute` quantised to 5 m), since the mid-step travelled+ // split moves the geometry. Only built when a route is actually selected.+ val routeOverlay = remember(+ selectedFeature, route, tokens,+ navProgress?.segmentIndex,+ navProgress?.distanceAlongRoute?.let { (it / 5.0).toInt() },+ ) {+ if (selectedFeature is SpecificFeature.Route && route is RouteService.Route) {+ buildRouteOverlay(route, navProgress, tokens)+ } else {+ null+ }+ }+ // The library takes a nullable GeoPoint, so :maps' two sentinels are converted here // and go no further: GeoPoint(0, 0) is this app's "no fix" and means null, and a null // bearing means no heading yet rather than due north.@@ -109,6 +159,40 @@ fun MapSurface( } } + // The app's pins, moved into the renderer so they pan and tilt glued to the basemap instead of+ // trailing it a frame the way the Compose pin overlays did. Each pin gets a stable id and a+ // parallel map from that id to what a tap on it means, so a tap resolves through the renderer's+ // id buffer ([Projection.pickMarker]) rather than a CPU hit-test. Rebuilt only when the pin+ // inputs change, so a pan does not churn it. See [buildMarkers].+ val (markers, markerHits) = remember(searchResults, savedPlaces, parkingSpot, familyMembers) {+ buildMarkers(searchResults, savedPlaces, parkingSpot, familyMembers)+ }++ // Simulated in-service transit vehicles for the visible bbox, recomputed at ~1 Hz and drawn by+ // the renderer as billboarded sprites on their own overlay, apart from the pins above. Gated on+ // the transit toggle and the lifecycle, and empty below its zoom gate, so it costs nothing when+ // transit is off, the map is hidden, or the viewport is too wide to enumerate cheaply.+ val vehicles = rememberTransitVehicles(camera, transitEnabled)++ // Prefetch traffic for the visible 1° squares once the camera settles, so the overlay has+ // data independent of route search (today traffic is fetched only during a route search).+ // The native side dedups squares for the session, so a re-pan over an already-fetched+ // square is a cheap no-op and the fetched data is kept. Keyed on the toggle so it stops+ // when traffic is off. `collectLatest { delay() }` is the repo's debounce idiom (see+ // GooglePoiMapViewModel): a newer camera position cancels the pending delay, so the fetch+ // only fires after the camera stops moving.+ LaunchedEffect(camera, trafficEnabled) {+ if (!trafficEnabled) return@LaunchedEffect+ snapshotFlow { camera.position }.collectLatest {+ delay(TRAFFIC_PREFETCH_DEBOUNCE_MS)+ // The component overlay is dense and zoom-gated in the archive/renderer, and a+ // world-zoom viewport would enumerate hundreds of 1° squares, so only prefetch+ // once zoomed in enough for it to be useful.+ if (camera.position.zoom < TRAFFIC_MIN_ZOOM) return@collectLatest+ prefetchTrafficSquares(camera.visibleBoundsOrWorld())+ }+ }+ VectorMap( cameraState = camera, modifier = modifier,@@ -129,35 +213,47 @@ fun MapSurface( selectedFeature.position?.let { RegionMask(it, RegionLevel.LOCALITY) } else -> null },- // GAP (deferred, renderer has no raster-layer API): the Google traffic tiles- // have nothing to mount on. [trafficEnabled] is kept so the toggle plumbing- // survives; see also the no-op branch in [MapLayers].+ // The live traffic overlay: baked geometry gated by [LayerOptions.traffic] above,+ // coloured by this id->ARGB table. Null clears it (toggle off / nothing to draw).+ trafficColors = trafficColors,+ // The route line, coloured per segment (traffic/transit/travelled) and drawn inside+ // the renderer's frame so it stays glued to the basemap on a pan. Null draws nothing.+ route = routeOverlay,+ // The app's pins, drawn by the renderer as billboarded sprites so they pan/tilt in+ // lock-step with the basemap. Their taps resolve through the id buffer below.+ markers = markers,+ // Simulated transit vehicles, on their own ~1 Hz overlay under the pins. Not tap targets.+ vehicles = vehicles, onMapClickWithScreen = { click -> coroutineScope.launch { val projection = camera.projection ?: return@launch val offset = click.screen- // Pins live in Compose, not the renderer: rebuild the same features the- // layers draw and hit-test them in screen space. Rebuilt per tap (not- // remembered) so a pin added while the map is open is tappable on the- // next tap, not the next recomposition.- val pins = pinFeatures(- searchResults = searchResults,- savedPlaces = savedPlaces,- parkingSpot = parkingSpot,- familyMembers = familyMembers,- )- val picker = MapFeaturePicker(- source = FeatureSource { box, layerIds ->- featuresInBox(- pins.filter { it.layerId in layerIds }.map { it.feature },- box,- projection,+ // Renderer-drawn pins resolve through the GPU id buffer first: correct under tilt,+ // and never a frame behind the basemap the way the old Compose hit-test was. On a+ // miss (e.g. a pin pushed this very frame, before the id buffer caught up) fall back+ // to the CPU hit-test over the same features, which is tilt-aware via Projection.+ val hit = markerHits[projection.pickMarker(offset.x.value, offset.y.value)]+ ?: run {+ val pins = pinFeatures(+ searchResults = searchResults,+ savedPlaces = savedPlaces,+ parkingSpot = parkingSpot,+ familyMembers = familyMembers, )- },- transitEnabled = transitEnabled,- )+ val picker = MapFeaturePicker(+ source = FeatureSource { box, layerIds ->+ featuresInBox(+ pins.filter { it.layerId in layerIds }.map { it.feature },+ box,+ projection,+ )+ },+ transitEnabled = transitEnabled,+ )+ picker.pickPin(offset)+ } - when (val hit = picker.pickPin(offset)) {+ when (hit) { MapHit.Parking -> { chrome.show(MapOverlay.Parking) return@launch@@ -251,19 +347,10 @@ fun MapSurface( }, ) { MapLayers(- selectedFeature = selectedFeature,- route = route, cameraState = camera,- navProgress = navProgress,- searchResults = searchResults,- savedPlaces = savedPlaces,- parkingSpot = parkingSpot,- familyMembers = familyMembers,- trafficEnabled = trafficEnabled, satelliteEnabled = satelliteEnabled, safetyEnabled = safetyEnabled, transitEnabled = transitEnabled,- darkBasemap = darkBasemap, ) } }@@ -271,22 +358,30 @@ fun MapSurface( /** * Intent extra carrying a dev-only archive URL/path for the map renderer. *- * DEBUG builds only (see [resolveDevArchivePath]): lets device-verifier point the+ * DEBUG builds only (see [resolveArchivePath]): lets device-verifier point the * smoke test at a locally served archive without touching the prod default. */ const val EXTRA_ARCHIVE_PATH = "maps.intent.extra.ARCHIVE_PATH" /**- * The renderer archive override, or null for the prod default.+ * Which archive the renderer opens, in precedence order. *- * Reads [EXTRA_ARCHIVE_PATH] off the host Activity's launch intent. DEBUG-only by- * construction: release builds return null unconditionally, so no launch flag (or- * stale intent) can ever redirect prod traffic at a dev archive.+ * 1. [EXTRA_ARCHIVE_PATH] off the host Activity's launch intent. DEBUG-only by+ * construction, so no launch flag (or stale intent) can redirect a release build.+ * 2. The device's own copy, downloaded once on first launch or `adb push`ed over it —+ * [MapTileCache.localArchive] cannot tell the two apart, which is what makes+ * sideloading a freshly tiled archive a push rather than a rebuild.+ * 3. Null, which leaves the renderer streaming the published archive by range request.+ * Only reachable if the download gate was somehow satisfied without the file, since+ * `InitialDownloadChecker` will not let the app start without it. */-private fun resolveDevArchivePath(context: android.content.Context): String? {- if (!BuildConfig.DEBUG) return null- val activity = context as? Activity ?: return null- return activity.intent?.getStringExtra(EXTRA_ARCHIVE_PATH)?.ifBlank { null }+private fun resolveArchivePath(context: android.content.Context): String? {+ val override = if (BuildConfig.DEBUG) {+ (context as? Activity)?.intent?.getStringExtra(EXTRA_ARCHIVE_PATH)?.ifBlank { null }+ } else {+ null+ }+ return override ?: MapTileCache.localArchive(context) } /**@@ -298,6 +393,84 @@ private const val STATION_POI_TYPE = PoiCategories.STATION_TYPE /** A pin feature tagged with the probe layer it belongs to. */ private data class TaggedFeature(val layerId: String, val feature: Feature1) +/**+ * How long the camera must be still before a traffic prefetch fires. Matches the browse-time+ * debounce the POI driver uses; long enough that a fling does not fetch every square it flies+ * over, short enough that the overlay fills in promptly once you stop.+ */+private const val TRAFFIC_PREFETCH_DEBOUNCE_MS = 400L++/**+ * Below this zoom the per-component traffic overlay is neither drawn (the archive zoom-gates+ * it) nor worth fetching — a zoomed-out viewport spans too many 1° squares to enumerate.+ */+private const val TRAFFIC_MIN_ZOOM = 11.0++/**+ * Safety cap on how many 1° squares a single settle may request, so an unexpectedly wide+ * viewport (near the antimeridian, or a viewport measured before the zoom gate applies) can+ * never fan out into hundreds of fetches. At [TRAFFIC_MIN_ZOOM] a settled viewport is a+ * handful of squares, well under this.+ */+private const val TRAFFIC_MAX_SQUARES = 16L++/**+ * Ask the native prefetch to load traffic for every 1° square the viewport touches.+ *+ * [ensureTrafficLoadedNative] re-derives the packed square from the point and dedups, so+ * passing each cell's centre is enough and repeats are free. A viewport that would span more+ * than [TRAFFIC_MAX_SQUARES] cells (or an inverted/antimeridian box) is skipped rather than+ * enumerated.+ */+private fun prefetchTrafficSquares(bounds: GeoBounds) {+ val lonMin = floor(bounds.west).toInt()+ val lonMax = floor(bounds.east).toInt()+ val latMin = floor(bounds.south).toInt()+ val latMax = floor(bounds.north).toInt()+ val cells = (lonMax - lonMin + 1).toLong() * (latMax - latMin + 1).toLong()+ if (cells < 1L || cells > TRAFFIC_MAX_SQUARES) return+ for (lat in latMin..latMax) {+ for (lon in lonMin..lonMax) {+ OfflineRouter.ensureTrafficLoadedNative(lat + 0.5, lon + 0.5, true)+ }+ }+}++/**+ * Resolve the component-level traffic readings into an id→ARGB table for the renderer.+ *+ * Buckets mirror `staticColorFor` in `RouteOverlayBuilder`: `ratio < 0.5` jam, `< 0.9` slow,+ * else free, where `ratio = ratio_pct / 100`. `ratio_pct == 0` is "no data" and is dropped — an id+ * absent from the table draws nothing, so those segments fall back to the plain basemap road.+ * Colours come from [tokens], which already encodes the light/dark palette, so the renderer+ * only looks them up. Returns null when nothing is left to draw.+ */+private fun buildTrafficColorTable(+ components: OfflineRouter.TrafficComponents,+ tokens: MapTokens,+): TrafficColorTable? {+ val n = components.ids.size+ if (n == 0) return null+ val outIds = LongArray(n)+ val outArgb = IntArray(n)+ var k = 0+ for (i in 0 until n) {+ val pct = components.ratioPct[i].toInt() and 0xFF+ if (pct == 0) continue+ val ratio = pct / 100.0+ val color = when {+ ratio < 0.5 -> tokens.traffic.jam+ ratio < 0.9 -> tokens.traffic.slow+ else -> tokens.traffic.free+ }+ outIds[k] = components.ids[i]+ outArgb[k] = color.toArgb()+ k+++ }+ if (k == 0) return null+ return TrafficColorTable(outIds.copyOf(k), outArgb.copyOf(k))+}+ /** * The tappable pin set: every Compose-drawn pin as the [Feature1] its resolver * (`toSelected*`) already understands, tagged for [MapFeaturePicker]'s per-layer@@ -333,3 +506,53 @@ private fun pinFeatures( add(TaggedFeature(FAMILY_LOCATION_LAYER_ID, familyPinFeature(member))) } }++/**+ * The renderer marker set for the app's pins, plus a map from each marker's id to the [MapHit] a+ * tap on it means, resolved once here so the tap path is a lookup.+ *+ * The renderer draws these (billboarded, glued to the basemap); a tap reads back the marker's id+ * from the id buffer and this map turns it into the same [MapHit] the old CPU picker produced. Ids+ * are assigned per pin kind in disjoint ranges so they stay unique and never collide with the+ * pick-buffer's `0` = "nothing". A pin whose feature does not resolve (a malformed saved place, say)+ * is dropped rather than drawn as an untappable dot — the same outcome the CPU picker's+ * `firstNotNullOfOrNull` gave.+ */+private fun buildMarkers(+ searchResults: List<SearchResult>,+ savedPlaces: List<SavedPlace>,+ parkingSpot: ParkingSpot?,+ familyMembers: List<FamilyMember>,+): Pair<List<MapMarker>, Map<Long, MapHit>> {+ val markers = ArrayList<MapMarker>()+ val hits = HashMap<Long, MapHit>()+ // Disjoint id ranges per kind: 1 for the single parking pin, then a decade each for the lists.+ var id = 1L+ if (parkingSpot != null) {+ markers.add(MapMarker(id, GeoPoint(parkingSpot.lon, parkingSpot.lat), MarkerIcon.PARKING))+ hits[id] = MapHit.Parking+ id+++ }+ id = 100_000L+ for (result in searchResults) {+ val place = searchPinFeature(result).toSelectedSearchResult() ?: continue+ markers.add(MapMarker(id, GeoPoint(result.lon, result.lat), MarkerIcon.SEARCH))+ hits[id] = MapHit.Place(place)+ id+++ }+ id = 200_000L+ for (saved in savedPlaces) {+ val place = savedPinFeature(saved).toSelectedSavedPlace() ?: continue+ markers.add(MapMarker(id, GeoPoint(saved.lon, saved.lat), MarkerIcon.SAVED))+ hits[id] = MapHit.Place(place)+ id+++ }+ id = 300_000L+ for (member in familyMembers) {+ val place = familyPinFeature(member).toSelectedFamilyMember() ?: continue+ markers.add(MapMarker(id, GeoPoint(member.lng, member.lat), MarkerIcon.FAMILY))+ hits[id] = MapHit.Place(place)+ id+++ }+ return markers to hits+}
maps/src/main/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilder.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilder.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilder.ktnew file mode 100644index 0000000000..bac9e2e269--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/RouteOverlayBuilder.kt@@ -0,0 +1,151 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.map.RouteOverlay+import com.vayunmathur.library.map.RouteSegment+import com.vayunmathur.library.map.RouteStyle+import com.vayunmathur.maps.ui.theme.MapTokens+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.RouteService++/**+ * Turns a [RouteService.Route] into the coloured-segment [RouteOverlay] the Vulkan renderer+ * draws, replacing the Compose `RouteLayer` that used to stroke the same segments on a Canvas+ * over `VectorMap`. Drawing in the renderer is what stops the route lagging the basemap by a+ * frame on a pan — the puck, region mask and traffic already moved in for the same reason.+ *+ * The colouring is unchanged from `RouteLayer`: driving uses traffic-aware red/amber/green,+ * transit uses the line's own brand colour, walk/bike a single inert blue, and during+ * navigation the route is split at the snapped point so the travelled part greys out. Only+ * the output type changed — coloured [RouteSegment]s instead of GeoJSON `route-color`+ * features.+ *+ * No casing, matching `RouteLayer`'s plain 8 dp stroke: the phone route sat directly on the+ * basemap with no outline. (The car uses [RouteStyle]'s default casing; this deliberately+ * turns it off.)+ */+fun buildRouteOverlay(+ route: RouteService.Route,+ navProgress: NavigationProgress?,+ tokens: MapTokens,+): RouteOverlay? {+ val segments = buildRouteSegments(route, navProgress, tokens)+ if (segments.isEmpty()) return null+ return RouteOverlay(segments, RouteStyle(width = 8.dp, casingWidth = 0.dp))+}++/**+ * The per-step colour for the static (non-navigating) case. Driving is traffic-aware,+ * transit uses the line's own colour (falling back when the feed gives none or an+ * unparseable one), walk/bike fall through to a single inert colour.+ */+private fun staticColorFor(step: RouteService.Step, tokens: MapTokens): Color =+ when (step.travelMode) {+ RouteService.TravelMode.DRIVE -> when {+ step.speedRatio < 0.5 -> tokens.traffic.jam+ step.speedRatio < 0.9 -> tokens.traffic.slow+ else -> tokens.traffic.free+ }+ // The colour the pack (or MOTIS) reported for this route, which is what the+ // step-list badge already shows. A blank or malformed feed colour falls back+ // rather than drawing a garbage colour.+ RouteService.TravelMode.TRANSIT ->+ step.transitDetails?.transitLine?.color?.ifBlank { null }?.let(::parseHexColor)+ ?: tokens.routeTransitFallback+ else -> tokens.routeInert+ }++/** Parse a `#rrggbb`/`#aarrggbb` feed colour, or `null` when it is not valid. */+private fun parseHexColor(hex: String): Color? =+ runCatching { Color(android.graphics.Color.parseColor(hex)) }.getOrNull()++/**+ * Build the coloured segment list for the route.+ *+ * When [navProgress] is null this returns one segment per [RouteService.Step] with the+ * mode-aware static colour.+ *+ * 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 colour,+ * - the current step is split: portion behind the snap → gray; portion ahead → mode colour,+ * - steps strictly after keep their mode colour.+ *+ * 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 mirrors [com.vayunmathur.maps.util.PolylineIndex]'s `stepRanges`+ * construction (cursor walk; steps share endpoints).+ */+private fun buildRouteSegments(+ route: RouteService.Route,+ navProgress: NavigationProgress?,+ tokens: MapTokens,+): List<RouteSegment> {+ val traveledGray = tokens.traffic.traveled+ if (navProgress == null) {+ return route.step.filter { it.polyline.size >= 2 }.map { step ->+ RouteSegment(step.polyline, staticColorFor(step, tokens))+ }+ }++ val currentStepIdx = navProgress.currentStepIndex+ val snappedSegIdx = navProgress.segmentIndex // index into route.polyline+ val snappedPos = navProgress.snappedPosition++ val out = mutableListOf<RouteSegment>()+ // 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 skipping the cursor advance).+ continue+ }+ val first = cursor+ val last = (first + stepLen - 1).coerceAtMost(route.polyline.size - 1)+ val color = staticColorFor(step, tokens)++ when {+ stepIdx < currentStepIdx -> {+ // Entirely behind: gray.+ out += RouteSegment(step.polyline, traveledGray)+ }+ stepIdx > currentStepIdx -> {+ // Entirely ahead: mode colour.+ out += RouteSegment(step.polyline, color)+ }+ snappedSegIdx < first -> {+ // Snap fell on an earlier step than our step-index math attributed to this+ // step (brief off-by-one near a boundary, or a glitchy GPS fix). Treat the+ // whole step as ahead rather than fabricating a gray spur.+ out += RouteSegment(step.polyline, color)+ }+ snappedSegIdx > last -> {+ // Snap fell on a later step. Treat the whole step as behind.+ out += RouteSegment(step.polyline, traveledGray)+ }+ 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 += RouteSegment(behindVertices, traveledGray)+ }+ // Ahead portion: snapped position, then remaining vertices.+ val aheadVertices = mutableListOf(snappedPos)+ aheadVertices.addAll(step.polyline.subList(localSnapVertex + 1, stepLen))+ if (aheadVertices.size >= 2) {+ out += RouteSegment(aheadVertices, color)+ }+ }+ }+ cursor = last+ }+ return out+}
maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.ktnew file mode 100644index 0000000000..1e0b08c765--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/TransitVehicles.kt@@ -0,0 +1,119 @@+package com.vayunmathur.maps.ui.map++import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner+import com.vayunmathur.library.map.CameraState+import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.MapMarker+import com.vayunmathur.library.map.MarkerIcon+import com.vayunmathur.maps.util.OfflineRouter+import com.vayunmathur.maps.util.visibleBoundsOrWorld+import kotlinx.coroutines.delay++/**+ * How often the in-service vehicle set is recomputed, mirroring the ~1 Hz cadence the departures+ * board countdown uses ([com.vayunmathur.maps.ui.DeparturesSheet]). The native+ * `activeVehicles` folds schedule + realtime delay into each recompute; between recomputes the+ * renderer holds each sprite's last pushed position. One second of drift is a few metres at transit+ * speeds — small at the zooms this draws at — so a plain re-push each tick is the whole animation,+ * with no per-frame predictor. The native `Vehicle` carries a bearing but no speed, so there is no+ * cheap on-device dead-reckoning to do, and the shared sprite path is geography-agnostic; if smooth+ * 60 fps tweening is wanted later it belongs in the renderer's overlay draw, keyed on the stable+ * per-trip [OfflineRouter.Vehicle.id].+ */+private const val VEHICLE_TICK_MS = 1_000L++/**+ * Below this zoom the visible bbox spans too many in-service trips for a 1 Hz recompute to stay+ * cheap (the plan's own note on bounding the enumeration to the viewport), and the sprites would be+ * an unreadable swarm anyway. Matches the spirit of the traffic prefetch's own zoom gate.+ */+private const val VEHICLE_MIN_ZOOM = 11.0++/**+ * The simulated in-service transit vehicles for the visible bbox, recomputed at ~1 Hz and mapped to+ * renderer markers, or an empty list when the transit layer is off, the surface is hidden, or the+ * camera is zoomed too far out (see [VEHICLE_MIN_ZOOM]).+ *+ * Drive [com.vayunmathur.library.map.VectorMap]'s `vehicles` with the return value: it is pushed on+ * its own cadence, apart from the app pins, so a vehicle recompute never churns the pins and the+ * moving sprites stay out of the pin tap-pick. The loop samples the camera's live bounds each tick,+ * so a pan or zoom re-targets the enumeration without restarting the effect. Gated on the lifecycle+ * with the same ON_START/ON_STOP observer the renderer uses, so a backgrounded or hidden map stops+ * recomputing and clears its vehicles rather than leaving a stale swarm behind.+ */+@Composable+fun rememberTransitVehicles(+ camera: CameraState,+ transitEnabled: Boolean,+): List<MapMarker> {+ val context = LocalContext.current+ val lifecycleOwner = LocalLifecycleOwner.current+ var started by remember { mutableStateOf(false) }+ var vehicles by remember { mutableStateOf(emptyList<MapMarker>()) }++ // The same ON_START/ON_STOP gate VulkanMapSurface stops the renderer on: a STARTED-but-not-+ // RESUMED surface (split-screen, PiP) is on screen and must keep its vehicles moving.+ DisposableEffect(lifecycleOwner) {+ val observer = LifecycleEventObserver { _, event ->+ when (event) {+ Lifecycle.Event.ON_START -> started = true+ Lifecycle.Event.ON_STOP -> started = false+ else -> Unit+ }+ }+ lifecycleOwner.lifecycle.addObserver(observer)+ onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+ }++ LaunchedEffect(transitEnabled, started) {+ if (!transitEnabled || !started) {+ vehicles = emptyList()+ return@LaunchedEffect+ }+ while (true) {+ val bounds = camera.visibleBoundsOrWorld()+ vehicles = if (camera.position.zoom < VEHICLE_MIN_ZOOM) {+ emptyList()+ } else {+ OfflineRouter.activeVehicles(+ context,+ minLat = bounds.south,+ minLon = bounds.west,+ maxLat = bounds.north,+ maxLon = bounds.east,+ ).map { v ->+ MapMarker(+ id = v.id,+ position = GeoPoint(longitude = v.lon, latitude = v.lat),+ icon = gtfsModeToMarkerIcon(v.mode),+ )+ }+ }+ delay(VEHICLE_TICK_MS)+ }+ }+ return vehicles+}++/**+ * The renderer marker icon for a coarse GTFS mode label (see+ * [OfflineRouter.Vehicle.mode]). Trams/monorails, the rail family (subway/rail/funicular/aerial),+ * ferries and everything else (bus/trolleybus and any unknown) each fold onto one of the four+ * reserved `VEHICLE_*` sprites, which is as fine as the shared atlas draws.+ */+internal fun gtfsModeToMarkerIcon(mode: String): Int = when (mode) {+ "TRAM", "MONORAIL" -> MarkerIcon.VEHICLE_TRAM+ "SUBWAY", "RAIL", "FUNICULAR", "AERIAL" -> MarkerIcon.VEHICLE_TRAIN+ "FERRY" -> MarkerIcon.VEHICLE_FERRY+ else -> MarkerIcon.VEHICLE_BUS+}
maps/src/main/java/com/vayunmathur/maps/ui/nav/ElevationChart.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/ElevationChart.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/ElevationChart.ktnew file mode 100644index 0000000000..4087e1c168--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/ElevationChart.kt@@ -0,0 +1,93 @@+package com.vayunmathur.maps.ui.nav++import androidx.compose.foundation.Canvas+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.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.maps.R+import com.vayunmathur.maps.util.RouteService+import kotlin.math.roundToInt++/**+ * Route elevation profile chart (WS-G): plots ground elevation against cumulative distance and+ * summarises total ascent/descent. Fed by [RouteService.Route.elevationProfile], which the offline+ * router bakes from the graph's per-node DEM elevation. Renders nothing when there is no usable+ * profile (fewer than two samples, or a dead-flat route), so callers can invoke it unconditionally.+ */+@Composable+fun ElevationChart(+ profile: List<RouteService.ElevationPoint>,+ ascentMeters: Double,+ descentMeters: Double,+ modifier: Modifier = Modifier,+) {+ if (profile.size < 2) return+ val minElev = profile.minOf { it.elevationMeters }+ val maxElev = profile.maxOf { it.elevationMeters }+ val totalDist = profile.last().distanceMeters+ // A flat or zero-length route has no shape worth drawing.+ if (totalDist <= 0.0 || maxElev - minElev < 1.0) return++ val lineColor = MaterialTheme.colorScheme.primary+ val fillColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.18f)+ val axisColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f)++ Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {+ Text(+ stringResource(R.string.nav_elevation_title),+ fontSize = 14.sp,+ fontWeight = FontWeight.Bold,+ )+ Spacer(Modifier.size(4.dp))+ Text(+ stringResource(+ R.string.nav_elevation_gain_loss,+ ascentMeters.roundToInt(),+ descentMeters.roundToInt(),+ ),+ fontSize = 13.sp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ Spacer(Modifier.size(6.dp))+ Canvas(Modifier.fillMaxWidth().height(72.dp)) {+ val w = size.width+ val h = size.height+ val elevRange = (maxElev - minElev).coerceAtLeast(1.0)+ // Map a profile sample to a canvas point, y inverted so higher ground is higher up.+ fun px(p: RouteService.ElevationPoint): Offset {+ val x = (p.distanceMeters / totalDist * w).toFloat()+ val y = (h - (p.elevationMeters - minElev) / elevRange * h).toFloat()+ return Offset(x, y)+ }++ val first = px(profile.first())+ val line = Path().apply { moveTo(first.x, first.y) }+ val area = Path().apply { moveTo(first.x, h); lineTo(first.x, first.y) }+ for (i in 1 until profile.size) {+ val o = px(profile[i])+ line.lineTo(o.x, o.y)+ area.lineTo(o.x, o.y)+ }+ area.lineTo(w, h)+ area.close()++ drawLine(axisColor, Offset(0f, h), Offset(w, h), strokeWidth = 1.dp.toPx())+ drawPath(area, fillColor)+ drawPath(line, lineColor, style = Stroke(width = 2.dp.toPx()))+ }+ }+}
maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.ktindex 01c574e0c8..7f222961d3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt@@ -40,6 +40,7 @@ fun StepsSheet( currentStepIndex: Int, onClose: () -> Unit, modifier: Modifier = Modifier,+ route: RouteService.Route? = null, ) { Card( modifier = modifier.fillMaxWidth(),@@ -59,6 +60,16 @@ fun StepsSheet( IconButton(onClose) { IconClose() } } HorizontalDivider()+ // Route elevation profile (WS-G), when the graph carried DEM data. Renders nothing for a+ // flat/transit route, so it is safe to place unconditionally above the step list.+ if (route != null && route.elevationProfile.size >= 2) {+ ElevationChart(+ profile = route.elevationProfile,+ ascentMeters = route.ascentMeters,+ descentMeters = route.descentMeters,+ )+ HorizontalDivider()+ } LazyColumn(Modifier.fillMaxWidth()) { itemsIndexed(steps) { index, step -> val dim = index < currentStepIndex
maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.ktindex aab9bc53cf..8e2cc79318 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt@@ -1,12 +1,43 @@ package com.vayunmathur.maps.util +import android.content.Context+import java.io.File+ /**- * Where the streamed protomaps archives live.+ * Where the map archives live: the streamed protomaps ones, and the `.mamaps` basemap+ * that is now fetched once onto the device instead. *- * Only the URLs: the byte-range fetching and disk cache for them are inside- * `:library:map`'s renderer, which owns its own cache directory.+ * Only the URLs and the on-disk location: the byte-range fetching and disk cache for the+ * streamed archives are inside `:library:map`'s renderer, which owns its own cache directory. */ object MapTileCache {+ /**+ * The `.mamaps` basemap, fetched once into external files alongside the graph and POI+ * packs rather than range-requested for the life of the install.+ *+ * Named for its role rather than its extent, so the same install can be handed a+ * state-sized archive today and a planet one later without the filename becoming a lie.+ */+ const val BASEMAP_ARCHIVE_FILE = "basemap.mamaps"++ /** Where [BASEMAP_ARCHIVE_FILE] is fetched from on a first launch that has no copy yet. */+ const val BASEMAP_ARCHIVE_URL =+ "https://data.vayunmathur.com/planet.mamaps"++ /**+ * The on-device archive, or null when there is no copy yet.+ *+ * A sideloaded archive is indistinguishable from a downloaded one, and that is the point:+ * `adb push`ing a locally built `.mamaps` here both satisfies the first-launch download+ * gate and becomes what the renderer opens, so iterating on the tiler does not mean+ * waiting on a multi-gigabyte transfer. Null sends the renderer back to streaming+ * [BASEMAP_ARCHIVE_URL] by range request.+ */+ fun localArchive(context: Context): String? =+ File(context.getExternalFilesDir(null), BASEMAP_ARCHIVE_FILE)+ .takeIf { it.isFile }+ ?.absolutePath+ /** * The single source of truth for the streamed basemap PMTiles URL. *
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 26ccae241a..21dd99b55c 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -194,6 +194,34 @@ object OfflineRouter { lat: Double, lon: Double ): String?+ /**+ * Simulated in-service transit vehicles for the visible bbox (WS-F): every+ * trip in `<basePath>/<feed>.transit` running at `nowSecs` (seconds since+ * feed-local midnight), interpolated to a live `lon,lat,bearing` along its+ * shape. Positions are computed on-device from the pack schedule + shape ++ * the realtime overlay; there is no live GPS feed.+ *+ * Time and `overlay*` arguments are as in [findTransitRouteNative], so a+ * `>24:00:00` overnight trip is placed and a delayed/cancelled trip is drawn+ * live/suppressed. Returns [RawVehicle]s (possibly empty), or null when the+ * feed is missing/malformed.+ */+ private external fun activeVehiclesNative(+ basePath: String,+ feed: String,+ nowSecs: Int,+ weekday: Int,+ date: Int,+ prevWeekday: Int,+ prevDate: Int,+ overlayCoords: DoubleArray,+ overlayRoutes: Array<String>,+ overlayTimes: IntArray,+ minLat: Double,+ minLon: Double,+ maxLat: Double,+ maxLon: Double+ ): Array<RawVehicle>? private external fun updateTrafficNative( edgeIds: LongArray, speeds: ByteArray,@@ -206,6 +234,58 @@ object OfflineRouter { private val _trafficVersion = kotlinx.coroutines.flow.MutableStateFlow(0) val trafficVersion = _trafficVersion.asStateFlow() + /**+ * Live per-component traffic for **display**, as a flat id→ratio table.+ *+ * Separate from the big-edge speeds that feed [updateTrafficNative] (routing/ETA, which+ * stay entirely native): these component-level values are pushed to the renderer as an+ * id→colour table by the map layer, which resolves the colour from the theme. [ids] and+ * [ratioPct] are parallel; [ratioPct] is the wire's `u8 = round(speedRatio*100)`, where+ * `0` means "no data" (the consumer skips those). The renderer draws a colour only for+ * ids present here and present in a resident tile, so ids for squares that scrolled off+ * are harmless — which is why this is an accumulating session cache rather than something+ * pruned on every pan (see [trafficComponents]).+ */+ class TrafficComponents(val ids: LongArray, val ratioPct: ByteArray) {+ companion object {+ val EMPTY = TrafficComponents(LongArray(0), ByteArray(0))+ }+ }++ /**+ * Component traffic keyed by the packed 1° square it was fetched for (the same+ * `packedSquare` [fetchTrafficData] receives). The native prefetch dedups squares for the+ * whole session ([ensureTrafficLoadedNative] never re-asks for a square it already+ * requested), so a square is fetched once and kept: dropping it here would leave a+ * re-panned area permanently uncoloured with no way to refetch. Cleared only on [reload]+ * (a graph swap can renumber ids).+ */+ private val componentBySquare = java.util.concurrent.ConcurrentHashMap<Int, TrafficComponents>()+ private val _trafficComponents =+ kotlinx.coroutines.flow.MutableStateFlow(TrafficComponents.EMPTY)++ /**+ * The merged component table across every fetched square, republished whenever a fetch+ * lands. The map layer collects this, converts each ratio to an ARGB colour against the+ * current palette, and pushes `id→colour` to the renderer.+ */+ val trafficComponents = _trafficComponents.asStateFlow()++ /** Concatenate the per-square tables into one flat id/ratio snapshot and publish it. */+ private fun republishComponents() {+ val squares = componentBySquare.values.toList()+ val total = squares.sumOf { it.ids.size }+ val ids = LongArray(total)+ val ratios = ByteArray(total)+ var off = 0+ for (s in squares) {+ System.arraycopy(s.ids, 0, ids, off, s.ids.size)+ System.arraycopy(s.ratioPct, 0, ratios, off, s.ratioPct.size)+ off += s.ids.size+ }+ _trafficComponents.value = TrafficComponents(ids, ratios)+ }+ private var cacheDirPath: String? = null private var trafficUpdateJob: kotlinx.coroutines.Job? = null @@ -234,7 +314,7 @@ object OfflineRouter { "fetchTrafficData START: bbox ($minLat,$minLon)-($maxLat,$maxLon) packed=$packedSquare forceAsync=$forceAsync" ) - val block: suspend () -> Unit = {+ val block: suspend () -> Unit = block@{ try { val (status, bytes) = NetworkClient.performRequestBytes(@@ -245,16 +325,54 @@ object OfflineRouter { "TRAFFIC_DATA", "fetchTrafficData NETWORK DONE: status=$status, size=${bytes.size}" )- // Response layout: n * 8-byte LE u64 edge IDs, then n * 1-byte speeds.- if (status == 200 && bytes.size >= 9) {- val n = bytes.size / 9- val edgeIds = LongArray(n)+ // Two-level response (little-endian):+ // u32 n_big, u32 n_component+ // n_big x (u64 big_edge_id, u8 kph) -- routing, unchanged+ // n_component x (u64 component_id, u8 ratio_pct) -- display+ // ratio_pct = round(speedRatio*100); 0 = no data. Records are interleaved+ // (id then speed), not struct-of-arrays. The big level still feeds+ // updateTrafficNative exactly as before; the component level is kept in+ // Kotlin and pushed to the renderer as an id->colour table.+ if (status == 200 && bytes.size >= 8) { val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)- for (i in 0 until n) edgeIds[i] = buffer.long- val speeds = ByteArray(n)- buffer.get(speeds)- Log.d("TRAFFIC_DATA", "fetchTrafficData PROCESSING: $n edges")+ val nBig = buffer.int.toLong() and 0xFFFF_FFFFL+ val nComponent = buffer.int.toLong() and 0xFFFF_FFFFL+ val expected = 8L + 9L * (nBig + nComponent)+ if (bytes.size.toLong() != expected) {+ Log.w(+ "TRAFFIC_DATA",+ "fetchTrafficData SIZE MISMATCH: got ${bytes.size}, expected $expected (n_big=$nBig n_component=$nComponent)"+ )+ notifyTrafficFetchFinishedNative(packedSquare)+ return@block+ }+ val nBigI = nBig.toInt()+ val nComponentI = nComponent.toInt()++ // Big level: split the interleaved (id, kph) records into the parallel+ // arrays updateTrafficNative expects.+ val edgeIds = LongArray(nBigI)+ val speeds = ByteArray(nBigI)+ for (i in 0 until nBigI) {+ edgeIds[i] = buffer.long+ speeds[i] = buffer.get()+ }++ // Component level: kept for display.+ val compIds = LongArray(nComponentI)+ val compRatios = ByteArray(nComponentI)+ for (i in 0 until nComponentI) {+ compIds[i] = buffer.long+ compRatios[i] = buffer.get()+ }++ Log.d(+ "TRAFFIC_DATA",+ "fetchTrafficData PROCESSING: $nBigI big edges, $nComponentI components"+ ) updateTrafficNative(edgeIds, speeds, packedSquare)+ componentBySquare[packedSquare] = TrafficComponents(compIds, compRatios)+ republishComponents() notifyTrafficUpdated() } else { Log.w("TRAFFIC_DATA", "fetchTrafficData NO DATA: status=$status")@@ -317,6 +435,17 @@ object OfflineRouter { val boardStopId: String?, /** MOTIS/Transitous id of the ride's alight stop. See [boardStopId]. */ val alightStopId: String?,+ /**+ * Per-coordinate ground elevation in metres, parallel to [geometry]+ * (so `elevations.size == geometry.size / 2`). Baked from the DEM at+ * graph-build time (WS-G) and interpolated along each edge. Empty on a+ * transit leg or when the graph carries no elevation data.+ */+ val elevations: DoubleArray,+ /** Whole-route cumulative ascent in metres (repeated on every step). */+ val ascentM: Double,+ /** Whole-route cumulative descent in metres (repeated on every step). */+ val descentM: Double, ) /** One offline scheduled departure from the baked `.transit` index. */@@ -340,6 +469,40 @@ object OfflineRouter { val realTime: Boolean ) + /**+ * One simulated in-service vehicle as it crosses the JNI boundary. Flat like+ * [RawStep]/[RawDeparture]; [Vehicle] is the typed form callers consume.+ */+ class RawVehicle+ @Keep+ constructor(+ val lon: Double,+ val lat: Double,+ /** Heading in degrees, 0 = north, clockwise, along the direction of travel. */+ val bearing: Double,+ /** GTFS `route_color` packed as 0xRRGGBB, or 0 when absent. */+ val colour: Int,+ /** GTFS `route_type`. */+ val mode: Int,+ /** Stable per-trip id, so a sprite animates between recomputes. */+ val id: Long,+ )++ /**+ * A simulated moving transit vehicle for the map overlay (WS-F). [bearing] is+ * degrees (0 = north, clockwise); [colour] is 0xRRGGBB (0 when absent);+ * [mode] is a coarse label (BUS/TRAM/RAIL/…) for icon selection; [id] is+ * stable across the ~1 Hz recomputes for the same trip.+ */+ data class Vehicle(+ val lon: Double,+ val lat: Double,+ val bearing: Float,+ val colour: Int,+ val mode: String,+ val id: Long,+ )+ /** * MOTIS realtime, flattened for the JNI overlay arguments. [coords] is * interleaved `[lat, lon, ...]`, [times] is interleaved@@ -384,6 +547,10 @@ object OfflineRouter { fun reload(context: Context) { isInitialized = false cachedTransitFeeds = null+ // A new graph vintage can renumber edge/component ids, so the display cache from the+ // old graph must not survive the swap.+ componentBySquare.clear()+ _trafficComponents.value = TrafficCompon
Diff truncated.