Modern Apps git

← Modern-Apps.git

maps P10: transit departure boards (Transitous)

Commit
dffe39e91bdd4f94fcb2c45e22eb77a729ce1fda
Author
vayun-mathur <[email protected]>
When
2026-08-17 00:33 UTC (3 months ago)
Parents
c47dc66

Diff

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 0632bbadc5..408eb67d98 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -123,11 +123,12 @@ fun Navigation(     poiViewModel: GooglePoiMapViewModel = viewModel(),     settingsViewModel: MapSettingsViewModel = viewModel(),     parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel = viewModel(),+    transitViewModel: com.vayunmathur.maps.util.TransitStopsViewModel = viewModel(), ) {     val backStack = rememberNavBackStack<Route>(Route.MapPage)     MainNavigation(backStack) {         entry<Route.MapPage> {-            MapPage(backStack, viewModel, zonesViewModel, savedPlacesViewModel, poiViewModel, searchViewModel, settingsViewModel, parkingViewModel)+            MapPage(backStack, viewModel, zonesViewModel, savedPlacesViewModel, poiViewModel, searchViewModel, settingsViewModel, parkingViewModel, transitViewModel)         }         entry<Route.DownloadedMapsPage> {             DownloadedMapsPage(backStack, zonesViewModel)
maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.ktindex 6a4211c5a0..6c2b1386f8 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt@@ -15,11 +15,13 @@ object MapPreferences {     const val KEY_LAYER_TRAFFIC = "layer_traffic"     const val KEY_LAYER_SATELLITE = "layer_satellite"     const val KEY_LAYER_SAFETY = "layer_safety"+    const val KEY_LAYER_TRANSIT = "layer_transit"      const val DEFAULT_VOICE_GUIDANCE = true     const val DEFAULT_LAYER_TRAFFIC = true     const val DEFAULT_LAYER_SATELLITE = false     const val DEFAULT_LAYER_SAFETY = false+    const val DEFAULT_LAYER_TRANSIT = false }  /** App theme selection persisted under [MapPreferences.KEY_THEME_MODE]. */
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.ktnew file mode 100644index 0000000000..bfe19fad7c--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousDataSource.kt@@ -0,0 +1,157 @@+package com.vayunmathur.maps.data.transit++import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.net.URLEncoder+import java.time.Instant+import java.time.OffsetDateTime++/**+ * Online public-transit data source (P10) backed by **Transitous** — a free,+ * community-hosted aggregation of open GTFS / GTFS-RT feeds — via its **MOTIS**+ * REST API. Two calls are exposed:+ *+ *  - [stopsInBbox] — nearby stops for the current viewport (`/api/v1/map/stops`,+ *    the same endpoint the MOTIS web map uses to draw stop dots), for the+ *    overlay layer.+ *  - [departures] — the live board for one stop (`/api/v1/stoptimes`): route+ *    short name, headsign, scheduled + realtime time, delay, platform.+ *+ * Design mirrors [com.vayunmathur.maps.data.google.GooglePoiDiscovery]:+ *  - an `object` singleton, all network on [Dispatchers.IO];+ *  - **never throws** — every public call returns empty on any failure so a+ *    flaky feed or a MOTIS schema drift degrades gracefully;+ *  - **brief caching**: stops are cached per rounded viewport (they rarely+ *    change); departures are cached per stop for only [DEPARTURES_TTL_MS] since+ *    they are live.+ *+ * ONLINE-ONLY (P11 adds offline transit from bundled GTFS). Routing is+ * untouched — this is a read-only board.+ *+ * NOTE (on-device): the live MOTIS fetch needs a device/emulator with network+ * and cannot be exercised at compile time; the endpoints/parse below are+ * verified by shape only.+ */+object TransitousDataSource {++    private const val BASE_URL = "https://api.transitous.org"++    /** Cap departures requested per board so a busy hub stays scrollable. */+    private const val DEPARTURE_COUNT = 30++    /** Cap stops per viewport so a dense metro area doesn't flood the overlay. */+    private const val MAX_STOPS = 200++    /** Departures are live — cache only very briefly to smooth refresh taps. */+    private const val DEPARTURES_TTL_MS = 20_000L++    private val REQUEST_HEADERS = mapOf(+        "Accept" to "application/json",+        "User-Agent" to "Modern-Apps-Maps/1.0",+    )++    // Stops LRU keyed on the rounded viewport box (stops are static-ish).+    private data class BboxKey(val minLat: Double, val minLon: Double, val maxLat: Double, val maxLon: Double)+    private val stopsCache = object : LinkedHashMap<BboxKey, List<TransitStop>>(16, 0.75f, true) {+        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<BboxKey, List<TransitStop>>) = size > 32+    }++    // Departures cache keyed on stop id, with a short TTL (live data).+    private class Timed(val at: Long, val value: List<Departure>)+    private val departuresCache = object : LinkedHashMap<String, Timed>(16, 0.75f, true) {+        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Timed>) = size > 32+    }++    /**+     * Stops within the viewport box. Never throws — returns an empty list on any+     * failure. LRU-cached on the box rounded to ~100 m so small pans reuse the+     * previous fetch.+     */+    suspend fun stopsInBbox(+        minLat: Double,+        minLon: Double,+        maxLat: Double,+        maxLon: Double,+    ): List<TransitStop> {+        val key = BboxKey(round3(minLat), round3(minLon), round3(maxLat), round3(maxLon))+        synchronized(stopsCache) { stopsCache[key]?.let { return it } }+        val stops = runCatching { fetchStops(minLat, minLon, maxLat, maxLon) }.getOrDefault(emptyList())+        synchronized(stopsCache) { stopsCache[key] = stops }+        return stops+    }++    /**+     * Live departures for [stopId]. Never throws — empty on failure. Cached for+     * [DEPARTURES_TTL_MS]; pass [force] (a manual refresh) to bypass the cache.+     */+    suspend fun departures(stopId: String, force: Boolean = false): List<Departure> {+        if (!force) {+            synchronized(departuresCache) {+                departuresCache[stopId]?.let {+                    if (System.currentTimeMillis() - it.at < DEPARTURES_TTL_MS) return it.value+                }+            }+        }+        val deps = runCatching { fetchDepartures(stopId) }.getOrDefault(emptyList())+        synchronized(departuresCache) { departuresCache[stopId] = Timed(System.currentTimeMillis(), deps) }+        return deps+    }++    private suspend fun fetchStops(+        minLat: Double,+        minLon: Double,+        maxLat: Double,+        maxLon: Double,+    ): List<TransitStop> = withContext(Dispatchers.IO) {+        // MOTIS map/stops takes the box corners as "lat,lon" min/max pairs.+        val url = "$BASE_URL/api/v1/map/stops" ++            "?min=${enc("$minLat,$minLon")}&max=${enc("$maxLat,$maxLon")}"+        val stops: List<MotisMapStop> = NetworkClient.getJson(url, REQUEST_HEADERS, useSystemTrust = true)+        stops.asSequence()+            .map { TransitStop(id = it.id, name = it.name.ifBlank { it.id }, lat = it.lat, lon = it.lon) }+            .distinctBy { it.id }+            .take(MAX_STOPS)+            .toList()+    }++    private suspend fun fetchDepartures(stopId: String): List<Departure> = withContext(Dispatchers.IO) {+        val url = "$BASE_URL/api/v1/stoptimes" ++            "?stopId=${enc(stopId)}&n=$DEPARTURE_COUNT&arriveBy=false"+        val resp: MotisStoptimes = NetworkClient.getJson(url, REQUEST_HEADERS, useSystemTrust = true)+        resp.stopTimes.mapNotNull { it.toDeparture() }+    }++    /** Map a MOTIS stoptime → app [Departure]; drop entries with no usable+     *  departure time. Delay is realtime − scheduled in whole minutes. */+    private fun MotisStopTime.toDeparture(): Departure? {+        val place = place ?: return null+        val scheduled = parseEpoch(place.scheduledDeparture ?: place.departure) ?: return null+        val realtime = parseEpoch(place.departure) ?: scheduled+        val delayMin = ((realtime - scheduled) / 60_000L).toInt()+        return Departure(+            line = routeShortName?.ifBlank { null } ?: agencyName?.ifBlank { null } ?: "",+            headsign = headsign?.ifBlank { null } ?: place.name ?: "",+            scheduledMillis = scheduled,+            realtimeMillis = realtime,+            delayMinutes = delayMin,+            realTime = realTime,+            platform = (place.track ?: place.scheduledTrack)?.ifBlank { null },+            mode = mode,+            routeColor = routeColor?.removePrefix("#")?.ifBlank { null },+            cancelled = cancelled,+        )+    }++    /** Parse a MOTIS ISO-8601 timestamp (with zone offset) → epoch millis, or+     *  null. Tolerates a plain `...Z` instant too. */+    private fun parseEpoch(iso: String?): Long? {+        if (iso.isNullOrBlank()) return null+        return runCatching { OffsetDateTime.parse(iso).toInstant().toEpochMilli() }+            .recoverCatching { Instant.parse(iso).toEpochMilli() }+            .getOrNull()+    }++    private fun round3(v: Double): Double = Math.round(v * 1000.0) / 1000.0+    private fun enc(s: String): String = URLEncoder.encode(s, "UTF-8")+}
maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.ktnew file mode 100644index 0000000000..0674e7c2f3--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/transit/TransitousModels.kt@@ -0,0 +1,92 @@+package com.vayunmathur.maps.data.transit++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Public-transit models for the P10 departure boards (Transitous / MOTIS,+ * open GTFS + GTFS-RT). Two layers of types live here:+ *+ *  - **App models** ([TransitStop], [Departure]) — what the overlay layer, the+ *    ViewModel and the [com.vayunmathur.maps.ui.DeparturesSheet] consume. They+ *    are position/epoch-based and carry no MOTIS wire quirks.+ *  - **Wire DTOs** (the `Motis*` classes) — the subset of the MOTIS v1 REST+ *    responses we actually read. Every field is optional/defaulted and the+ *    [com.vayunmathur.library.network.NetworkClient] JSON is+ *    `ignoreUnknownKeys`, so a MOTIS schema change degrades to nulls rather+ *    than throwing (mirrors the Google-scrape null-safety convention).+ */++/** A transit stop drawn on the map and tapped to open its departure board. */+data class TransitStop(+    val id: String,+    val name: String,+    val lat: Double,+    val lon: Double,+)++/**+ * One upcoming departure at a stop. Times are epoch millis so the sheet can run+ * a purely client-side live countdown; [delayMinutes] is realtime − scheduled+ * (positive = late, negative = early) and drives the delay colouring.+ */+data class Departure(+    val line: String,+    val headsign: String,+    val scheduledMillis: Long,+    val realtimeMillis: Long,+    val delayMinutes: Int,+    val realTime: Boolean,+    val platform: String?,+    val mode: String?,+    /** GTFS route colour as a 6-digit hex WITHOUT a leading `#`, or null. */+    val routeColor: String?,+    val cancelled: Boolean,+)++// --- MOTIS v1 wire DTOs ----------------------------------------------------++/** Response of `GET /api/v1/map/stops` — the stops within a viewport box. */+@Serializable+data class MotisMapStop(+    val id: String,+    val name: String = "",+    val lat: Double,+    val lon: Double,+)++/** Response of `GET /api/v1/stoptimes` — the live board for one stop. */+@Serializable+data class MotisStoptimes(+    val stopTimes: List<MotisStopTime> = emptyList(),+)++@Serializable+data class MotisStopTime(+    val place: MotisPlace? = null,+    val mode: String? = null,+    val realTime: Boolean = false,+    val headsign: String? = null,+    val agencyName: String? = null,+    val routeShortName: String? = null,+    val routeColor: String? = null,+    val routeTextColor: String? = null,+    val tripId: String? = null,+    val cancelled: Boolean = false,+)++/**+ * A place node inside a MOTIS stoptime. Times are ISO-8601 strings (with a zone+ * offset); `scheduled*` is the timetable time and the bare field is realtime.+ */+@Serializable+data class MotisPlace(+    val name: String? = null,+    val stopId: String? = null,+    val arrival: String? = null,+    val departure: String? = null,+    @SerialName("scheduledArrival") val scheduledArrival: String? = null,+    @SerialName("scheduledDeparture") val scheduledDeparture: String? = null,+    val track: String? = null,+    @SerialName("scheduledTrack") val scheduledTrack: String? = null,+)
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktnew file mode 100644index 0000000000..94c9f26a8e--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -0,0 +1,255 @@+package com.vayunmathur.maps.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextDecoration+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconRefresh+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.Text+import com.vayunmathur.maps.R+import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.util.DeparturesState+import kotlinx.coroutines.delay++/**+ * Public-transit departure board (P10): a live board for one stop, opened by+ * tapping a transit-stop pin. Departures are grouped by line (each with its GTFS+ * route colour), show a client-side live countdown, and are coloured by delay+ * (on-time green, slightly late amber, very late / cancelled red). Uses the+ * shared [ModalBottomSheet] from `:library:ui` (no raw scaffold), mirroring+ * [ParkingSheet] / [LayersSheet].+ *+ * The board is ONLINE-ONLY (Transitous); a failed fetch degrades to the+ * "no departures" state rather than an error.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DeparturesSheet(+    state: DeparturesState,+    onDismiss: () -> Unit,+    onRefresh: () -> Unit,+) {+    val stop: TransitStop? = when (state) {+        is DeparturesState.Loading -> state.stop+        is DeparturesState.Loaded -> state.stop+        DeparturesState.Idle -> null+    }++    // Live countdown clock: recomputed every 15 s (minute-granularity display).+    var now by remember { mutableLongStateOf(System.currentTimeMillis()) }+    LaunchedEffectTicker { now = it }++    ModalBottomSheet(onDismissRequest = onDismiss) {+        Column(Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 24.dp)) {+            Row(+                Modifier.fillMaxWidth(),+                horizontalArrangement = Arrangement.SpaceBetween,+                verticalAlignment = Alignment.CenterVertically,+            ) {+                Column(Modifier.weight(1f)) {+                    Text(+                        stop?.name ?: stringResource(R.string.transit_departures_title),+                        style = MaterialTheme.typography.titleMedium,+                        color = MaterialTheme.colorScheme.primary,+                        maxLines = 2,+                        overflow = TextOverflow.Ellipsis,+                    )+                    Text(+                        stringResource(R.string.transit_departures_title),+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+                IconButton(onClick = onRefresh) {+                    IconRefresh()+                }+            }++            Spacer(Modifier.height(8.dp))++            when (state) {+                is DeparturesState.Loading, DeparturesState.Idle -> {+                    Text(+                        stringResource(R.string.transit_departures_loading),+                        style = MaterialTheme.typography.bodyMedium,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                    )+                }+                is DeparturesState.Loaded -> {+                    if (state.departures.isEmpty()) {+                        Text(+                            stringResource(R.string.transit_departures_none),+                            style = MaterialTheme.typography.bodyMedium,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    } else {+                        DepartureList(state.departures, now)+                    }+                }+            }+        }+    }+}++/** Group departures by line (ordered by the soonest departure in each group)+ *  and render each as a coloured line badge + its upcoming trips. */+@Composable+private fun DepartureList(departures: List<Departure>, now: Long) {+    val groups = remember(departures) {+        departures+            .sortedBy { it.realtimeMillis }+            .groupBy { it.line }+            .entries+            .sortedBy { entry -> entry.value.minOfOrNull { it.realtimeMillis } ?: Long.MAX_VALUE }+    }++    LazyColumn(Modifier.fillMaxWidth().heightIn(max = 420.dp)) {+        items(groups, key = { it.key }) { (line, trips) ->+            Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {+                LineBadge(line, trips.first().routeColor)+                Spacer(Modifier.height(4.dp))+                trips.forEach { dep ->+                    DepartureRow(dep, now)+                }+            }+            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)+        }+    }+}++@Composable+private fun LineBadge(line: String, routeColor: String?) {+    val bg = parseHexColor(routeColor) ?: MaterialTheme.colorScheme.primary+    Text(+        text = line.ifBlank { "—" },+        style = MaterialTheme.typography.labelLarge,+        fontWeight = FontWeight.Bold,+        color = onColorFor(bg),+        modifier = Modifier+            .clip(RoundedCornerShape(6.dp))+            .background(bg)+            .padding(horizontal = 8.dp, vertical = 2.dp),+    )+}++@Composable+private fun DepartureRow(dep: Departure, now: Long) {+    Row(+        Modifier.fillMaxWidth().padding(vertical = 4.dp),+        horizontalArrangement = Arrangement.SpaceBetween,+        verticalAlignment = Alignment.CenterVertically,+    ) {+        Column(Modifier.weight(1f)) {+            Text(+                dep.headsign.ifBlank { "—" },+                style = MaterialTheme.typography.bodyMedium,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+                textDecoration = if (dep.cancelled) TextDecoration.LineThrough else null,+            )+            val platform = dep.platform+            if (platform != null) {+                Text(+                    stringResource(R.string.transit_platform, platform),+                    style = MaterialTheme.typography.bodySmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }+        }++        Column(horizontalAlignment = Alignment.End) {+            if (dep.cancelled) {+                Text(+                    stringResource(R.string.transit_cancelled),+                    style = MaterialTheme.typography.labelMedium,+                    fontWeight = FontWeight.Bold,+                    color = DELAY_LATE,+                )+            } else {+                Text(+                    countdownText(dep.realtimeMillis, now),+                    style = MaterialTheme.typography.titleSmall,+                    fontWeight = FontWeight.Bold,+                    color = delayColor(dep.delayMinutes),+                )+                if (dep.realTime && dep.delayMinutes != 0) {+                    Text(+                        stringResource(R.string.transit_delay_minutes, dep.delayMinutes),+                        style = MaterialTheme.typography.bodySmall,+                        color = delayColor(dep.delayMinutes),+                    )+                }+            }+        }+    }+}++/** Minutes until [target] as display text; "Now" once it's due/passed. */+@Composable+private fun countdownText(target: Long, now: Long): String {+    val minutes = Math.ceil((target - now) / 60_000.0).toInt()+    return if (minutes <= 0) stringResource(R.string.transit_now)+    else stringResource(R.string.transit_minutes, minutes)+}++private val DELAY_ON_TIME = Color(0xFF2E7D32)+private val DELAY_SLIGHT = Color(0xFFF9A825)+private val DELAY_LATE = Color(0xFFC62828)++/** On-time/early → green, 1–4 min late → amber, ≥5 late → red. */+private fun delayColor(delayMinutes: Int): Color = when {+    delayMinutes <= 0 -> DELAY_ON_TIME+    delayMinutes < 5 -> DELAY_SLIGHT+    else -> DELAY_LATE+}++/** Parse a 6-digit hex (with or without `#`) → [Color], or null. */+private fun parseHexColor(hex: String?): Color? {+    if (hex.isNullOrBlank()) return null+    return runCatching { Color(android.graphics.Color.parseColor("#" + hex.removePrefix("#"))) }.getOrNull()+}++/** Readable text colour (black/white) for a coloured badge background. */+private fun onColorFor(bg: Color): Color {+    val luminance = 0.299 * bg.red + 0.587 * bg.green + 0.114 * bg.blue+    return if (luminance > 0.6) Color.Black else Color.White+}++/** A once-per-15s ticker that reports the current epoch millis to [onTick]. */+@Composable+private fun LaunchedEffectTicker(onTick: (Long) -> Unit) {+    androidx.compose.runtime.LaunchedEffect(Unit) {+        while (true) {+            onTick(System.currentTimeMillis())+            delay(15_000L)+        }+    }+}
maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.ktindex 4a6813e9a1..871717597b 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/LayersSheet.kt@@ -8,6 +8,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.IconDirections import com.vayunmathur.library.ui.IconShield import com.vayunmathur.library.ui.IconStyle import com.vayunmathur.library.ui.IconWarning@@ -38,6 +39,8 @@ fun LayersSheet(     onSatelliteChange: (Boolean) -> Unit,     safetyEnabled: Boolean,     onSafetyChange: (Boolean) -> Unit,+    transitEnabled: Boolean,+    onTransitChange: (Boolean) -> Unit, ) {     ModalBottomSheet(onDismissRequest = onDismiss) {         Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) {@@ -68,6 +71,16 @@ fun LayersSheet(                 )             } +            // Transit — live (P10). Shows nearby stops; tap a stop for its+            // live departure board (Transitous, online-only).+            SettingsSwitchRow(+                title = stringResource(R.string.layer_transit),+                supportingText = stringResource(R.string.layer_transit_desc),+                checked = transitEnabled,+                onCheckedChange = onTransitChange,+                leadingContent = { IconDirections() },+            )+             // Safety layers — surfaced now, gated on the P13 PMTiles v5.             SettingsSwitchRow(                 title = stringResource(R.string.layer_safety),
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 b17b8ebab5..4f56f8580d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -112,7 +112,7 @@ import com.vayunmathur.maps.R as MapsR  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, zonesViewModel: MapsZonesViewModel, savedPlacesViewModel: SavedPlacesViewModel, poiViewModel: GooglePoiMapViewModel, searchViewModel: MapsSearchViewModel, settingsViewModel: MapSettingsViewModel, parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel) {+fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, zonesViewModel: MapsZonesViewModel, savedPlacesViewModel: SavedPlacesViewModel, poiViewModel: GooglePoiMapViewModel, searchViewModel: MapsSearchViewModel, settingsViewModel: MapSettingsViewModel, parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel, transitViewModel: com.vayunmathur.maps.util.TransitStopsViewModel) {     val selectedFeature by viewModel.selectedFeature.collectAsState()     val context = LocalContext.current     val coroutineScope = rememberCoroutineScope()@@ -134,8 +134,15 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     val trafficEnabled by settingsViewModel.trafficLayer.collectAsState()     val satelliteEnabled by settingsViewModel.satelliteLayer.collectAsState()     val safetyEnabled by settingsViewModel.safetyLayer.collectAsState()+    val transitEnabled by settingsViewModel.transitLayer.collectAsState()     var showLayersSheet by remember { mutableStateOf(false) } +    // Public transit (P10): nearby stops overlay + live departure board. Stops+    // are only fetched/drawn while the Transit layer is on.+    val transitStops by transitViewModel.stops.collectAsState()+    val selectedTransitStop by transitViewModel.selected.collectAsState()+    val departuresState by transitViewModel.departures.collectAsState()+     // Google POI overlay pins (viewport scrape → custom layer, replacing the     // suppressed native basemap POIs).     val googlePins by poiViewModel.pins.collectAsState()@@ -154,7 +161,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,         )     } -    LaunchedEffect(camera.position) {+    LaunchedEffect(camera.position, transitEnabled) {         if (camera.position.zoom >= 11.0) {             delay(300) // Debounce traffic loading             val projection = camera.projection@@ -168,6 +175,11 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                 // Refresh the Google POI overlay for the idle viewport (VM                 // debounces + LRU-caches the keyless scrape).                 poiViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west)+                // Refresh nearby transit stops (P10) only while the layer is on+                // (VM debounces + caches; wide views clear the overlay).+                if (transitEnabled) {+                    transitViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west)+                }             }         }     }@@ -412,6 +424,20 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                     return@launch                                 } +                                // Transit stop (P10): tapping a stop opens its+                                // live departure board instead of selecting a+                                // place. Only hit-tested while the layer is on.+                                if (transitEnabled) {+                                    val stopHit = projection?.queryRenderedFeatures(+                                        offset,+                                        setOf(TRANSIT_STOP_LAYER_ID)+                                    )?.firstNotNullOfOrNull { it.toTransitStop() }+                                    if (stopHit != null) {+                                        transitViewModel.openStop(stopHit)+                                        return@launch+                                    }+                                }+                                 // Hit-test the search-result pins first, then the                                 // ambient Google POI overlay — a pin tap re-selects                                 // the place as a GenericPlace so@@ -483,7 +509,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                             ClickResult.Pass                         }                 ) {-                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, googlePins, searchResults, savedPins, parkingSpot, trafficEnabled, satelliteEnabled, safetyEnabled)+                        MyMapLayers(selectedFeature, route?.get(selectedRouteType), json, userPosition, userBearing, navProgress, googlePins, searchResults, savedPins, parkingSpot, transitStops, trafficEnabled, satelliteEnabled, safetyEnabled, transitEnabled)                     }                 } @@ -731,6 +757,8 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         onSatelliteChange = { settingsViewModel.setSatelliteLayer(it) },                         safetyEnabled = safetyEnabled,                         onSafetyChange = { settingsViewModel.setSafetyLayer(it) },+                        transitEnabled = transitEnabled,+                        onTransitChange = { settingsViewModel.setTransitLayer(it) },                     )                 } @@ -760,6 +788,16 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         )                     }                 }++                // Departure board (P10): opened by tapping a transit stop. Live+                // board from Transitous (online-only); dismiss clears selection.+                if (selectedTransitStop != null) {+                    DeparturesSheet(+                        state = departuresState,+                        onDismiss = { transitViewModel.closeStop() },+                        onRefresh = { transitViewModel.refresh() },+                    )+                }             }         }     }
maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.ktindex ecdeccadc5..5f8a7a8828 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -57,9 +57,11 @@ fun MyMapLayers(     searchResults: List<SearchResult> = emptyList(),     savedPlaces: List<com.vayunmathur.maps.data.SavedPlace> = emptyList(),     parkingSpot: com.vayunmathur.maps.data.ParkingSpot? = null,+    transitStops: List<com.vayunmathur.maps.data.transit.TransitStop> = emptyList(),     trafficEnabled: Boolean = true,     satelliteEnabled: Boolean = false,     safetyEnabled: Boolean = false,+    transitEnabled: Boolean = false, ) {     val trafficVersion by OfflineRouter.trafficVersion.collectAsState()     val context = LocalContext.current@@ -166,6 +168,12 @@ fun MyMapLayers(         // Parking pin (P9). Tap → parking sheet (handled in MapPage.onMapClick).         ParkingLayer(parkingSpot) +        // Nearby transit stops (P10). Shown only when the Transit layer is on;+        // tap a stop → live departure board (handled in MapPage.onMapClick).+        if (transitEnabled) {+            TransitStopsLayer(transitStops)+        }+         // Posted-speed-limit probe overlay (Decision D4). Invisible; queried         // under the puck during navigation. No-op until the tileset is hosted.         MaxspeedLayer()
maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.ktnew file mode 100644index 0000000000..9ea4313a91--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/TransitStopsLayer.kt@@ -0,0 +1,136 @@+package com.vayunmathur.maps.ui++import androidx.compose.runtime.Composable+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.graphics.Color+import androidx.compose.ui.graphics.ImageBitmap+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.unit.dp+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.string+import com.vayunmathur.maps.data.transit.TransitStop+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.jsonPrimitive+import org.maplibre.compose.expressions.dsl.const+import org.maplibre.compose.expressions.dsl.image+import org.maplibre.compose.expressions.dsl.interpolate+import org.maplibre.compose.expressions.dsl.linear+import org.maplibre.compose.expressions.dsl.zoom+import org.maplibre.compose.layers.CircleLayer+import org.maplibre.compose.layers.SymbolLayer+import org.maplibre.compose.sources.GeoJsonData+import org.maplibre.compose.sources.GeoJsonOptions+import org.maplibre.compose.sources.GeoJsonSource+import org.maplibre.compose.util.MaplibreComposable+import org.maplibre.spatialk.geojson.FeatureCollection+import org.maplibre.spatialk.geojson.Point+import org.maplibre.spatialk.geojson.Position++/** Symbol layer id — hit-tested in MapPage.onMapClick so a tapped transit stop+ *  opens its departure board. */+const val TRANSIT_STOP_LAYER_ID = "transit-stop-pins"+private const val TRANSIT_STOP_DOT_LAYER_ID = "transit-stop-dots"+private const val TRANSIT_STOP_SOURCE_ID = "transit-stop-geojson"++/** Transit teal so stops read distinctly from Google POIs (category colours),+ *  saved pins (blue) and search results (red). */+private val TRANSIT_STOP_COLOR = Color(0xFF00897B)++/**+ * Nearby-transit-stops overlay (P10): a [GeoJsonSource] fed from the viewport+ * Transitous fetch plus a [CircleLayer] dot and a [SymbolLayer] glyph on top,+ * ported to maplibre-compose declarative layers exactly like [GooglePoiLayer] /+ * [SavedPlacesLayer]. Mounted only when the Transit layer toggle is on (see+ * [MyMapLayers]); a tap → the [DeparturesSheet] via [toTransitStop].+ */+@Composable+@MaplibreComposable+fun TransitStopsLayer(stops: List<TransitStop>) {+    val marker = remember { generateTransitMarkerBitmap() }+    var source by remember { mutableStateOf<GeoJsonSource?>(null) }++    LaunchedEffect(Unit) {+        source = GeoJsonSource(+            TRANSIT_STOP_SOURCE_ID,+            GeoJsonData.Features(FeatureCollection(emptyList<Feature1>())),+            GeoJsonOptions(),+        )+    }++    source?.let { src ->+        LaunchedEffect(stops) {+            src.setData(GeoJsonData.Features(FeatureCollection(stops.map { it.toFeature() })))+        }++        CircleLayer(+            TRANSIT_STOP_DOT_LAYER_ID,+            src,+            color = const(TRANSIT_STOP_COLOR),+            radius = interpolate(+                linear(), zoom(),+                12 to const(4.dp),+                15 to const(6.dp),+                18 to const(8.dp),+            ),+            strokeColor = const(Color.White),+            strokeWidth = const(1.5.dp),+        )++        SymbolLayer(+            TRANSIT_STOP_LAYER_ID,+            src,+            iconImage = image(marker),+            iconSize = interpolate(+                linear(), zoom(),+                12 to const(0.35f),+                15 to const(0.5f),+                18 to const(0.65f),+            ),+        )+    }+}++/** Rebuild a stop as a GeoJSON point feature; id/name/lat/lon ride along so+ *  onMapClick can open the board for it. */+private fun TransitStop.toFeature(): Feature1 = Feature1(+    Point(Position(lon, lat)),+    JsonObject(+        mapOf(+            "id" to JsonPrimitive(id),+            "name" to JsonPrimitive(name),+            "lat" to JsonPrimitive(lat),+            "lng" to JsonPrimitive(lon),+        )+    ),+)++/** Convert a hit-tested transit-stop feature back into a [TransitStop] so the+ *  tap handler can open the departure board. */+fun Feature1.toTransitStop(): TransitStop? {+    val props = properties ?: return null+    val id = props.string("id")?.ifBlank { null } ?: return null+    val name = props.string("name")?.ifBlank { null } ?: id+    val lat = props["lat"]?.jsonPrimitive?.doubleOrNull ?: return null+    val lng = props["lng"]?.jsonPrimitive?.doubleOrNull ?: return null+    return TransitStop(id, name, lat, lng)+}++/** Draw the transit marker once: a white centre dot on the teal base circle so+ *  it reads as a transit stop at pin size. */+private fun generateTransitMarkerBitmap(): ImageBitmap {+    val size = 48+    val bmp = android.graphics.Bitmap.createBitmap(size, size, android.graphics.Bitmap.Config.ARGB_8888)+    val canvas = android.graphics.Canvas(bmp)+    val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG)+    val cx = size / 2f+    val cy = size / 2f+    paint.color = android.graphics.Color.WHITE+    canvas.drawCircle(cx, cy, size / 4f, paint)+    return bmp.asImageBitmap()+}
maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.ktindex 16c17dd6e5..3c12e0b1db 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt@@ -69,6 +69,9 @@ class MapSettingsViewModel(application: Application) : AndroidViewModel(applicat     val safetyLayer: StateFlow<Boolean> = boolPref(         MapPreferences.KEY_LAYER_SAFETY, MapPreferences.DEFAULT_LAYER_SAFETY,     )+    val transitLayer: StateFlow<Boolean> = boolPref(+        MapPreferences.KEY_LAYER_TRANSIT, MapPreferences.DEFAULT_LAYER_TRANSIT,+    )      fun setTrafficLayer(enabled: Boolean) =         launch { ds.setBoolean(MapPreferences.KEY_LAYER_TRAFFIC, enabled) }@@ -79,6 +82,9 @@ class MapSettingsViewModel(application: Application) : AndroidViewModel(applicat     fun setSafetyLayer(enabled: Boolean) =         launch { ds.setBoolean(MapPreferences.KEY_LAYER_SAFETY, enabled) } +    fun setTransitLayer(enabled: Boolean) =+        launch { ds.setBoolean(MapPreferences.KEY_LAYER_TRANSIT, enabled) }+     private fun boolPref(key: String, default: Boolean): StateFlow<Boolean> =         ds.booleanFlow(key).stateIn(             viewModelScope, SharingStarted.Eagerly, ds.getBoolean(key, default),
maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.ktnew file mode 100644index 0000000000..bca5302331--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt@@ -0,0 +1,128 @@+package com.vayunmathur.maps.util++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.maps.data.transit.Departure+import com.vayunmathur.maps.data.transit.TransitStop+import com.vayunmathur.maps.data.transit.TransitousDataSource+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.FlowPreview+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.debounce+import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.flow.flatMapLatest+import kotlinx.coroutines.flow.flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.flowOn+import kotlinx.coroutines.flow.mapLatest+import kotlinx.coroutines.flow.stateIn+import kotlin.math.abs++/**+ * Drives the P10 public-transit UI: the nearby-stops overlay and the departure+ * board (both online via [TransitousDataSource]).+ *+ * Two independent flows:+ *  - [stops] — a debounced, LRU-cached list of [TransitStop]s for the current+ *    viewport (mirrors [GooglePoiMapViewModel]); wider-than-city views clear the+ *    overlay since stops there are meaningless and dense.+ *  - [departures] — the board for the [openStop]-selected stop, re-fetched on+ *    [refresh]. The live countdown itself is computed client-side in the sheet+ *    from each departure's epoch time, so no polling is needed here.+ *+ * All network is on [Dispatchers.IO]. ONLINE-ONLY (P11 adds offline).+ */+class TransitStopsViewModel(application: Application) : AndroidViewModel(application) {++    private data class Bbox(val north: Double, val east: Double, val south: Double, val west: Double)++    // Rounded viewport box; null suppresses fetching (zoomed out / too wide).+    private val _bbox = MutableStateFlow<Bbox?>(null)++    @OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)+    val stops: StateFlow<List<TransitStop>> = _bbox+        .filterNotNull()+        .debounce(DEBOUNCE_MS)+        .distinctUntilChanged()+        .mapLatest { b -> TransitousDataSource.stopsInBbox(b.south, b.west, b.north, b.east) }+        .flowOn(Dispatchers.IO)+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())++    /**+     * Feed a camera-idle viewport (from `queryVisibleBoundingBox()`). Views+     * wider than [MAX_LAT_SPAN] clear the stops; otherwise the rounded box drives+     * the next fetch.+     */+    fun onViewport(north: Double, east: Double, south: Double, west: Double) {+        if (abs(north - south) > MAX_LAT_SPAN) {+            _bbox.value = null+            return+        }+        _bbox.value = Bbox(round3(north), round3(east), round3(south), round3(west))+    }++    // --- Departure board ---------------------------------------------------++    private val _selected = MutableStateFlow<TransitStop?>(null)+    val selected: StateFlow<TransitStop?> = _selected.asStateFlow()++    // Bumped by refresh() to force a re-fetch of the same stop.+    private val _refreshTick = MutableStateFlow(0)++    @OptIn(ExperimentalCoroutinesApi::class)+    val departures: StateFlow<DeparturesState> =+        combine(_selected, _refreshTick) { stop, tick -> stop to tick }+            .flatMapLatest { (stop, tick) ->+                if (stop == null) {+                    flowOf(DeparturesState.Idle)+                } else {+                    flow {+                        emit(DeparturesState.Loading(stop))+                        val force = tick > 0+                        val deps = TransitousDataSource.departures(stop.id, force = force)+                        emit(DeparturesState.Loaded(stop, deps))+                    }.flowOn(Dispatchers.IO)+                }+            }+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), DeparturesState.Idle)++    /** Open the board for [stop] (called from the map tap). */+    fun openStop(stop: TransitStop) {+        _refreshTick.value = 0+        _selected.value = stop+    }++    /** Close the board. */+    fun closeStop() {+        _selected.value = null+    }++    /** Force a live re-fetch of the current stop's board. */+    fun refresh() {+        if (_selected.value != null) _refreshTick.value += 1+    }++    private fun round3(v: Double): Double = Math.round(v * 1000.0) / 1000.0++    private companion object {+        const val DEBOUNCE_MS = 500L++        // ~9 km of latitude — transit stops are dense, so keep the fetch to a+        // tighter zoom than the Google-POI overlay.+        const val MAX_LAT_SPAN = 0.08+    }+}++/** UI state for the departure board. */+sealed interface DeparturesState {+    data object Idle : DeparturesState+    data class Loading(val stop: TransitStop) : DeparturesState+    data class Loaded(val stop: TransitStop, val departures: List<Departure>) : DeparturesState+}
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 12b74098ba..953fae045f 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -294,6 +294,27 @@     <string name="layer_safety_desc">Show speed cameras, stop signs and signals</string>     <!-- LayersSheet: safety layers description while the data isn't available yet. -->     <string name="layer_safety_unavailable">Coming soon</string>+    <!-- LayersSheet: public-transit layer toggle. Noun. -->+    <string name="layer_transit">Transit</string>+    <!-- LayersSheet: transit layer description. -->+    <string name="layer_transit_desc">Show nearby stops and live departures</string>++    <!-- Departure board: section subtitle under the stop name. Noun. -->+    <string name="transit_departures_title">Departures</string>+    <!-- Departure board: shown while the live board is loading. -->+    <string name="transit_departures_loading">Loading departures\u2026</string>+    <!-- Departure board: shown when no upcoming departures were found. -->+    <string name="transit_departures_none">No upcoming departures</string>+    <!-- Departure board: platform/track label. %1$s = platform name e.g. "3" -->+    <string name="transit_platform">Platform %1$s</string>+    <!-- Departure board: a cancelled trip. -->+    <string name="transit_cancelled">Cancelled</string>+    <!-- Departure board: a departure that is due now / already departing. -->+    <string name="transit_now">Now</string>+    <!-- Departure board: minutes until departure. %1$d = whole minutes e.g. "5 min" -->+    <string name="transit_minutes">%1$d min</string>+    <!-- Departure board: realtime delay vs schedule, signed. %1$d = signed minutes e.g. "+3 min" -->+    <string name="transit_delay_minutes">%1$+d min</string>      <!-- Settings: screen title. Noun. -->     <string name="settings_title">Settings</string>