maps: convert JNI surface to shared jni_fn! macro
- Commit
6786c831880d1de269c7ce3c6ed8a17fa1c142a8- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 19:40 UTC (4 days ago)
- Parents
7fef409
LOC Phase 5 rollout. Fifteen of the sixteen offlinerouter JNI functions repeated the EnvUnowned / with_env / LogErrorAndDefault scaffold and convert to jni_bridge::jni_fn! across routes.rs, traffic_jni.rs and the transit_jni parts; notifyTrafficFetchFinishedNative stays hand-written. Bodies are verbatim (verified token-for-token); the one body that named its 'local lifetime in a closure annotation now names the macro's 'l, a purely local rename. Handles and null checks stay in the bodies, and now-unused EnvUnowned imports are dropped. Lines: the jni/ tree goes 1760 -> 1561 (-199, -11.3%); structure_check maps module 75,648 after, structure: OK. Cargo.lock gains only the jni_bridge edge for offlinerouter. Verified: nm -D on libofflinerouter.so before/after - exported symbol set identical (16/16 Java_ OfflineRouter symbols); cargo test -p offlinerouter: 128 passed, 1 ignored; JVM bridge tests :maps:testDevUnitTestNative OfflineRouterSlice3ExtraTest (3/3) + MapsTransitC5Test (2/2) passed (run excludes the pre-existing rustFileLength ratchet); cargo fmt --check -p offlinerouter clean.
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 69d936faeb..c15f62aa51 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3973,6 +3973,7 @@ version = "0.1.0" dependencies = [ "flate2", "jni",+ "jni_bridge", "libc", "ruzstd", "tilecodec",
maps/src/main/rust/Cargo.toml
diff --git a/maps/src/main/rust/Cargo.toml b/maps/src/main/rust/Cargo.tomlindex 104b9bc090..79f1f30868 100644--- a/maps/src/main/rust/Cargo.toml+++ b/maps/src/main/rust/Cargo.toml@@ -12,6 +12,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] # JNI surface (armv8-only). Upstream jni from crates.io; see the root Cargo.toml. jni.workspace = true+jni_bridge = { path = "../../../../library/jni-bridge/src/main/rust" } # mmap of the whole-world graph (nodes/edges/intermediate/…), mirroring the old # C++ router's mmap loader. Direct libc rather than memmap2 to keep the dep tree # minimal (memmap2 was intentionally dropped from the workspace).
maps/src/main/rust/src/jni/routes.rs
diff --git a/maps/src/main/rust/src/jni/routes.rs b/maps/src/main/rust/src/jni/routes.rsindex 1c245d43c0..688c5c664d 100644--- a/maps/src/main/rust/src/jni/routes.rs+++ b/maps/src/main/rust/src/jni/routes.rs@@ -8,7 +8,8 @@ use std::sync::{Arc, Mutex, OnceLock, RwLock}; use jni::objects::{JObject, JString, JValue}; use jni::sys::{jdouble, jint, jobjectArray};-use jni::{jni_sig, jni_str, Env, EnvUnowned};+use jni::{jni_sig, jni_str, Env};+use jni_bridge::jni_fn; use crate::geometry::TrafficSpeeds; use crate::graph::{Graph, WALK};@@ -101,211 +102,191 @@ pub(crate) fn ensure_traffic_loaded( // JNI: init // --------------------------------------------------------------------------- -#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_init<'local>(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,-) -> bool {- env.with_env(|env| -> jni::errors::Result<bool> {- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(false),- };+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_init -> bool; (_thiz: JObject<'l>, base_path: JString<'l>) |env| {+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(false),+ }; - // Single-archive first: one download carries tiles, graph, POI and- // transit, and the archive's own checks refuse a corrupt container before- // any section loads. Falls back to the multi-file layout.- let graph =- Graph::load_archive(&crate::graph::archive_path(&base)).or_else(|| Graph::load(&base));- match graph {- Some(g) => {- if let Ok(mut w) = GRAPH.write() {- *w = Some(Arc::new(g));- Ok(true)- } else {- Ok(false)- }+ // Single-archive first: one download carries tiles, graph, POI and+ // transit, and the archive's own checks refuse a corrupt container before+ // any section loads. Falls back to the multi-file layout.+ let graph =+ Graph::load_archive(&crate::graph::archive_path(&base)).or_else(|| Graph::load(&base));+ match graph {+ Some(g) => {+ if let Ok(mut w) = GRAPH.write() {+ *w = Some(Arc::new(g));+ Ok(true)+ } else {+ Ok(false) }- None => Ok(false), }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ None => Ok(false),+ }+} } // --------------------------------------------------------------------------- // JNI: findRouteNative // --------------------------------------------------------------------------- -#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNative<'local>(- mut env: EnvUnowned<'local>,- thiz: JObject<'local>,- s_lat: jdouble,- s_lon: jdouble,- e_lat: jdouble,- e_lon: jdouble,- mode: jint,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let null = std::ptr::null_mut();- let g = match graph() {- Some(g) => g,- None => return Ok(null),+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNative -> jobjectArray; (thiz: JObject<'l>, s_lat: jdouble, s_lon: jdouble, e_lat: jdouble, e_lon: jdouble, mode: jint) |env| {+ let null = std::ptr::null_mut();+ let g = match graph() {+ Some(g) => g,+ None => return Ok(null),+ };++ // Snapshot the current traffic speeds so the hot loop needs no locking and+ // concurrent updateTrafficNative calls don't block the whole route.+ let speeds: TrafficSpeeds = traffic_speeds().read().map(|m| m.clone()).unwrap_or_default();++ let state_mutex = route_state();+ let mut state = state_mutex.lock().unwrap();+ let RouteState { scratch, heap } = &mut *state;++ // prepare + search need the JNI env for the driving traffic prefetch.+ // The search asks on every expansion, but a square once requested stays+ // requested, so only the first ask per square needs the global lock.+ let ctx = {+ let mut last_square = u32::MAX;+ let mut seen_squares: HashSet<u32> = HashSet::new();+ let mut ensure = |lat_e7: i32, lon_e7: i32| {+ let (_, _, square) = traffic_square(lat_e7, lon_e7);+ if square == last_square {+ return;+ }+ last_square = square;+ if seen_squares.insert(square) {+ ensure_traffic_loaded(&mut *env, &thiz, lat_e7, lon_e7, false);+ } }; - // Snapshot the current traffic speeds so the hot loop needs no locking and- // concurrent updateTrafficNative calls don't block the whole route.- let speeds: TrafficSpeeds = traffic_speeds().read().map(|m| m.clone()).unwrap_or_default();-- let state_mutex = route_state();- let mut state = state_mutex.lock().unwrap();- let RouteState { scratch, heap } = &mut *state;-- // prepare + search need the JNI env for the driving traffic prefetch.- // The search asks on every expansion, but a square once requested stays- // requested, so only the first ask per square needs the global lock.- let ctx = {- let mut last_square = u32::MAX;- let mut seen_squares: HashSet<u32> = HashSet::new();- let mut ensure = |lat_e7: i32, lon_e7: i32| {- let (_, _, square) = traffic_square(lat_e7, lon_e7);- if square == last_square {- return;- }- last_square = square;- if seen_squares.insert(square) {- ensure_traffic_loaded(&mut *env, &thiz, lat_e7, lon_e7, false);- }- };-- let mut ctx = match prepare_routing(- &g, &speeds, &mut ensure, s_lat, s_lon, e_lat, e_lon, mode, scratch, heap,- ) {- Some(c) => c,- None => return Ok(null),- };- perform_search_loop(&g, &speeds, &mut ensure, mode, &mut ctx, scratch, heap);- ctx+ let mut ctx = match prepare_routing(+ &g, &speeds, &mut ensure, s_lat, s_lon, e_lat, e_lon, mode, scratch, heap,+ ) {+ Some(c) => c,+ None => return Ok(null), };+ perform_search_loop(&g, &speeds, &mut ensure, mode, &mut ctx, scratch, heap);+ ctx+ }; - // A route that never leaves the edge it snapped to reaches no node, so- // `target_node` stays unset; `ctx.direct` is the route in that case.- if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() {- return Ok(null);- }+ // A route that never leaves the edge it snapped to reaches no node, so+ // `target_node` stays unset; `ctx.direct` is the route in that case.+ if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() {+ return Ok(null);+ } - let mut steps = reconstruct_path(&g, &speeds, mode, &ctx, scratch);- // No elevation section (planet4 ships none): every sample is a fabricated 0 m, which- // Kotlin would draw as a flat chart with 0 m ascent. Empty arrays read as "no profile".- if !g.has_elevation() {- for step in &mut steps {- step.elevations.clear();- }+ let mut steps = reconstruct_path(&g, &speeds, mode, &ctx, scratch);+ // No elevation section (planet4 ships none): every sample is a fabricated 0 m, which+ // Kotlin would draw as a flat chart with 0 m ascent. Empty arrays read as "no profile".+ if !g.has_elevation() {+ for step in &mut steps {+ step.elevations.clear(); }- // Whole-route elevation totals (WS-G): cumulative ascent/descent in metres, computed once and- // carried on every RawStep so Kotlin can read them off any step.- let (ascent_m, descent_m) = route_ascent_descent(&steps);+ }+ // Whole-route elevation totals (WS-G): cumulative ascent/descent in metres, computed once and+ // carried on every RawStep so Kotlin can read them off any step.+ let (ascent_m, descent_m) = route_ascent_descent(&steps);++ // --- Marshal steps into OfflineRouter.RawStep[] ---+ let class = match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawStep")) {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // MUST match the descriptor at the transit call site below: one ctor, two+ // callers. The trailing two Strings are the ride's MOTIS board/alight ids;+ // the trailing `[DDD` is WS-G's per-coordinate elevation array (parallel to+ // the geometry) plus the route's cumulative ascent/descent in metres.+ let ctor = jni_sig!("(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;IIILjava/lang/String;Ljava/lang/String;[DDD)V");++ let array = match env.new_object_array(steps.len() as i32, &class, JObject::null()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ }; - // --- Marshal steps into OfflineRouter.RawStep[] ---- let class = match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawStep")) {- Ok(c) => c,+ for (i, step) in steps.iter().enumerate() {+ let name = g.road_name(step.name_off).unwrap_or_else(|| "Unknown Road".to_string());+ let jname: JObject = match env.new_string(&name) {+ Ok(s) => s.into(), Err(_) => return Ok(null), };- // MUST match the descriptor at the transit call site below: one ctor, two- // callers. The trailing two Strings are the ride's MOTIS board/alight ids;- // the trailing `[DDD` is WS-G's per-coordinate elevation array (parallel to- // the geometry) plus the route's cumulative ascent/descent in metres.- let ctor = jni_sig!("(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;IIILjava/lang/String;Ljava/lang/String;[DDD)V");+ let jgeom = match env.new_double_array(step.coords.len()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ };+ if jgeom.set_region(env, 0, &step.coords).is_err() {+ return Ok(null);+ }+ let jgeom_obj: JObject = jgeom.into(); - let array = match env.new_object_array(steps.len() as i32, &class, JObject::null()) {+ // Packed turn-lane guidance: one int per lane (dir * 2 + valid).+ let jlanes = match env.new_int_array(step.lanes.len()) { Ok(a) => a, Err(_) => return Ok(null), };+ if !step.lanes.is_empty()+ && jlanes.set_region(env, 0, &step.lanes).is_err()+ {+ return Ok(null);+ }+ let jlanes_obj: JObject = jlanes.into(); - for (i, step) in steps.iter().enumerate() {- let name = g.road_name(step.name_off).unwrap_or_else(|| "Unknown Road".to_string());- let jname: JObject = match env.new_string(&name) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jgeom = match env.new_double_array(step.coords.len()) {- Ok(a) => a,- Err(_) => return Ok(null),- };- if jgeom.set_region(env, 0, &step.coords).is_err() {- return Ok(null);- }- let jgeom_obj: JObject = jgeom.into();-- // Packed turn-lane guidance: one int per lane (dir * 2 + valid).- let jlanes = match env.new_int_array(step.lanes.len()) {- Ok(a) => a,- Err(_) => return Ok(null),- };- if !step.lanes.is_empty()- && jlanes.set_region(env, 0, &step.lanes).is_err()- {- return Ok(null);- }- let jlanes_obj: JObject = jlanes.into();-- // Per-coordinate elevation (metres), parallel to the geometry double[].- let jelev = match env.new_double_array(step.elevations.len()) {- Ok(a) => a,- Err(_) => return Ok(null),- };- if !step.elevations.is_empty()- && jelev.set_region(env, 0, &step.elevations).is_err()- {- return Ok(null);- }- let jelev_obj: JObject = jelev.into();-- let obj = match env.new_object(- &class,- &ctor,- &[- JValue::Int(step.maneuver),- JValue::Object(&jname),- JValue::Long(step.dist_mm as i64),- JValue::Long(step.time_10ms as i64),- JValue::Object(&jgeom_obj),- JValue::Double(step.speed_ratio),- // Transit-only tail. The ctor descriptor is shared with the- // RAPTOR path; the road graph has no timetable, so it fills the- // transit fields with nulls/zeros.- JValue::Bool(false),- JValue::Object(&JObject::null()),- JValue::Object(&JObject::null()),- JValue::Object(&JObject::null()),- JValue::Int(0),- JValue::Object(&jlanes_obj),- JValue::Object(&JObject::null()),- JValue::Int(0),- JValue::Int(0),- JValue::Int(0),- // No MOTIS stop ids on a road-graph step.- JValue::Object(&JObject::null()),- JValue::Object(&JObject::null()),- // WS-G elevation profile: per-coordinate elevations + route totals.- JValue::Object(&jelev_obj),- JValue::Double(ascent_m),- JValue::Double(descent_m),- ],- ) {- Ok(o) => o,- Err(_) => return Ok(null),- };- if array.set_element(env, i, &obj).is_err() {- return Ok(null);- }+ // Per-coordinate elevation (metres), parallel to the geometry double[].+ let jelev = match env.new_double_array(step.elevations.len()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ };+ if !step.elevations.is_empty()+ && jelev.set_region(env, 0, &step.elevations).is_err()+ {+ return Ok(null); }+ let jelev_obj: JObject = jelev.into();++ let obj = match env.new_object(+ &class,+ &ctor,+ &[+ JValue::Int(step.maneuver),+ JValue::Object(&jname),+ JValue::Long(step.dist_mm as i64),+ JValue::Long(step.time_10ms as i64),+ JValue::Object(&jgeom_obj),+ JValue::Double(step.speed_ratio),+ // Transit-only tail. The ctor descriptor is shared with the+ // RAPTOR path; the road graph has no timetable, so it fills the+ // transit fields with nulls/zeros.+ JValue::Bool(false),+ JValue::Object(&JObject::null()),+ JValue::Object(&JObject::null()),+ JValue::Object(&JObject::null()),+ JValue::Int(0),+ JValue::Object(&jlanes_obj),+ JValue::Object(&JObject::null()),+ JValue::Int(0),+ JValue::Int(0),+ JValue::Int(0),+ // No MOTIS stop ids on a road-graph step.+ JValue::Object(&JObject::null()),+ JValue::Object(&JObject::null()),+ // WS-G elevation profile: per-coordinate elevations + route totals.+ JValue::Object(&jelev_obj),+ JValue::Double(ascent_m),+ JValue::Double(descent_m),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return Ok(null),+ };+ if array.set_element(env, i, &obj).is_err() {+ return Ok(null);+ }+ } - Ok(array.into_raw())- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ Ok(array.into_raw())+} } // --------------------------------------------------------------------------- // Walk-leg road snapper (shared with the transit planner)
maps/src/main/rust/src/jni/traffic_jni.rs
diff --git a/maps/src/main/rust/src/jni/traffic_jni.rs b/maps/src/main/rust/src/jni/traffic_jni.rsindex 8e1142f09e..05c91f9967 100644--- a/maps/src/main/rust/src/jni/traffic_jni.rs+++ b/maps/src/main/rust/src/jni/traffic_jni.rs@@ -9,6 +9,7 @@ use std::sync::{Mutex, OnceLock}; use jni::objects::{JByteArray, JLongArray, JObject}; use jni::sys::{jbyteArray, jdouble, jdoubleArray, jint}; use jni::EnvUnowned;+use jni_bridge::jni_fn; use super::routes::{ensure_traffic_loaded, graph}; @@ -27,78 +28,68 @@ pub(crate) fn traffic_meta() -> &'static Mutex<TrafficMeta> { // JNI: updateTrafficNative // --------------------------------------------------------------------------- -#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_updateTrafficNative<'local>(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- edge_ids: JLongArray<'local>,- speeds: JByteArray<'local>,- packed_square: jint,-) {- env.with_env(|env| -> jni::errors::Result<()> {- let g = match graph() {- Some(g) => g,- None => return Ok(()),- };-- let len = edge_ids.len(env).unwrap_or(0);- if len == 0 {- // Still record an (empty) square so the overlay clears it.- let mut meta = traffic_meta().lock().unwrap();- meta.by_square.entry(packed_square).or_default().clear();- return Ok(());- }- let mut ids = vec![0i64; len];- if edge_ids.get_region(env, 0, &mut ids).is_err() {- return Ok(());- }- let mut sp = vec![0i8; len];- if speeds.get_region(env, 0, &mut sp).is_err() {- return Ok(());- }-- // The walk runs with no lock held. It recovers each edge's source node (a binary- // search over the planet's node array) and reads three records out of the mapped- // graph, which on a phone means cold flash pages and zstd blocks — while- // `traffic_meta` is the lock the camera-settle prefetch (`ensureTrafficLoadedNative`)- // takes first. Holding it across the walk let the caller wait out the whole square.- // Now both locks are held only for the swap-in below.- let mut updates: Vec<(u64, u8)> = Vec::with_capacity(len);- let mut fresh: Vec<f64> = Vec::with_capacity(len * 5);- for i in 0..len {- let edge_id = ids[i] as u64;- let speed = sp[i] as u8;- if edge_id < g.edge_count && speed < 255 {- updates.push((edge_id, speed));- // The only entry point with no source node in hand: the id comes- // from Kotlin. Recovered first, because reading the record needs it.- let source = g.find_node_idx_for_edge(edge_id);- let edge = g.edge(source, edge_id);- let node_u = g.node(source);- if edge.target < g.node_count {- let node_v = g.node(edge.target);- let ratio = if edge.speed_limit > 0 {- speed as f64 / edge.speed_limit as f64- } else {- 1.0- };- fresh.push(node_u.lat_e7 as f64 * 1e-7);- fresh.push(node_u.lon_e7 as f64 * 1e-7);- fresh.push(node_v.lat_e7 as f64 * 1e-7);- fresh.push(node_v.lon_e7 as f64 * 1e-7);- fresh.push(ratio);- }+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_updateTrafficNative; (_thiz: JObject<'l>, edge_ids: JLongArray<'l>, speeds: JByteArray<'l>, packed_square: jint) |env| {+ let g = match graph() {+ Some(g) => g,+ None => return Ok(()),+ };++ let len = edge_ids.len(env).unwrap_or(0);+ if len == 0 {+ // Still record an (empty) square so the overlay clears it.+ let mut meta = traffic_meta().lock().unwrap();+ meta.by_square.entry(packed_square).or_default().clear();+ return Ok(());+ }+ let mut ids = vec![0i64; len];+ if edge_ids.get_region(env, 0, &mut ids).is_err() {+ return Ok(());+ }+ let mut sp = vec![0i8; len];+ if speeds.get_region(env, 0, &mut sp).is_err() {+ return Ok(());+ }++ // The walk runs with no lock held. It recovers each edge's source node (a binary+ // search over the planet's node array) and reads three records out of the mapped+ // graph, which on a phone means cold flash pages and zstd blocks — while+ // `traffic_meta` is the lock the camera-settle prefetch (`ensureTrafficLoadedNative`)+ // takes first. Holding it across the walk let the caller wait out the whole square.+ // Now both locks are held only for the swap-in below.+ let mut updates: Vec<(u64, u8)> = Vec::with_capacity(len);+ let mut fresh: Vec<f64> = Vec::with_capacity(len * 5);+ for i in 0..len {+ let edge_id = ids[i] as u64;+ let speed = sp[i] as u8;+ if edge_id < g.edge_count && speed < 255 {+ updates.push((edge_id, speed));+ // The only entry point with no source node in hand: the id comes+ // from Kotlin. Recovered first, because reading the record needs it.+ let source = g.find_node_idx_for_edge(edge_id);+ let edge = g.edge(source, edge_id);+ let node_u = g.node(source);+ if edge.target < g.node_count {+ let node_v = g.node(edge.target);+ let ratio = if edge.speed_limit > 0 {+ speed as f64 / edge.speed_limit as f64+ } else {+ 1.0+ };+ fresh.push(node_u.lat_e7 as f64 * 1e-7);+ fresh.push(node_u.lon_e7 as f64 * 1e-7);+ fresh.push(node_v.lat_e7 as f64 * 1e-7);+ fresh.push(node_v.lon_e7 as f64 * 1e-7);+ fresh.push(ratio); } }- {- let mut speeds_w = super::routes::traffic_speeds().write().unwrap();- speeds_w.extend(updates);- }- traffic_meta().lock().unwrap().by_square.insert(packed_square, fresh);- Ok(())- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ }+ {+ let mut speeds_w = super::routes::traffic_speeds().write().unwrap();+ speeds_w.extend(updates);+ }+ traffic_meta().lock().unwrap().by_square.insert(packed_square, fresh);+ Ok(())+} } // --------------------------------------------------------------------------- // JNI: notifyTrafficFetchFinishedNative (no-op, kept for ABI compatibility)@@ -118,106 +109,75 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_notifyTraffi // JNI: getTrafficSegmentsNative // --------------------------------------------------------------------------- -#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficSegmentsNative<- 'local,->(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,-) -> jdoubleArray {- env.with_env(|env| -> jni::errors::Result<jdoubleArray> {- let null = std::ptr::null_mut();- let meta = traffic_meta().lock().unwrap();+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficSegmentsNative -> jdoubleArray; (_thiz: JObject<'l>) |env| {+ let null = std::ptr::null_mut();+ let meta = traffic_meta().lock().unwrap(); - let mut flattened: Vec<f64> = Vec::new();- for segments in meta.by_square.values() {- flattened.extend_from_slice(segments);- if flattened.len() > 50000 {- break;- }- }+ let mut flattened: Vec<f64> = Vec::new();+ for segments in meta.by_square.values() {+ flattened.extend_from_slice(segments); if flattened.len() > 50000 {- flattened.truncate(50000);+ break; }-- match env.new_double_array(flattened.len()) {- Ok(arr) => {- if !flattened.is_empty() && arr.set_region(env, 0, &flattened).is_err() {- return Ok(null);- }- Ok(arr.into_raw())+ }+ if flattened.len() > 50000 {+ flattened.truncate(50000);+ }++ match env.new_double_array(flattened.len()) {+ Ok(arr) => {+ if !flattened.is_empty() && arr.set_region(env, 0, &flattened).is_err() {+ return Ok(null); }- Err(_) => Ok(null),+ Ok(arr.into_raw()) }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ Err(_) => Ok(null),+ }+} } // --------------------------------------------------------------------------- // JNI: getTrafficTileNative // --------------------------------------------------------------------------- -#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficTileNative<'local>(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- z: jint,- x: jint,- y: jint,-) -> jbyteArray {- env.with_env(|env| -> jni::errors::Result<jbyteArray> {- let null = std::ptr::null_mut();- let tile = {- let meta = traffic_meta().lock().unwrap();- crate::mvt::generate_traffic_tile(&meta.by_square, z, x, y)- };- let bytes = match tile {- Some(b) => b,- None => return Ok(null),- };-- // set_byte_array_region takes &[i8]; reinterpret the gzip bytes.- let signed: &[i8] =- unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const i8, bytes.len()) };- match env.new_byte_array(bytes.len()) {- Ok(arr) => {- if arr.set_region(env, 0, signed).is_err() {- return Ok(null);- }- Ok(arr.into_raw())+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficTileNative -> jbyteArray; (_thiz: JObject<'l>, z: jint, x: jint, y: jint) |env| {+ let null = std::ptr::null_mut();+ let tile = {+ let meta = traffic_meta().lock().unwrap();+ crate::mvt::generate_traffic_tile(&meta.by_square, z, x, y)+ };+ let bytes = match tile {+ Some(b) => b,+ None => return Ok(null),+ };++ // set_byte_array_region takes &[i8]; reinterpret the gzip bytes.+ let signed: &[i8] =+ unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const i8, bytes.len()) };+ match env.new_byte_array(bytes.len()) {+ Ok(arr) => {+ if arr.set_region(env, 0, signed).is_err() {+ return Ok(null); }- Err(_) => Ok(null),+ Ok(arr.into_raw()) }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ Err(_) => Ok(null),+ }+} } // --------------------------------------------------------------------------- // JNI: ensureTrafficLoadedNative // --------------------------------------------------------------------------- -#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_ensureTrafficLoadedNative<- 'local,->(- mut env: EnvUnowned<'local>,- thiz: JObject<'local>,- lat: jdouble,- lon: jdouble,- force_async: bool,-) {- env.with_env(|env| -> jni::errors::Result<()> {- if graph().is_none() {- return Ok(());- }- ensure_traffic_loaded(- &mut *env,- &thiz,- (lat * 1e7) as i32,- (lon * 1e7) as i32,- force_async,- );- Ok(())- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_ensureTrafficLoadedNative; (thiz: JObject<'l>, lat: jdouble, lon: jdouble, force_async: bool) |env| {+ if graph().is_none() {+ return Ok(());+ }+ ensure_traffic_loaded(+ &mut *env,+ &thiz,+ (lat * 1e7) as i32,+ (lon * 1e7) as i32,+ force_async,+ );+ Ok(())+} }
maps/src/main/rust/src/jni/transit_jni/departures.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/departures.rs b/maps/src/main/rust/src/jni/transit_jni/departures.rsindex 1fc3378f49..df8a76e699 100644--- a/maps/src/main/rust/src/jni/transit_jni/departures.rs+++ b/maps/src/main/rust/src/jni/transit_jni/departures.rs@@ -4,7 +4,8 @@ use jni::objects::{JDoubleArray, JIntArray, JObject, JObjectArray, JString, JValue}; use jni::sys::{jdouble, jint, jobjectArray};-use jni::{jni_sig, jni_str, EnvUnowned};+use jni::{jni_sig, jni_str};+use jni_bridge::jni_fn; use super::cache::transit_index; use super::overlay::read_delay_entries;@@ -13,135 +14,113 @@ use super::overlay::read_delay_entries; // 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: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- lat: jdouble,- lon: jdouble,- dep_secs: jint,- weekday: jint,- date: jint,- prev_weekday: jint,- prev_date: jint,- overlay_coords: JDoubleArray<'local>,- overlay_routes: JObjectArray<'local>,- overlay_times: JIntArray<'local>,- max: jint,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };+// 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.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getStopDeparturesNative -> jobjectArray; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, lat: jdouble, lon: jdouble, dep_secs: jint, weekday: jint, date: jint, prev_weekday: jint, prev_date: jint, overlay_coords: JDoubleArray<'l>, overlay_routes: JObjectArray<'l>, overlay_times: JIntArray<'l>, max: jint) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ }; - let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };- if !index.covers(lat, lon) {- return Ok(null);- }+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ };+ if !index.covers(lat, lon) {+ return Ok(null);+ } - let entries =- read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);- let overlay = if entries.is_empty() {- None- } else {- Some(crate::transit::DelayOverlay::build(&index, &entries))- };+ let entries =+ read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);+ let overlay = if entries.is_empty() {+ None+ } else {+ Some(crate::transit::DelayOverlay::build(&index, &entries))+ }; - let deps = crate::transit::stop_departures(- &index,- lat,- lon,- dep_secs.max(0) as u32,- crate::transit::Schedule {- day: crate::transit::QueryDay {- weekday: weekday.max(0) as u32,- date: date.max(0) as u32,- prev_weekday: prev_weekday.max(0) as u32,- prev_date: prev_date.max(0) as u32,- },- overlay: overlay.as_ref(),+ let deps = crate::transit::stop_departures(+ &index,+ lat,+ lon,+ dep_secs.max(0) as u32,+ crate::transit::Schedule {+ day: crate::transit::QueryDay {+ weekday: weekday.max(0) as u32,+ date: date.max(0) as u32,+ prev_weekday: prev_weekday.max(0) as u32,+ prev_date: prev_date.max(0) as u32, },- max.max(0) as usize,- );+ overlay: overlay.as_ref(),+ },+ max.max(0) as usize,+ );++ let class = match env+ .find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawDeparture"))+ {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // MUST match the RawDeparture ctor: 4 strings, 4 ints, 2 bools, then the+ // packed trip id (J) LAST so older descriptors never renumber.+ let ctor = jni_sig!(+ "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIZZJ)V"+ );+ let array = match env.new_object_array(deps.len() as i32, &class, JObject::null()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ }; - let class = match env- .find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawDeparture"))- {- Ok(c) => c,+ for (i, d) in deps.iter().enumerate() {+ let jroute: JObject = match env.new_string(&d.route_name) {+ Ok(s) => s.into(), Err(_) => return Ok(null), };- // MUST match the RawDeparture ctor: 4 strings, 4 ints, 2 bools, then the- // packed trip id (J) LAST so older descriptors never renumber.- let ctor = jni_sig!(- "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IIIIZZJ)V"- );- let array = match env.new_object_array(deps.len() as i32, &class, JObject::null()) {- Ok(a) => a,+ let jheadsign: JObject = match env.new_string(&d.headsign) {+ Ok(s) => s.into(), Err(_) => return Ok(null), };-- for (i, d) in deps.iter().enumerate() {- let jroute: JObject = match env.new_string(&d.route_name) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jheadsign: JObject = match env.new_string(&d.headsign) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jfeed: JObject = match env.new_string(&d.feed) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jcode: JObject = match env.new_string(&d.stop_code) {- Ok(s) => s.into(),- Err(_) => return Ok(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),- JValue::Int(d.delay_secs),- JValue::Bool(d.cancelled),- JValue::Bool(d.real_time),- JValue::Long(d.trip_id),- ],- ) {- Ok(o) => o,- Err(_) => return Ok(null),- };- if array.set_element(env, i, &obj).is_err() {- return Ok(null);- }+ let jfeed: JObject = match env.new_string(&d.feed) {+ Ok(s) => s.into(),+ Err(_) => return Ok(null),+ };+ let jcode: JObject = match env.new_string(&d.stop_code) {+ Ok(s) => s.into(),+ Err(_) => return Ok(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),+ JValue::Int(d.delay_secs),+ JValue::Bool(d.cancelled),+ JValue::Bool(d.real_time),+ JValue::Long(d.trip_id),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return Ok(null),+ };+ if array.set_element(env, i, &obj).is_err() {+ return Ok(null); }+ } - Ok(array.into_raw())- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ Ok(array.into_raw())+} }
maps/src/main/rust/src/jni/transit_jni/itinerary.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/itinerary.rs b/maps/src/main/rust/src/jni/transit_jni/itinerary.rsindex 59d82080c4..3892f8c20b 100644--- a/maps/src/main/rust/src/jni/transit_jni/itinerary.rs+++ b/maps/src/main/rust/src/jni/transit_jni/itinerary.rs@@ -5,7 +5,8 @@ use jni::objects::{JDoubleArray, JIntArray, JObject, JObjectArray, JString, JValue}; use jni::sys::{jint, jlong, jobject};-use jni::{jni_sig, jni_str, EnvUnowned};+use jni::{jni_sig, jni_str};+use jni_bridge::jni_fn; use super::cache::transit_index; use super::overlay::read_delay_entries;@@ -14,149 +15,130 @@ use super::overlay::read_delay_entries; // JNI: getTripItineraryNative (a trip's full stop list + times) // --------------------------------------------------------------------------- -/// The itinerary of the trip `vehicle_id` names: header-/// `(route_name, headsign, color, route_type, feed, cancelled)` plus one-/// `RawTripStop` per stop `(name, lat, lon, arr_secs, dep_secs, motis_id)`.-/// Times are seconds since feed-local midnight in the query-day frame with-/// the realtime overlay applied — the same frame as departure-board times,-/// so Kotlin converts them identically. Returns null when the id does not-/// resolve or the trip does not run on the query service day.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getTripItineraryNative<- 'local,->(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- vehicle_id: jlong,- weekday: jint,- date: jint,- prev_weekday: jint,- prev_date: jint,- overlay_coords: JDoubleArray<'local>,- overlay_routes: JObjectArray<'local>,- overlay_times: JIntArray<'local>,-) -> jobject {- env.with_env(|env| -> jni::errors::Result<jobject> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };+// The itinerary of the trip `vehicle_id` names: header+// `(route_name, headsign, color, route_type, feed, cancelled)` plus one+// `RawTripStop` per stop `(name, lat, lon, arr_secs, dep_secs, motis_id)`.+// Times are seconds since feed-local midnight in the query-day frame with+// the realtime overlay applied — the same frame as departure-board times,+// so Kotlin converts them identically. Returns null when the id does not+// resolve or the trip does not run on the query service day.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getTripItineraryNative -> jobject; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, vehicle_id: jlong, weekday: jint, date: jint, prev_weekday: jint, prev_date: jint, overlay_coords: JDoubleArray<'l>, overlay_routes: JObjectArray<'l>, overlay_times: JIntArray<'l>) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ }; - let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ }; - let entries =- read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);- let overlay = if entries.is_empty() {- None- } else {- Some(crate::transit::DelayOverlay::build(&index, &entries))- };+ let entries =+ read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);+ let overlay = if entries.is_empty() {+ None+ } else {+ Some(crate::transit::DelayOverlay::build(&index, &entries))+ }; - let itin = match crate::transit::trip_itinerary(- &index,- vehicle_id,- crate::transit::Schedule {- day: crate::transit::QueryDay {- weekday: weekday.max(0) as u32,- date: date.max(0) as u32,- prev_weekday: prev_weekday.max(0) as u32,- prev_date: prev_date.max(0) as u32,- },- overlay: overlay.as_ref(),+ let itin = match crate::transit::trip_itinerary(+ &index,+ vehicle_id,+ crate::transit::Schedule {+ day: crate::transit::QueryDay {+ weekday: weekday.max(0) as u32,+ date: date.max(0) as u32,+ prev_weekday: prev_weekday.max(0) as u32,+ prev_date: prev_date.max(0) as u32, },- ) {- Some(t) => t,- None => return Ok(null),- };+ overlay: overlay.as_ref(),+ },+ ) {+ Some(t) => t,+ None => return Ok(null),+ }; - let stop_class = match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawTripStop")) {- Ok(c) => c,+ let stop_class = match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawTripStop")) {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // MUST match the RawTripStop ctor: name, lat, lon (D), arr, dep (I), motisId, cancelled (Z).+ let stop_ctor = jni_sig!("(Ljava/lang/String;DDIILjava/lang/String;Z)V");+ let stop_array = match env.new_object_array(itin.stops.len() as i32, &stop_class, JObject::null())+ {+ Ok(a) => a,+ Err(_) => return Ok(null),+ };+ for (i, s) in itin.stops.iter().enumerate() {+ let jname: JObject = match env.new_string(&s.name) {+ Ok(x) => x.into(), Err(_) => return Ok(null), };- // MUST match the RawTripStop ctor: name, lat, lon (D), arr, dep (I), motisId, cancelled (Z).- let stop_ctor = jni_sig!("(Ljava/lang/String;DDIILjava/lang/String;Z)V");- let stop_array = match env.new_object_array(itin.stops.len() as i32, &stop_class, JObject::null())- {- Ok(a) => a,+ let jmotis: JObject = match env.new_string(&s.motis_id) {+ Ok(x) => x.into(), Err(_) => return Ok(null), };- for (i, s) in itin.stops.iter().enumerate() {- let jname: JObject = match env.new_string(&s.name) {- Ok(x) => x.into(),- Err(_) => return Ok(null),- };- let jmotis: JObject = match env.new_string(&s.motis_id) {- Ok(x) => x.into(),- Err(_) => return Ok(null),- };- let obj = match env.new_object(- &stop_class,- &stop_ctor,- &[- JValue::Object(&jname),- JValue::Double(s.lat),- JValue::Double(s.lon),- JValue::Int(s.arr_secs as i32),- JValue::Int(s.dep_secs as i32),- JValue::Object(&jmotis),- JValue::Bool(itin.cancelled),- ],- ) {- Ok(o) => o,- Err(_) => return Ok(null),- };- if stop_array.set_element(env, i, &obj).is_err() {- return Ok(null);- }- }-- let itin_class =- match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawTripItinerary")) {- Ok(c) => c,- Err(_) => return Ok(null),- };- // MUST match the RawTripItinerary ctor: route, headsign, color, type (I),- // feed, cancelled (Z), stops ([L...RawTripStop;).- let itin_ctor = jni_sig!("(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;Z[Lcom/vayunmathur/maps/util/OfflineRouter$RawTripStop;)V");- let jroute: JObject = match env.new_string(&itin.route_name) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jhead: JObject = match env.new_string(&itin.headsign) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jfeed: JObject = match env.new_string(&itin.feed) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jobjs: JObject = stop_array.into();- match env.new_object(- &itin_class,- itin_ctor,+ let obj = match env.new_object(+ &stop_class,+ &stop_ctor, &[- JValue::Object(&jroute),- JValue::Object(&jhead),- JValue::Int(itin.color as i32),- JValue::Int(itin.route_type as i32),- JValue::Object(&jfeed),+ JValue::Object(&jname),+ JValue::Double(s.lat),+ JValue::Double(s.lon),+ JValue::Int(s.arr_secs as i32),+ JValue::Int(s.dep_secs as i32),+ JValue::Object(&jmotis), JValue::Bool(itin.cancelled),- JValue::Object(&jobjs), ], ) {- Ok(o) => Ok(o.into_raw()),- Err(_) => Ok(null),+ Ok(o) => o,+ Err(_) => return Ok(null),+ };+ if stop_array.set_element(env, i, &obj).is_err() {+ return Ok(null); }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ }++ let itin_class =+ match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawTripItinerary")) {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // MUST match the RawTripItinerary ctor: route, headsign, color, type (I),+ // feed, cancelled (Z), stops ([L...RawTripStop;).+ let itin_ctor = jni_sig!("(Ljava/lang/String;Ljava/lang/String;IILjava/lang/String;Z[Lcom/vayunmathur/maps/util/OfflineRouter$RawTripStop;)V");+ let jroute: JObject = match env.new_string(&itin.route_name) {+ Ok(s) => s.into(),+ Err(_) => return Ok(null),+ };+ let jhead: JObject = match env.new_string(&itin.headsign) {+ Ok(s) => s.into(),+ Err(_) => return Ok(null),+ };+ let jfeed: JObject = match env.new_string(&itin.feed) {+ Ok(s) => s.into(),+ Err(_) => return Ok(null),+ };+ let jobjs: JObject = stop_array.into();+ match env.new_object(+ &itin_class,+ itin_ctor,+ &[+ JValue::Object(&jroute),+ JValue::Object(&jhead),+ JValue::Int(itin.color as i32),+ JValue::Int(itin.route_type as i32),+ JValue::Object(&jfeed),+ JValue::Bool(itin.cancelled),+ JValue::Object(&jobjs),+ ],+ ) {+ Ok(o) => Ok(o.into_raw()),+ Err(_) => Ok(null),+ }+} }
maps/src/main/rust/src/jni/transit_jni/lines.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/lines.rs b/maps/src/main/rust/src/jni/transit_jni/lines.rsindex ec42c49a8d..9f210df3ac 100644--- a/maps/src/main/rust/src/jni/transit_jni/lines.rs+++ b/maps/src/main/rust/src/jni/transit_jni/lines.rs@@ -7,7 +7,8 @@ use jni::objects::{JObject, JString, JValue}; use jni::sys::{jdouble, jobjectArray};-use jni::{jni_sig, jni_str, Env, EnvUnowned};+use jni::{jni_sig, jni_str, Env};+use jni_bridge::jni_fn; use super::cache::transit_index; @@ -61,96 +62,72 @@ fn rail_lines_to_java<'local>( // JNI: getRailLinesNative (drawable rail polylines + agency colours) // --------------------------------------------------------------------------- -/// Every rail line serving the bbox, with its agency colour and GTFS-/// `route_type`: `(name, color, route_type, feed, coords)`. `coords` is a flat-/// `[lon0, lat0, ...]` like a `RawStep` geometry. Returns an empty array (not-/// null) when the pack is absent — no lines is a valid answer — and null only-/// on a JNI failure. Bounded natively (`MAX_RAIL_LINES`).-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getRailLinesNative<'local>(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- min_lat: jdouble,- min_lon: jdouble,- max_lat: jdouble,- max_lon: jdouble,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };+// Every rail line serving the bbox, with its agency colour and GTFS+// `route_type`: `(name, color, route_type, feed, coords)`. `coords` is a flat+// `[lon0, lat0, ...]` like a `RawStep` geometry. Returns an empty array (not+// null) when the pack is absent — no lines is a valid answer — and null only+// on a JNI failure. Bounded natively (`MAX_RAIL_LINES`).+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getRailLinesNative -> jobjectArray; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, min_lat: jdouble, min_lon: jdouble, max_lat: jdouble, max_lon: jdouble) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ }; - let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ }; - // No covers() gate: a line serves the bbox when any of its stops does,- // and the bbox centre may be nowhere near a stop. The stop-based cull in- // `rail_lines` is the coverage check.- let lines = crate::transit::rail_lines(&index, min_lat, min_lon, max_lat, max_lon);-- match rail_lines_to_java(&mut *env, &lines) {- Some(a) => Ok(a),- None => Ok(null),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ // No covers() gate: a line serves the bbox when any of its stops does,+ // and the bbox centre may be nowhere near a stop. The stop-based cull in+ // `rail_lines` is the coverage check.+ let lines = crate::transit::rail_lines(&index, min_lat, min_lon, max_lat, max_lon); -/// Every line serving the stop nearest `(lat, lon)`, with its agency colour-/// and GTFS `route_type`: same `(name, color, route_type, feed, coords)` and-/// corridor slot as [`getRailLinesNative`]. Buses included — at one stop a-/// handful of bus polylines is context, not noise. Returns an empty array-/// (not null) when the pack is absent or no stop is near; null only on a JNI-/// failure. Bounded natively (`MAX_RAIL_LINES`).-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getStopLinesNative<'local>(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- lat: jdouble,- lon: jdouble,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };+ match rail_lines_to_java(&mut *env, &lines) {+ Some(a) => Ok(a),+ None => Ok(null),+ }+} } - let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };+// Every line serving the stop nearest `(lat, lon)`, with its agency colour+// and GTFS `route_type`: same `(name, color, route_type, feed, coords)` and+// corridor slot as [`getRailLinesNative`]. Buses included — at one stop a+// handful of bus polylines is context, not noise. Returns an empty array+// (not null) when the pack is absent or no stop is near; null only on a JNI+// failure. Bounded natively (`MAX_RAIL_LINES`).+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getStopLinesNative -> jobjectArray; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, lat: jdouble, lon: jdouble) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ }; - // Same nearest-stop resolution as the departure board (which the lines- // must agree with), with the pack bbox as the coverage gate.- if !index.covers(lat, lon) {- return match rail_lines_to_java(&mut *env, &[]) {- Some(a) => Ok(a),- None => Ok(null),- };- }- let lines = crate::transit::routes_for_stop(&index, lat, lon);+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ }; - match rail_lines_to_java(&mut *env, &lines) {+ // Same nearest-stop resolution as the departure board (which the lines+ // must agree with), with the pack bbox as the coverage gate.+ if !index.covers(lat, lon) {+ return match rail_lines_to_java(&mut *env, &[]) { Some(a) => Ok(a), None => Ok(null),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ };+ }+ let lines = crate::transit::routes_for_stop(&index, lat, lon);++ match rail_lines_to_java(&mut *env, &lines) {+ Some(a) => Ok(a),+ None => Ok(null),+ }+} }
maps/src/main/rust/src/jni/transit_jni/lookups.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/lookups.rs b/maps/src/main/rust/src/jni/transit_jni/lookups.rsindex 5ca99abc0f..42bbd75d98 100644--- a/maps/src/main/rust/src/jni/transit_jni/lookups.rs+++ b/maps/src/main/rust/src/jni/transit_jni/lookups.rs@@ -4,7 +4,7 @@ use jni::objects::{JObject, JString}; use jni::sys::{jdouble, jstring};-use jni::EnvUnowned;+use jni_bridge::jni_fn; use super::cache::transit_index; @@ -12,130 +12,94 @@ use super::cache::transit_index; // JNI: hasTransitArchiveNative (does the archive carry a transit section?) // --------------------------------------------------------------------------- -/// Whether `<base_path>/basemap.mamaps` carries a transit section (kind 13).-///-/// The Kotlin discovery gate calls this before listing per-region-/// `<base>/*.transit` files: on an archive-only device there are no sidecar-/// files, so without this the gate finds nothing and every transit entry-/// point short-circuits before any JNI call. A pure presence probe — it reads-/// the archive's section directory without parsing the TRIX pack — so it is-/// cheap enough to call on every entry.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_hasTransitArchiveNative<- 'local,->(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,-) -> bool {- env.with_env(|env| -> jni::errors::Result<bool> {- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(false),- };- Ok(crate::transit::TransitIndex::has_archive_transit(&crate::graph::archive_path(&base)))- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+// Whether `<base_path>/basemap.mamaps` carries a transit section (kind 13).+//+// The Kotlin discovery gate calls this before listing per-region+// `<base>/*.transit` files: on an archive-only device there are no sidecar+// files, so without this the gate finds nothing and every transit entry+// point short-circuits before any JNI call. A pure presence probe — it reads+// the archive's section directory without parsing the TRIX pack — so it is+// cheap enough to call on every entry.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_hasTransitArchiveNative -> bool; (_thiz: JObject<'l>, base_path: JString<'l>) |env| {+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(false),+ };+ Ok(crate::transit::TransitIndex::has_archive_transit(&crate::graph::archive_path(&base)))+} } // --------------------------------------------------------------------------- // JNI: getFeedTimezoneNative (IANA tz of the feed covering a coordinate) // --------------------------------------------------------------------------- -/// IANA timezone (e.g. `America/Los_Angeles`) of the feed covering-/// `(lat, lon)` in `<base_path>/<feed>.transit`, from the v3 `FEED_TZ` section.-/// Returns null when the pack is absent/stale, doesn't cover the point, or its-/// feed had no `agency.txt` — the caller then falls back to the device zone.-/// Callers need this because the index is world-merged: every query time must be-/// expressed in the feed's local frame, not the device's.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_getFeedTimezoneNative<- 'local,->(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- lat: jdouble,- lon: jdouble,-) -> jstring {- env.with_env(|env| -> jni::errors::Result<jstring> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };- if !index.covers(lat, lon) {- return Ok(null);- }- let tz = index.timezone_at(lat, lon);- if tz.is_empty() {- return Ok(null);- }- match env.new_string(&tz) {- Ok(s) => Ok(s.into_raw()),- Err(_) => Ok(null),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+// IANA timezone (e.g. `America/Los_Angeles`) of the feed covering+// `(lat, lon)` in `<base_path>/<feed>.transit`, from the v3 `FEED_TZ` section.+// Returns null when the pack is absent/stale, doesn't cover the point, or its+// feed had no `agency.txt` — the caller then falls back to the device zone.+// Callers need this because the index is world-merged: every query time must be+// expressed in the feed's local frame, not the device's.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_getFeedTimezoneNative -> jstring; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, lat: jdouble, lon: jdouble) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ };+ if !index.covers(lat, lon) {+ return Ok(null);+ }+ let tz = index.timezone_at(lat, lon);+ if tz.is_empty() {+ return Ok(null);+ }+ match env.new_string(&tz) {+ Ok(s) => Ok(s.into_raw()),+ Err(_) => Ok(null),+ }+} } // --------------------------------------------------------------------------- // JNI: nearestStopMotisIdNative (MOTIS id of the stop nearest a coordinate) // --------------------------------------------------------------------------- -/// MOTIS/Transitous stop id (e.g. `us-ca-SF-bayarea_901201`) of the stop nearest-/// `(lat, lon)` in `<base_path>/<feed>.transit`, from the v5 `FEED_MOTIS_PREFIX` +-/// `STOP_GTFS_ID` sections. Returns null when the pack is absent, predates v5,-/// doesn't cover the point, or its feed's Transitous source name was unknown at-/// build time.-///-/// Exists because the departure board fetches its realtime overlay *before* it-/// knows which stop the board is for, so it needs to name the stop up front. A-/// local lookup, no network — which is the whole point of baking the id.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_nearestStopMotisIdNative<- 'local,->(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- lat: jdouble,- lon: jdouble,-) -> jstring {- env.with_env(|env| -> jni::errors::Result<jstring> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };- if !index.covers(lat, lon) {- return Ok(null);- }- match index.nearest_stop_motis_id(lat, lon) {- Some(id) => match env.new_string(&id) {- Ok(s) => Ok(s.into_raw()),- Err(_) => Ok(null),- },- None => Ok(null),- }- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+// MOTIS/Transitous stop id (e.g. `us-ca-SF-bayarea_901201`) of the stop nearest+// `(lat, lon)` in `<base_path>/<feed>.transit`, from the v5 `FEED_MOTIS_PREFIX` ++// `STOP_GTFS_ID` sections. Returns null when the pack is absent, predates v5,+// doesn't cover the point, or its feed's Transitous source name was unknown at+// build time.+//+// Exists because the departure board fetches its realtime overlay *before* it+// knows which stop the board is for, so it needs to name the stop up front. A+// local lookup, no network — which is the whole point of baking the id.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_nearestStopMotisIdNative -> jstring; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, lat: jdouble, lon: jdouble) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ };+ if !index.covers(lat, lon) {+ return Ok(null);+ }+ match index.nearest_stop_motis_id(lat, lon) {+ Some(id) => match env.new_string(&id) {+ Ok(s) => Ok(s.into_raw()),+ Err(_) => Ok(null),+ },+ None => Ok(null),+ }+} }
maps/src/main/rust/src/jni/transit_jni/route.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/route.rs b/maps/src/main/rust/src/jni/transit_jni/route.rsindex 2ba5701585..638440d5a1 100644--- a/maps/src/main/rust/src/jni/transit_jni/route.rs+++ b/maps/src/main/rust/src/jni/transit_jni/route.rs@@ -4,7 +4,8 @@ use jni::objects::{JDoubleArray, JIntArray, JObject, JObjectArray, JString, JValue}; use jni::sys::{jdouble, jint, jobjectArray};-use jni::{jni_sig, jni_str, Env, EnvUnowned};+use jni::{jni_sig, jni_str, Env};+use jni_bridge::jni_fn; use super::super::routes::snap_walk_legs; use super::cache::transit_index;@@ -14,213 +15,190 @@ use super::overlay::read_delay_entries; // JNI: findTransitRouteNative (offline RAPTOR over a per-region transit index) // --------------------------------------------------------------------------- -/// Plan an offline transit journey using the compact `.transit` index at-/// `<base_path>/<feed>.transit` (produced by `scripts/maps/gtfs_ingest`).-/// Returns `OfflineRouter.RawStep[]` (walk + wait + ride legs) or `null` when-/// the feed is absent, does not cover the endpoints, or no journey exists — in-/// which case the Kotlin side falls back to the P10 online Transitous planner.-///-/// The `overlay_*` arrays carry MOTIS realtime board entries so RAPTOR avoids-/// cancelled trips and plans against live times; pass empty arrays for a-/// schedule-only plan. See `transit::DelayOverlay` for why the join is a-/// fingerprint rather than a trip id.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findTransitRouteNative<- 'local,->(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- s_lat: jdouble,- s_lon: jdouble,- e_lat: jdouble,- e_lon: jdouble,- dep_secs: jint,- weekday: jint,- date: jint,- prev_weekday: jint,- prev_date: jint,- overlay_coords: JDoubleArray<'local>,- overlay_routes: JObjectArray<'local>,- overlay_times: JIntArray<'local>,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,+// Plan an offline transit journey using the compact `.transit` index at+// `<base_path>/<feed>.transit` (produced by `scripts/maps/gtfs_ingest`).+// Returns `OfflineRouter.RawStep[]` (walk + wait + ride legs) or `null` when+// the feed is absent, does not cover the endpoints, or no journey exists — in+// which case the Kotlin side falls back to the P10 online Transitous planner.+//+// The `overlay_*` arrays carry MOTIS realtime board entries so RAPTOR avoids+// cancelled trips and plans against live times; pass empty arrays for a+// schedule-only plan. See `transit::DelayOverlay` for why the join is a+// fingerprint rather than a trip id.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_findTransitRouteNative -> jobjectArray; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, s_lat: jdouble, s_lon: jdouble, e_lat: jdouble, e_lon: jdouble, dep_secs: jint, weekday: jint, date: jint, prev_weekday: jint, prev_date: jint, overlay_coords: JDoubleArray<'l>, overlay_routes: JObjectArray<'l>, overlay_times: JIntArray<'l>) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };++ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ };+ if !index.covers(s_lat, s_lon) || !index.covers(e_lat, e_lon) {+ return Ok(null);+ }++ let entries =+ read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);+ let overlay = if entries.is_empty() {+ None+ } else {+ Some(crate::transit::DelayOverlay::build(&index, &entries))+ };++ let mut legs = match crate::transit::plan(+ &index,+ s_lat,+ s_lon,+ e_lat,+ e_lon,+ dep_secs.max(0) as u32,+ crate::transit::Schedule {+ day: crate::transit::QueryDay {+ weekday: weekday.max(0) as u32,+ date: date.max(0) as u32,+ prev_weekday: prev_weekday.max(0) as u32,+ prev_date: prev_date.max(0) as u32,+ },+ overlay: overlay.as_ref(),+ },+ ) {+ Some(l) if !l.is_empty() => l,+ _ => return Ok(null),+ };+ snap_walk_legs(&mut legs);++ let class = match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawStep")) {+ Ok(c) => c,+ Err(_) => return Ok(null),+ };+ // MUST match the descriptor at the driving call site above: one ctor, two+ // callers. The trailing two Strings are the ride's MOTIS board/alight ids;+ // the trailing `[DDD` is WS-G's per-coordinate elevation array + route+ // ascent/descent, which a transit leg leaves empty/zero (no baked terrain).+ let ctor = jni_sig!("(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;IIILjava/lang/String;Ljava/lang/String;[DDD)V");+ let array = match env.new_object_array(legs.len() as i32, &class, JObject::null()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ };++ for (i, leg) in legs.iter().enumerate() {+ let jname: JObject = match env.new_string(&leg.name) {+ Ok(s) => s.into(), Err(_) => return Ok(null), };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,+ let jgeom = match env.new_double_array(leg.coords.len()) {+ Ok(a) => a, Err(_) => return Ok(null), };-- let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };- if !index.covers(s_lat, s_lon) || !index.covers(e_lat, e_lon) {+ if !leg.coords.is_empty()+ && jgeom.set_region(env, 0, &leg.coords).is_err()+ { return Ok(null); }+ let jgeom_obj: JObject = jgeom.into(); - let entries =- read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);- let overlay = if entries.is_empty() {- None+ let opt_str = |env: &mut Env<'l>, s: &str| -> JObject<'l> {+ if s.is_empty() {+ JObject::null()+ } else {+ match env.new_string(s) {+ Ok(js) => js.into(),+ Err(_) => JObject::null(),+ }+ }+ };+ let is_transit = leg.kind.is_transit();+ // A WAIT leg needs its stop name for the "wait at X" instruction, but+ // must not carry a feed or it would render as a ride in the UI.+ let has_stops = leg.kind != crate::transit::LegKind::Walk;+ let jfeed = if is_transit { opt_str(&mut *env, &leg.feed) } else { JObject::null() };+ let jcode = if has_stops { opt_str(&mut *env, &leg.from_stop) } else { JObject::null() };+ let jend = if has_stops { opt_str(&mut *env, &leg.to_stop) } else { JObject::null() };+ let jheadsign = if is_transit {+ opt_str(&mut *env, &leg.headsign)+ } else {+ JObject::null()+ };+ // Only a ride carries realtime, so only a ride carries stop ids. Empty on+ // a pre-v5 pack, which leaves the overlay with nothing to ask about.+ let jboard = if is_transit {+ opt_str(&mut *env, &leg.board_stop_motis_id)+ } else {+ JObject::null()+ };+ let jalight = if is_transit {+ opt_str(&mut *env, &leg.alight_stop_motis_id) } else {- Some(crate::transit::DelayOverlay::build(&index, &entries))+ JObject::null() }; - let mut legs = match crate::transit::plan(- &index,- s_lat,- s_lon,- e_lat,- e_lon,- dep_secs.max(0) as u32,- crate::transit::Schedule {- day: crate::transit::QueryDay {- weekday: weekday.max(0) as u32,- date: date.max(0) as u32,- prev_weekday: prev_weekday.max(0) as u32,- prev_date: prev_date.max(0) as u32,- },- overlay: overlay.as_ref(),- },- ) {- Some(l) if !l.is_empty() => l,- _ => return Ok(null),+ // Every leg's duration comes from RAPTOR's own times. A walk leg's+ // `dist_m` may have been redrawn along the road graph, which is longer+ // than the estimate the journey was planned on, so deriving the duration+ // from it would contradict the departure the plan was built around.+ let duration_10ms: i64 = (leg.arr_secs.saturating_sub(leg.dep_secs) as i64) * 100;+ let dist_mm: i64 = (leg.dist_m * 1000.0) as i64;+ // Ordinals mirror RouteService.API.Maneuver.+ let maneuver: i32 = match leg.kind {+ crate::transit::LegKind::Walk => 0, // MANEUVER_UNSPECIFIED+ crate::transit::LegKind::Wait => 21, // WAIT+ crate::transit::LegKind::Ride => 22, // RIDE };- snap_walk_legs(&mut legs); - let class = match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawStep")) {- Ok(c) => c,+ let jlanes = match env.new_int_array(0) {+ Ok(a) => a, Err(_) => return Ok(null), };- // MUST match the descriptor at the driving call site above: one ctor, two- // callers. The trailing two Strings are the ride's MOTIS board/alight ids;- // the trailing `[DDD` is WS-G's per-coordinate elevation array + route- // ascent/descent, which a transit leg leaves empty/zero (no baked terrain).- let ctor = jni_sig!("(ILjava/lang/String;JJ[DDZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I[ILjava/lang/String;IIILjava/lang/String;Ljava/lang/String;[DDD)V");- let array = match env.new_object_array(legs.len() as i32, &class, JObject::null()) {+ let jlanes_obj: JObject = jlanes.into();++ // A transit leg carries no baked terrain: an empty elevation array and zero ascent/descent.+ let jelev = match env.new_double_array(0) { Ok(a) => a, Err(_) => return Ok(null), };+ let jelev_obj: JObject = jelev.into(); - for (i, leg) in legs.iter().enumerate() {- let jname: JObject = match env.new_string(&leg.name) {- Ok(s) => s.into(),- Err(_) => return Ok(null),- };- let jgeom = match env.new_double_array(leg.coords.len()) {- Ok(a) => a,- Err(_) => return Ok(null),- };- if !leg.coords.is_empty()- && jgeom.set_region(env, 0, &leg.coords).is_err()- {- return Ok(null);- }- let jgeom_obj: JObject = jgeom.into();-- let opt_str = |env: &mut Env<'local>, s: &str| -> JObject<'local> {- if s.is_empty() {- JObject::null()- } else {- match env.new_string(s) {- Ok(js) => js.into(),- Err(_) => JObject::null(),- }- }- };- let is_transit = leg.kind.is_transit();- // A WAIT leg needs its stop name for the "wait at X" instruction, but- // must not carry a feed or it would render as a ride in the UI.- let has_stops = leg.kind != crate::transit::LegKind::Walk;- let jfeed = if is_transit { opt_str(&mut *env, &leg.feed) } else { JObject::null() };- let jcode = if has_stops { opt_str(&mut *env, &leg.from_stop) } else { JObject::null() };- let jend = if has_stops { opt_str(&mut *env, &leg.to_stop) } else { JObject::null() };- let jheadsign = if is_transit {- opt_str(&mut *env, &leg.headsign)- } else {- JObject::null()- };- // Only a ride carries realtime, so only a ride carries stop ids. Empty on- // a pre-v5 pack, which leaves the overlay with nothing to ask about.- let jboard = if is_transit {- opt_str(&mut *env, &leg.board_stop_motis_id)- } else {- JObject::null()- };- let jalight = if is_transit {- opt_str(&mut *env, &leg.alight_stop_motis_id)- } else {- JObject::null()- };-- // Every leg's duration comes from RAPTOR's own times. A walk leg's- // `dist_m` may have been redrawn along the road graph, which is longer- // than the estimate the journey was planned on, so deriving the duration- // from it would contradict the departure the plan was built around.- let duration_10ms: i64 = (leg.arr_secs.saturating_sub(leg.dep_secs) as i64) * 100;- let dist_mm: i64 = (leg.dist_m * 1000.0) as i64;- // Ordinals mirror RouteService.API.Maneuver.- let maneuver: i32 = match leg.kind {- crate::transit::LegKind::Walk => 0, // MANEUVER_UNSPECIFIED- crate::transit::LegKind::Wait => 21, // WAIT- crate::transit::LegKind::Ride => 22, // RIDE- };-- let jlanes = match env.new_int_array(0) {- Ok(a) => a,- Err(_) => return Ok(null),- };- let jlanes_obj: JObject = jlanes.into();-- // A transit leg carries no baked terrain: an empty elevation array and zero ascent/descent.- let jelev = match env.new_double_array(0) {- Ok(a) => a,- Err(_) => return Ok(null),- };- let jelev_obj: JObject = jelev.into();-- let obj = match env.new_object(- &class,- &ctor,- &[- JValue::Int(maneuver),- JValue::Object(&jname),- JValue::Long(dist_mm),- JValue::Long(duration_10ms),- JValue::Object(&jgeom_obj),- JValue::Double(1.0),- JValue::Bool(is_transit),- JValue::Object(&jfeed),- JValue::Object(&jcode),- JValue::Object(&jend),- JValue::Int(leg.stop_count),- JValue::Object(&jlanes_obj),- JValue::Object(&jheadsign),- JValue::Int(leg.route_color as i32),- JValue::Int(leg.dep_secs as i32),- JValue::Int(leg.arr_secs as i32),- JValue::Object(&jboard),- JValue::Object(&jalight),- JValue::Object(&jelev_obj),- JValue::Double(0.0),- JValue::Double(0.0),- ],- ) {- Ok(o) => o,- Err(_) => return Ok(null),- };- if array.set_element(env, i, &obj).is_err() {- return Ok(null);- }+ let obj = match env.new_object(+ &class,+ &ctor,+ &[+ JValue::Int(maneuver),+ JValue::Object(&jname),+ JValue::Long(dist_mm),+ JValue::Long(duration_10ms),+ JValue::Object(&jgeom_obj),+ JValue::Double(1.0),+ JValue::Bool(is_transit),+ JValue::Object(&jfeed),+ JValue::Object(&jcode),+ JValue::Object(&jend),+ JValue::Int(leg.stop_count),+ JValue::Object(&jlanes_obj),+ JValue::Object(&jheadsign),+ JValue::Int(leg.route_color as i32),+ JValue::Int(leg.dep_secs as i32),+ JValue::Int(leg.arr_secs as i32),+ JValue::Object(&jboard),+ JValue::Object(&jalight),+ JValue::Object(&jelev_obj),+ JValue::Double(0.0),+ JValue::Double(0.0),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return Ok(null),+ };+ if array.set_element(env, i, &obj).is_err() {+ return Ok(null); }+ } - Ok(array.into_raw())- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ Ok(array.into_raw())+} }
maps/src/main/rust/src/jni/transit_jni/vehicles.rs
diff --git a/maps/src/main/rust/src/jni/transit_jni/vehicles.rs b/maps/src/main/rust/src/jni/transit_jni/vehicles.rsindex 5bbdcb4886..2c5ec482be 100644--- a/maps/src/main/rust/src/jni/transit_jni/vehicles.rs+++ b/maps/src/main/rust/src/jni/transit_jni/vehicles.rs@@ -4,7 +4,8 @@ use jni::objects::{JDoubleArray, JIntArray, JObject, JObjectArray, JString, JValue}; use jni::sys::{jdouble, jint, jobjectArray};-use jni::{jni_sig, jni_str, EnvUnowned};+use jni::{jni_sig, jni_str};+use jni_bridge::jni_fn; use super::cache::transit_index; use super::overlay::read_delay_entries;@@ -13,113 +14,92 @@ use super::overlay::read_delay_entries; // JNI: activeVehiclesNative (simulated in-service vehicle positions) // --------------------------------------------------------------------------- -/// Simulated moving transit vehicles for the visible bbox (WS-F): every trip in-/// `<base_path>/<feed>.transit` that is in service at `now_secs` (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.-///-/// `weekday`/`date`/`prev_*` are the query service days (as in-/// `findTransitRouteNative`, so a `>24:00:00` overnight trip is placed). The-/// `overlay_*` arrays carry MOTIS realtime so a delayed trip is drawn at its live-/// position and a cancelled one is suppressed; pass empty arrays for a-/// schedule-only simulation. Returns `OfflineRouter.RawVehicle[]` (possibly-/// empty), or `null` when the feed is absent/malformed.-#[no_mangle]-pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_activeVehiclesNative<'local>(- mut env: EnvUnowned<'local>,- _thiz: JObject<'local>,- base_path: JString<'local>,- feed: JString<'local>,- now_secs: jint,- weekday: jint,- date: jint,- prev_weekday: jint,- prev_date: jint,- overlay_coords: JDoubleArray<'local>,- overlay_routes: JObjectArray<'local>,- overlay_times: JIntArray<'local>,- min_lat: jdouble,- min_lon: jdouble,- max_lat: jdouble,- max_lon: jdouble,-) -> jobjectArray {- env.with_env(|env| -> jni::errors::Result<jobjectArray> {- let null = std::ptr::null_mut();- let base: String = match base_path.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };- let feed_name: String = match feed.try_to_string(env) {- Ok(s) => s,- Err(_) => return Ok(null),- };+// Simulated moving transit vehicles for the visible bbox (WS-F): every trip in+// `<base_path>/<feed>.transit` that is in service at `now_secs` (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.+//+// `weekday`/`date`/`prev_*` are the query service days (as in+// `findTransitRouteNative`, so a `>24:00:00` overnight trip is placed). The+// `overlay_*` arrays carry MOTIS realtime so a delayed trip is drawn at its live+// position and a cancelled one is suppressed; pass empty arrays for a+// schedule-only simulation. Returns `OfflineRouter.RawVehicle[]` (possibly+// empty), or `null` when the feed is absent/malformed.+jni_fn! { Java_com_vayunmathur_maps_util_OfflineRouter_activeVehiclesNative -> jobjectArray; (_thiz: JObject<'l>, base_path: JString<'l>, feed: JString<'l>, now_secs: jint, weekday: jint, date: jint, prev_weekday: jint, prev_date: jint, overlay_coords: JDoubleArray<'l>, overlay_routes: JObjectArray<'l>, overlay_times: JIntArray<'l>, min_lat: jdouble, min_lon: jdouble, max_lat: jdouble, max_lon: jdouble) |env| {+ let null = std::ptr::null_mut();+ let base: String = match base_path.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ };+ let feed_name: String = match feed.try_to_string(env) {+ Ok(s) => s,+ Err(_) => return Ok(null),+ }; - let index = match transit_index(&base, &feed_name) {- Some(i) => i,- None => return Ok(null),- };+ let index = match transit_index(&base, &feed_name) {+ Some(i) => i,+ None => return Ok(null),+ }; - let entries =- read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);- let overlay = if entries.is_empty() {- None- } else {- Some(crate::transit::DelayOverlay::build(&index, &entries))- };+ let entries =+ read_delay_entries(&mut *env, &overlay_coords, &overlay_routes, &overlay_times);+ let overlay = if entries.is_empty() {+ None+ } else {+ Some(crate::transit::DelayOverlay::build(&index, &entries))+ }; - let vehicles = crate::transit::active_vehicles(- &index,- now_secs.max(0) as u32,- crate::transit::Schedule {- day: crate::transit::QueryDay {- weekday: weekday.max(0) as u32,- date: date.max(0) as u32,- prev_weekday: prev_weekday.max(0) as u32,- prev_date: prev_date.max(0) as u32,- },- overlay: overlay.as_ref(),+ let vehicles = crate::transit::active_vehicles(+ &index,+ now_secs.max(0) as u32,+ crate::transit::Schedule {+ day: crate::transit::QueryDay {+ weekday: weekday.max(0) as u32,+ date: date.max(0) as u32,+ prev_weekday: prev_weekday.max(0) as u32,+ prev_date: prev_date.max(0) as u32, },- min_lat,- min_lon,- max_lat,- max_lon,- );+ overlay: overlay.as_ref(),+ },+ min_lat,+ min_lon,+ max_lat,+ max_lon,+ ); - let class =- match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawVehicle")) {- Ok(c) => c,- Err(_) => return Ok(null),- };- // MUST match the RawVehicle ctor: lon, lat, bearing (D), colour, mode (I), id (J).- let ctor = jni_sig!("(DDDIIJ)V");- let array = match env.new_object_array(vehicles.len() as i32, &class, JObject::null()) {- Ok(a) => a,+ let class =+ match env.find_class(jni_str!("com/vayunmathur/maps/util/OfflineRouter$RawVehicle")) {+ Ok(c) => c, Err(_) => return Ok(null), };+ // MUST match the RawVehicle ctor: lon, lat, bearing (D), colour, mode (I), id (J).+ let ctor = jni_sig!("(DDDIIJ)V");+ let array = match env.new_object_array(vehicles.len() as i32, &class, JObject::null()) {+ Ok(a) => a,+ Err(_) => return Ok(null),+ }; - for (i, v) in vehicles.iter().enumerate() {- let obj = match env.new_object(- &class,- &ctor,- &[- JValue::Double(v.lon),- JValue::Double(v.lat),- JValue::Double(v.bearing),- JValue::Int(v.route_color as i32),- JValue::Int(v.route_type as i32),- JValue::Long(v.id),- ],- ) {- Ok(o) => o,- Err(_) => return Ok(null),- };- if array.set_element(env, i, &obj).is_err() {- return Ok(null);- }+ for (i, v) in vehicles.iter().enumerate() {+ let obj = match env.new_object(+ &class,+ &ctor,+ &[+ JValue::Double(v.lon),+ JValue::Double(v.lat),+ JValue::Double(v.bearing),+ JValue::Int(v.route_color as i32),+ JValue::Int(v.route_type as i32),+ JValue::Long(v.id),+ ],+ ) {+ Ok(o) => o,+ Err(_) => return Ok(null),+ };+ if array.set_element(env, i, &obj).is_err() {+ return Ok(null); }+ } - Ok(array.into_raw())- })- .resolve::<jni::errors::LogErrorAndDefault>()-}+ Ok(array.into_raw())+} }