Modern Apps git

← Modern-Apps.git

maps(transit): offline scheduled departure boards (no internet). New Rust transit::stop_departures reads the existing .transit RAPTOR pack for the nearest stop's upcoming departures; JNI getStopDeparturesNative + OfflineRouter.getStopDeparturesOffline; TransitStopsViewModel falls back to it when the online (already-realtime via MOTIS) board is empty. Reuses the downloaded .transit index - no graph regen.

Commit
4797343d18b3b51da90d44704f17f0c912cb2542
Author
vayun-mathur <[email protected]>
When
2026-08-18 23:14 UTC (3 months ago)
Parents
1e4cf1f

Diff

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 4474eef11e..2b536fcf37 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -6,6 +6,7 @@ import androidx.annotation.Keep import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.maps.R import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.transit.Departure import java.io.File import java.io.OutputStream import java.net.InetAddress@@ -117,6 +118,22 @@ object OfflineRouter {             weekday: Int,             date: Int     ): Array<RawStep>?+    /**+     * Offline scheduled departure board (no internet): upcoming departures from+     * the stop nearest `(lat,lon)` in `<basePath>/<feed>.transit`. `depSecs` is+     * seconds since local midnight, `weekday` 0=Mon..6=Sun, `date` yyyymmdd.+     * Returns null when the feed is missing or doesn't cover the point.+     */+    private external fun getStopDeparturesNative(+            basePath: String,+            feed: String,+            lat: Double,+            lon: Double,+            depSecs: Int,+            weekday: Int,+            date: Int,+            max: Int+    ): Array<RawDeparture>?     private external fun updateTrafficNative(             edgeIds: LongArray,             speeds: ByteArray,@@ -222,6 +239,22 @@ object OfflineRouter {             val lanePacked: IntArray     ) +    /** One offline scheduled departure from the baked `.transit` index. */+    class RawDeparture+    @Keep+    constructor(+            val routeName: String,+            val headsign: String,+            val feed: String,+            val stopCode: String,+            /** GTFS route colour as packed 0xRRGGBB, or 0 when absent. */+            val routeColor: Int,+            /** GTFS route_type. */+            val routeType: Int,+            /** Seconds since local (service-day) midnight. */+            val depSecs: Int+    )+     private var isInitialized = false     /** Base dir (external files) holding downloaded packs incl. `*.transit`. */     private var basePath: String? = null@@ -349,6 +382,86 @@ object OfflineRouter {         null     } +    /**+     * Offline scheduled departure board: upcoming departures for the stop nearest+     * `(lat,lon)` from any downloaded `*.transit` index covering it. Scheduled+     * times only (`realTime=false`); the online Transitous board (which already+     * carries GTFS-RT delays) is preferred when the device is online — this is+     * the no-internet fallback. Returns an empty list when nothing is available.+     */+    suspend fun getStopDeparturesOffline(+            context: Context,+            lat: Double,+            lon: Double,+            max: Int = 30+    ): List<Departure> = withContext(Dispatchers.Default) {+        if (!isInitialized) initialize(context)+        val base = basePath ?: return@withContext emptyList()+        val feeds = File(base)+                .listFiles { f -> f.isFile && f.name.endsWith(".transit") }+                ?.map { it.name.removeSuffix(".transit") }+                ?: emptyList()+        if (feeds.isEmpty()) return@withContext emptyList()++        val now = java.util.Calendar.getInstance()+        val depSecs = now.get(java.util.Calendar.HOUR_OF_DAY) * 3600 ++                now.get(java.util.Calendar.MINUTE) * 60 ++                now.get(java.util.Calendar.SECOND)+        val weekday = (now.get(java.util.Calendar.DAY_OF_WEEK) + 5) % 7+        val date = now.get(java.util.Calendar.YEAR) * 10000 ++                (now.get(java.util.Calendar.MONTH) + 1) * 100 ++                now.get(java.util.Calendar.DAY_OF_MONTH)+        // Epoch millis of local midnight, so depSecs -> absolute scheduled time.+        now.set(java.util.Calendar.HOUR_OF_DAY, 0)+        now.set(java.util.Calendar.MINUTE, 0)+        now.set(java.util.Calendar.SECOND, 0)+        now.set(java.util.Calendar.MILLISECOND, 0)+        val midnightMillis = now.timeInMillis++        val all = mutableListOf<Departure>()+        for (feed in feeds) {+            val raw = try {+                getStopDeparturesNative(base, feed, lat, lon, depSecs, weekday, date, max)+            } catch (_: Exception) {+                null+            } ?: continue+            for (d in raw) {+                val scheduled = midnightMillis + d.depSecs.toLong() * 1000L+                all.add(+                        Departure(+                                line = d.routeName,+                                headsign = d.headsign,+                                scheduledMillis = scheduled,+                                realtimeMillis = scheduled,+                                delayMinutes = 0,+                                realTime = false,+                                platform = null,+                                mode = gtfsRouteTypeToMode(d.routeType),+                                routeColor = if (d.routeColor == 0) null+                                             else String.format("%06X", d.routeColor and 0xFFFFFF),+                                cancelled = false,+                        )+                )+            }+        }+        all.sortBy { it.scheduledMillis }+        all.take(max)+    }++    /** Map a GTFS `route_type` (base + extended ranges) to a coarse mode label. */+    private fun gtfsRouteTypeToMode(t: Int): String = when (t) {+        0, 5, 900 -> "TRAM"+        1, in 400..499 -> "SUBWAY"+        2, in 100..199 -> "RAIL"+        3, in 200..299, in 700..799, 800 -> "BUS"+        4, 1000, 1200 -> "FERRY"+        6, 1300 -> "AERIAL"+        7, 1400 -> "FUNICULAR"+        11 -> "TROLLEYBUS"+        12 -> "MONORAIL"+        else -> "TRANSIT"+    }+     suspend fun getRoute(             context: Context,             start: Position,
maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.ktindex 65fd5569a9..a676b922a7 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/TransitStopsViewModel.kt@@ -88,7 +88,19 @@ class TransitStopsViewModel(application: Application) : AndroidViewModel(applica                     flow {                         emit(DeparturesState.Loading(stop))                         val force = tick > 0-                        val deps = TransitousDataSource.departures(stop.id, force = force)+                        val online = TransitousDataSource.departures(stop.id, force = force)+                        // Offline scheduled fallback (no internet / feed gap): the+                        // online board already carries GTFS-RT delays, so only fall+                        // back to the baked .transit schedule when it's empty.+                        val deps = if (online.isNotEmpty()) {+                            online+                        } else {+                            runCatching {+                                OfflineRouter.getStopDeparturesOffline(+                                    getApplication(), stop.lat, stop.lon,+                                )+                            }.getOrDefault(emptyList())+                        }                         emit(DeparturesState.Loaded(stop, deps))                     }.flowOn(Dispatchers.IO)                 }
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsindex 5d7056e76b..e744fdfc0f 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -449,6 +449,110 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findTransitR     array.into_raw() } +// ---------------------------------------------------------------------------+// JNI: getStopDeparturesNative (offline scheduled departure board)+// ---------------------------------------------------------------------------++/// Offline scheduled departure board from the `<base>/<feed>.transit` index for+/// the stop nearest `(lat,lon)`. `dep_secs` = seconds since local midnight,+/// `weekday` 0=Mon..6=Sun, `date` yyyymmdd. Returns+/// `OfflineRouter.RawDeparture[]` (sorted, upcoming, scheduled-only) or `null`+/// when the feed is absent / doesn't cover the point — the Kotlin side then+/// keeps the online board.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getStopDeparturesNative<+    'local,+>(+    mut env: JNIEnv<'local>,+    _thiz: JObject<'local>,+    base_path: JString<'local>,+    feed: JString<'local>,+    lat: jdouble,+    lon: jdouble,+    dep_secs: jint,+    weekday: jint,+    date: jint,+    max: jint,+) -> jobjectArray {+    let null = std::ptr::null_mut();+    let base: String = match env.get_string(&base_path) {+        Ok(s) => s.into(),+        Err(_) => return null,+    };+    let feed_name: String = match env.get_string(&feed) {+        Ok(s) => s.into(),+        Err(_) => return null,+    };++    let index = match transit::TransitIndex::load(&base, &feed_name) {+        Some(i) => i,+        None => return null,+    };+    if !index.covers(lat, lon) {+        return null;+    }++    let deps = transit::stop_departures(+        &index,+        lat,+        lon,+        dep_secs.max(0) as u32,+        weekday.max(0) as u32,+        date.max(0) as u32,+        max.max(0) as usize,+    );++    let class = match env.find_class("com/vayunmathur/maps/util/OfflineRouter$RawDeparture") {+        Ok(c) => c,+        Err(_) => return null,+    };+    let ctor = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)V";+    let array = match env.new_object_array(deps.len() as i32, &class, JObject::null()) {+        Ok(a) => a,+        Err(_) => return null,+    };++    for (i, d) in deps.iter().enumerate() {+        let jroute: JObject = match env.new_string(&d.route_name) {+            Ok(s) => s.into(),+            Err(_) => return null,+        };+        let jheadsign: JObject = match env.new_string(&d.headsign) {+            Ok(s) => s.into(),+            Err(_) => return null,+        };+        let jfeed: JObject = match env.new_string(&d.feed) {+            Ok(s) => s.into(),+            Err(_) => return null,+        };+        let jcode: JObject = match env.new_string(&d.stop_code) {+            Ok(s) => s.into(),+            Err(_) => return null,+        };+        let obj = match env.new_object(+            &class,+            ctor,+            &[+                JValue::Object(&jroute),+                JValue::Object(&jheadsign),+                JValue::Object(&jfeed),+                JValue::Object(&jcode),+                JValue::Int(d.route_color as i32),+                JValue::Int(d.route_type as i32),+                JValue::Int(d.dep_secs as i32),+            ],+        ) {+            Ok(o) => o,+            Err(_) => return null,+        };+        if env.set_object_array_element(&array, i as i32, &obj).is_err() {+            return null;+        }+    }++    array.into_raw()+}+ // --------------------------------------------------------------------------- // JNI: updateTrafficNative // ---------------------------------------------------------------------------
maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 8b07fb6c02..514638eebb 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -568,6 +568,111 @@ pub fn plan(     Some(legs) } +/// A single upcoming scheduled departure from a stop (offline board).+pub struct StopDeparture {+    pub route_name: String,+    pub headsign: String,+    pub feed: String,+    pub stop_code: String,+    pub route_color: u32,+    pub route_type: u32,+    /// Departure time in seconds since service-day midnight (may exceed 86400 for+    /// trips running past midnight).+    pub dep_secs: u32,+}++/// Build an offline departure board for the stop(s) nearest to `(lat,lon)`.+///+/// Gathers every route serving the nearest stop (and its co-located platforms+/// within [`STATION_RADIUS_M`]) and returns upcoming scheduled departures at or+/// after `dep_secs` (seconds since local midnight) on the query service day,+/// sorted by time and capped at `max`. Empty when no stop is near or nothing+/// departs — the caller then keeps whatever the online board returned.+pub fn stop_departures(+    idx: &TransitIndex,+    lat: f64,+    lon: f64,+    dep_secs: u32,+    weekday: u32,+    date: u32,+    max: usize,+) -> Vec<StopDeparture> {+    const STATION_RADIUS_M: f64 = 150.0;+    const NEAREST_MAX_M: f64 = 400.0;++    let n = idx.stop_count;+    if n == 0 {+        return Vec::new();+    }+    // Nearest stop to the tapped point (stops are matched by lat/lon — there is+    // no MOTIS<->baked stop id join).+    let mut nearest = u32::MAX;+    let mut nearest_d = f64::MAX;+    for s in 0..n {+        let (slat, slon) = idx.stop_ll(s);+        let d = dist_m(lat, lon, slat, slon);+        if d < nearest_d {+            nearest_d = d;+            nearest = s;+        }+    }+    if nearest == u32::MAX || nearest_d > NEAREST_MAX_M {+        return Vec::new();+    }+    let (blat, blon) = idx.stop_ll(nearest);+    let feed = idx.feed_name();++    let mut out: Vec<StopDeparture> = Vec::new();+    for s in 0..n {+        let (slat, slon) = idx.stop_ll(s);+        if dist_m(blat, blon, slat, slon) > STATION_RADIUS_M {+            continue;+        }+        let code = idx.read_str(idx.stop(s).code_off);+        let (rs, re) = idx.stop_routes_range(s);+        for i in rs..re {+            let r = idx.stop_route(i);+            let route = idx.route(r);+            // Position of this stop within the route's ordered stop list.+            let mut pos = u32::MAX;+            for p in 0..route.n_stops {+                if idx.route_stop(route.first_route_stop + p) == s {+                    pos = p;+                    break;+                }+            }+            // Skip if not on the route, or it's the terminus (no onward departure).+            if pos == u32::MAX || pos + 1 >= route.n_stops {+                continue;+            }+            let rname = idx.read_str(route.name_off);+            for t in 0..route.n_trips {+                let ti = route.first_trip + t;+                let trip = idx.trip(ti);+                if !idx.service_runs(trip.service_idx, weekday, date) {+                    continue;+                }+                let dep = idx.stoptime(trip.first_stoptime + pos).dep_s;+                if dep < dep_secs {+                    continue;+                }+                out.push(StopDeparture {+                    route_name: rname.clone(),+                    headsign: idx.read_str(trip.headsign_off),+                    feed: feed.clone(),+                    stop_code: code.clone(),+                    route_color: route.color,+                    route_type: route.route_type,+                    dep_secs: dep,+                });+            }+        }+    }+    out.sort_by_key(|d| d.dep_secs);+    out.truncate(max);+    out+}+ fn stop_of_leg_start(idx: &TransitIndex, leg: &TransitLeg) -> u32 {     // Recover the leg's first stop index by matching its start coordinate.     if leg.coords.len() < 2 {