Modern Apps git

← Modern-Apps.git

maps: fix crash, leak, security, and threading bugs across the app

Commit
19888a0702c90bb4fe832c595970421abf31513d
Author
Vayun Mathur <[email protected]>
When
2026-05-30 02:24 UTC (6 months ago)
Parents
555058a

Diff

library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt
diff --git a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.ktindex a25ce0ac3b..82ba413330 100644--- a/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt+++ b/library/network/src/main/java/com/vayunmathur/library/network/NetworkClient.kt@@ -15,6 +15,8 @@ import io.ktor.client.statement.bodyAsChannel import io.ktor.client.statement.bodyAsText import io.ktor.client.statement.request import io.ktor.http.HttpMethod+import io.ktor.http.contentLength+import io.ktor.http.isSuccess import io.ktor.serialization.kotlinx.json.json import io.ktor.utils.io.readAvailable import kotlinx.serialization.json.Json@@ -140,11 +142,34 @@ object NetworkClient {         headers: Map<String, *> = emptyMap<String, Any>(),         body: Any? = null     ): T {-        return client.request(url) {+        val response = client.request(url) {             this.method = HttpMethod.parse(method)             applyHeaders(headers)             body?.let { setBody(it) }-        }.body()+        }+        // Calling .body<T>() on a 204 No Content / 304 / empty-body response+        // throws Ktor's NoTransformationFoundException, which callers usually+        // catch and silently treat as "the call failed" — but it actually+        // means the server successfully responded with no payload. For the+        // T == Boolean case the answer should be `true` (success), and for+        // nullable / collection T the answer should be null/empty rather+        // than blowing up.+        if (response.status.value == 204 || response.contentLength() == 0L) {+            // The most common T's are Boolean (success/failure), List<...>,+            // Map<...>, and nullable data classes. We can't conjure a value+            // for an arbitrary T, but we can short-circuit the predictable+            // success-but-empty case by checking the type token.+            val tType = T::class+            @Suppress("UNCHECKED_CAST")+            when (tType) {+                Boolean::class -> return (response.status.value in 200..299) as T+                Unit::class -> return Unit as T+            }+        }+        if (!response.status.isSuccess()) {+            throw io.ktor.client.plugins.ResponseException(response, "HTTP ${response.status.value}")+        }+        return response.body()     }      suspend inline fun <reified T> getJson(
maps/src/main/cpp/native-lib.cpp
diff --git a/maps/src/main/cpp/native-lib.cpp b/maps/src/main/cpp/native-lib.cppindex 2ced25143d..314edacaf8 100644--- a/maps/src/main/cpp/native-lib.cpp+++ b/maps/src/main/cpp/native-lib.cpp@@ -292,7 +292,15 @@ inline uint32_t accurate_dist_mm(int32_t lat1_e7, int32_t lon1_e7, int32_t lat2_     double s_dphi = sin(delta_phi / 2.0);     double s_dlamb = sin(delta_lambda / 2.0);     double a = s_dphi * s_dphi + cos(phi1) * cos(phi2) * s_dlamb * s_dlamb;-    return (uint32_t)(R * 2.0 * atan2(sqrt(a), sqrt(1.0 - a)));+    double dist = R * 2.0 * atan2(sqrt(a), sqrt(1.0 - a));+    // Saturate instead of truncating: uint32_t maxes out at ~4 294 km,+    // and cross-country transit edges can exceed that. A wraparound+    // turns a 5 000 km segment into a 705 km segment in the cost+    // function and silently breaks routing; saturating preserves the+    // "this edge is enormous" signal even if it's no longer exact.+    if (dist >= (double)UINT32_MAX) return UINT32_MAX;+    if (dist < 0.0) return 0;+    return (uint32_t)dist; }  inline uint32_t get_edge_time_10ms(int zone_id, uint32_t local_edge_id, uint32_t dist_mm, uint8_t type, uint8_t limit, int mode) {@@ -438,6 +446,10 @@ SnappedEdge find_nearest_edge(double lat, double lon, int mode) {     for (int z = std::max(0, target_zone - 2); z <= std::min(NUM_ZONES - 1, target_zone + 2); ++z) {         if (!is_zone_mapped(z)) continue;         uint32_t zone_node_count = g_zone_offsets[z + 1] - g_zone_offsets[z];+        // Guard against an empty zone: `high = zone_node_count - 1` underflows+        // to 0xFFFFFFFF when zone_node_count == 0, which sends the binary+        // search reading way out of bounds on g_node_zones[z][mid].+        if (zone_node_count == 0) continue;         uint32_t low = 0, high = zone_node_count - 1, local_center = 0;         while (low <= high) {             uint32_t mid = low + (high - low) / 2;@@ -445,6 +457,7 @@ SnappedEdge find_nearest_edge(double lat, double lon, int mode) {                 local_center = mid;                 low = mid + 1;             } else {+                if (mid == 0) break;       // prevent unsigned wrap on `high = mid - 1`                 high = mid - 1;             }         }@@ -779,12 +792,22 @@ Java_com_vayunmathur_maps_util_OfflineRouter_init(JNIEnv* env, jobject thiz, jst      auto m_file = [&](const std::string& p, size_t& s) -> void* {         s = 0; int fd = open(p.c_str(), O_RDONLY); if (fd < 0) return nullptr;-        s = lseek(fd, 0, SEEK_END); void* a = mmap(nullptr, s, PROT_READ, MAP_SHARED, fd, 0); close(fd);+        off_t end = lseek(fd, 0, SEEK_END);+        if (end <= 0) { close(fd); return nullptr; }   // empty / unreadable file+        s = (size_t)end;+        void* a = mmap(nullptr, s, PROT_READ, MAP_SHARED, fd, 0); close(fd);         return (a == MAP_FAILED) ? nullptr : a;     };     size_t s_meta; uint32_t* meta = (uint32_t*)m_file(base + "metadata.bin", s_meta);     if (!meta) { env->ReleaseStringUTFChars(base_path, path_raw); return false; }     bool has_edge_metadata = (s_meta >= NUM_ZONES * 2 * sizeof(uint32_t));+    // Defensive: if metadata.bin is smaller than even the single-uint32-per-zone+    // layout, we can't safely index meta[i] below -> bail out instead of SIGBUS.+    if (s_meta < NUM_ZONES * sizeof(uint32_t)) {+        munmap(meta, s_meta);+        env->ReleaseStringUTFChars(base_path, path_raw);+        return false;+    }     g_zone_offsets[0] = 0;     if (has_edge_metadata) {         for (int i = 0; i < NUM_ZONES; ++i) g_zone_offsets[i+1] = g_zone_offsets[i] + meta[i*2];@@ -1020,9 +1043,17 @@ Java_com_vayunmathur_maps_util_OfflineRouter_getTrafficTileNative(JNIEnv* env, j         sqlite3_step(stmt); sqlite3_finalize(stmt);     } -    const auto& final_data = compressed.empty() ? tile_buf : compressed;-    jbyteArray res = env->NewByteArray(final_data.size());-    env->SetByteArrayRegion(res, 0, final_data.size(), (jbyte*)final_data.data());+    // If gzip somehow failed, we MUST NOT return the raw tile because the+    // HTTP wrapper in Kotlin unconditionally tags the body+    // `Content-Encoding: gzip`. MapLibre would then try to gunzip plain+    // protobuf and fail to render. Returning null here makes the server+    // respond with 204 (no tile) and MapLibre falls back to no traffic+    // overlay for that cell instead of breaking the render.+    if (compressed.empty()) {+        return nullptr;+    }+    jbyteArray res = env->NewByteArray(compressed.size());+    env->SetByteArrayRegion(res, 0, compressed.size(), (jbyte*)compressed.data());     return res; } 
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 36e52b2092..2e472aec38 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -7,7 +7,12 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.library.downloadservice.InitialDownloadChecker import com.vayunmathur.library.ui.DynamicTheme@@ -24,11 +29,21 @@ import com.vayunmathur.maps.ui.SearchPage import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.MapsZonesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import org.maplibre.android.log.Logger import java.io.File +/**+ * Copies the bundled `world_z0-6.pmtiles` asset into [Context.filesDir] on+ * first launch and returns the `pmtiles://` URL the map style references.+ *+ * MUST be called off the main thread — the pmtiles file is ~tens of MB and+ * copying it synchronously in `onCreate` previously caused an ANR on first+ * launch / after a clean install.+ */ fun ensurePmtilesReady(context: Context): String {     val fileName = "world_z0-6.pmtiles"     val outFile = File(context.filesDir, fileName)@@ -49,7 +64,6 @@ class MainActivity : ComponentActivity() {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         val ds = DataStoreUtils.getInstance(this)-        ensurePmtilesReady(this)         Logger.setVerbosity(Logger.INFO) // //        runBlocking {@@ -62,6 +76,15 @@ class MainActivity : ComponentActivity() {          setContent {             DynamicTheme {+                // Copy the bundled pmtiles asset off the main thread on first+                // launch (~tens of MB). Until it's ready we show whatever the+                // download-checker decides; afterwards the map style URL is+                // available via Application-level state (existing callers+                // re-invoke ensurePmtilesReady but it's a fast no-op once the+                // file is on disk).+                LaunchedEffect(Unit) {+                    withContext(Dispatchers.IO) { ensurePmtilesReady(this@MainActivity) }+                }                 InitialDownloadChecker(ds, listOf(                     Triple("https://data.vayunmathur.com/amenities.db", "amenities.db", getString(R.string.downloading_amenity_database)),                     Triple("https://data.vayunmathur.com/metadata.bin", "metadata.bin", getString(R.string.downloading_navigation_metadata)),
maps/src/main/java/com/vayunmathur/maps/data/CountryMap.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/CountryMap.kt b/maps/src/main/java/com/vayunmathur/maps/data/CountryMap.ktindex 49123f381b..b621c88a28 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/CountryMap.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/CountryMap.kt@@ -190,8 +190,11 @@ fun getProperties(fgbFeature: FgbFeature, header: Header): Map<String, JsonEleme     while (bb.hasRemaining()) {         val keyIndex = bb.short.toInt() and 0xFFFF -        val column = header.columns(keyIndex)-        val key = column?.name() ?: "attr_$keyIndex"+        // If the column index isn't in the header, we don't know how many+        // bytes to skip past — abort the rest of this feature's properties+        // rather than reading random bytes and possibly walking off the end.+        val column = header.columns(keyIndex) ?: break+        val key = column.name() ?: "attr_$keyIndex"         val valueType = column.type()          val value: JsonElement? = when (valueType) {
maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt b/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.ktindex 71946c07df..333f4f4e85 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt@@ -21,18 +21,25 @@ class OpeningHours(val rawString: String) {         fun from(input: String): OpeningHours = OpeningHours(input)          private fun parse(input: String): List<OpeningRule> {+            // Wrap each rule parse in runCatching so a single malformed segment+            // doesn't crash the bottom sheet. Real OSM `opening_hours` strings+            // include things like "24/7", "Mo-Fr sunrise-sunset", "PH", or+            // localised abbreviations we don't handle yet — silently drop those+            // rather than throwing NumberFormatException up the UI stack.             return input.split(";").mapNotNull { part ->-                val trimmed = part.trim()-                if (trimmed.isEmpty()) return@mapNotNull null--                val lastSpace = trimmed.lastIndexOf(' ')-                val dayPart = if (lastSpace != -1) trimmed.substring(0, lastSpace) else "Mo-Su"-                val timePart = trimmed.substring(lastSpace + 1)--                OpeningRule(-                    days = parseDays(dayPart),-                    intervals = parseIntervals(timePart)-                )+                runCatching {+                    val trimmed = part.trim()+                    if (trimmed.isEmpty()) return@runCatching null++                    val lastSpace = trimmed.lastIndexOf(' ')+                    val dayPart = if (lastSpace != -1) trimmed.substring(0, lastSpace) else "Mo-Su"+                    val timePart = trimmed.substring(lastSpace + 1)++                    OpeningRule(+                        days = parseDays(dayPart),+                        intervals = parseIntervals(timePart)+                    )+                }.getOrNull()             }         } @@ -51,6 +58,7 @@ class OpeningHours(val rawString: String) {                 val cleanSegment = segment.trim()                 if (cleanSegment.contains("-")) {                     val parts = cleanSegment.split("-")+                    if (parts.size < 2) return@forEach                     val start = map[parts[0]] ?: return@forEach                     val end = map[parts[1]] ?: return@forEach                     var curr = start@@ -71,16 +79,26 @@ class OpeningHours(val rawString: String) {             return timeStr.split(",").mapNotNull {                 val range = it.split("-")                 if (range.size != 2) return@mapNotNull null-                TimeInterval(parseCustomTime(range[0]), parseCustomTime(range[1]))+                val start = parseCustomTime(range[0]) ?: return@mapNotNull null+                val end = parseCustomTime(range[1]) ?: return@mapNotNull null+                TimeInterval(start, end)             }         } -        private fun parseCustomTime(time: String): LocalTime {+        // Returns null for unparseable strings instead of throwing — OSM has+        // entries like "sunrise", "12:00+", "dusk" that we can't represent.+        private fun parseCustomTime(time: String): LocalTime? {             val parts = time.trim().split(":")-            var hour = parts[0].toInt()-            val minute = if (parts.size > 1) parts[1].toInt() else 0-            if (hour >= 24) hour -= 24-            return LocalTime(hour, minute)+            if (parts.isEmpty() || parts[0].isBlank()) return null+            return try {+                var hour = parts[0].toInt()+                val minute = if (parts.size > 1) parts[1].toIntOrNull() ?: 0 else 0+                if (hour >= 24) hour -= 24+                if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return null+                LocalTime(hour, minute)+            } catch (_: NumberFormatException) {+                null+            }         }     } 
maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.ktindex 06c11e77bb..1e6fdfca57 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -43,23 +43,36 @@ suspend fun parse(feature: Feature1, db: AmenityDatabase): SpecificFeature? {     val properties = feature.properties ?: return null     return when(properties.string("kind")) {         "country" -> {-            val wiki = Wikidata.get(properties.string("wikidata")!!)-            SpecificFeature.Admin0Label(wiki.getProperty("P297")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)+            // Each of these tags may be missing on tiles for small/disputed+            // territories or when Wikidata returns no result. Skip the feature+            // rather than crashing the bottom sheet.+            val wikidataId = properties.string("wikidata") ?: return null+            val wiki = try { Wikidata.get(wikidataId) } catch (_: Exception) { return null }+            val iso = wiki.getProperty("P297") ?: return null+            val wikipediaUrl = wiki.getWikipedia() ?: return null+            val name = properties.string("name:en") ?: properties.string("name") ?: return null+            SpecificFeature.Admin0Label(iso, wikipediaUrl, name)         }         "region" -> {-            val wiki = Wikidata.get(properties.string("wikidata")!!)-            SpecificFeature.Admin1Label(wiki.getProperty("P300")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)+            val wikidataId = properties.string("wikidata") ?: return null+            val wiki = try { Wikidata.get(wikidataId) } catch (_: Exception) { return null }+            val iso = wiki.getProperty("P300") ?: return null+            val wikipediaUrl = wiki.getWikipedia() ?: return null+            val name = properties.string("name:en") ?: properties.string("name") ?: return null+            SpecificFeature.Admin1Label(iso, wikipediaUrl, name)         }         "restaurant", "fast_food", "cafe", "bar" -> {+            val point = geometry as? Point ?: return null             val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }-            SpecificFeature.Restaurant(tags["name"] ?: "", tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) }, (geometry as Point).coordinates)+            SpecificFeature.Restaurant(tags["name"] ?: "", tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) }, point.coordinates)         }         "bus_stop", "bus_station", "tram_stop", "railway_station", "subway_entrance" -> {+            val point = geometry as? Point ?: return null             val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }             val gtfsTag = tags.keys.find { it.startsWith("gtfs:stop_code:") }             val gtfsFeed = gtfsTag?.removePrefix("gtfs:stop_code:")             val stopCode = gtfsTag?.let { tags[it] }-            SpecificFeature.TransitStop(tags["name"] ?: "", stopCode, gtfsFeed, (geometry as Point).coordinates)+            SpecificFeature.TransitStop(tags["name"] ?: "", stopCode, gtfsFeed, point.coordinates)         }         !in listOf(             "country", "region", "county", "locality", "address", "building", "building_part",@@ -75,8 +88,9 @@ suspend fun parse(feature: Feature1, db: AmenityDatabase): SpecificFeature? {             "highway", "major_road", "minor_road", "path", "aerialway", "ferry", "rail",             "aeroway", "water", "lake", "playa", "ocean"         ) -> {+            val point = geometry as? Point ?: return null             val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }-            SpecificFeature.GenericPlace(tags["name"] ?: "", tags["phone"], tags["website"], tags["opening_hours"]?.let { OpeningHours.from(it) }, (geometry as Point).coordinates)+            SpecificFeature.GenericPlace(tags["name"] ?: "", tags["phone"], tags["website"], tags["opening_hours"]?.let { OpeningHours.from(it) }, point.coordinates)         }         else -> null     }
maps/src/main/java/com/vayunmathur/maps/data/Tag.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt b/maps/src/main/java/com/vayunmathur/maps/data/Tag.ktindex 2da20e3a82..37844f203c 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt@@ -69,16 +69,22 @@ abstract class AmenityDatabase : RoomDatabase() { fun buildAmenityDatabase(context: Context): AmenityDatabase {     val dbFile = File(context.getExternalFilesDir(null), "amenities.db") +    // Use `createFromFile` so Room opens the pre-downloaded SQLite file at+    // its real on-disk path. Passing dbFile.absolutePath as the `name`+    // argument (as the previous code did) makes Room interpret the slashes+    // as subdirectory components under /data/data/<pkg>/databases/, which+    // either fails to open or creates an unexpected file. The "name"+    // argument is just a logical identifier in this mode.     return Room.databaseBuilder(         context,         AmenityDatabase::class.java,-        dbFile.absolutePath // This name is ignored by our custom factory+        "amenities.db"     )+        .createFromFile(dbFile)         .setJournalMode(RoomDatabase.JournalMode.TRUNCATE) // External storage can be flaky with WAL         .addCallback(object : RoomDatabase.Callback() {             override fun onOpen(db: SupportSQLiteDatabase) {                 super.onOpen(db)-                // Safety check: ensure the file isn't read-only if you need to write                 db.execSQL("PRAGMA synchronous = NORMAL")             }         })
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 3ec445b995..36cde4f1be 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -114,7 +114,6 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     }      LaunchedEffect(camera.position) {-        println(camera.position.zoom)         if (camera.position.zoom >= 11.0) {             delay(300) // Debounce traffic loading             val projection = camera.projection@@ -249,9 +248,10 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                         listOf("${it}_base", "${it}_hybrid")                                     }.toSet()                                 ) ?: emptyList()-                                println("FEATURES: $features")-                                val listedFeatures = features.mapNotNull { parse(it, db) }-                                println("LISTED FEATURES: $listedFeatures")+                                // parse() may do network (Wikidata) + Room — do it off Main.+                                val listedFeatures = withContext(Dispatchers.IO) {+                                    features.mapNotNull { runCatching { parse(it, db) }.getOrNull() }+                                }                                  listedFeatures.firstOrNull()?.let {                                     if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(@@ -296,8 +296,15 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                                 ?: stringResource(MapsR.string.your_location)                                         )                                     }, Modifier.clickable {-                                        val bbox = camera.projection!!.queryVisibleBoundingBox()-                                        backStack.add(Route.SearchPage(idx, bbox.east, bbox.west, bbox.north, bbox.south))+                                        // Style may not have finished loading+                                        // — fall back to a world-spanning bbox+                                        // so the search query still works.+                                        val bbox = camera.projection?.queryVisibleBoundingBox()+                                        backStack.add(Route.SearchPage(idx,+                                            bbox?.east ?: 180.0,+                                            bbox?.west ?: -180.0,+                                            bbox?.north ?: 85.0,+                                            bbox?.south ?: -85.0))                                     }, trailingContent = {                                         Row(verticalAlignment = Alignment.CenterVertically) {                                             if(idx > 0 && idx < routeFeature.waypoints.size - 1) {@@ -329,8 +336,12 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         ListItem({                             Text(name)                         }, colors = ListItemDefaults.colors(Color.Transparent), modifier = Modifier.clickable {-                            val bbox = camera.projection!!.queryVisibleBoundingBox()-                            backStack.add(Route.SearchPage(null, bbox.east, bbox.west, bbox.north, bbox.south))+                            val bbox = camera.projection?.queryVisibleBoundingBox()+                            backStack.add(Route.SearchPage(null,+                                bbox?.east ?: 180.0,+                                bbox?.west ?: -180.0,+                                bbox?.north ?: 85.0,+                                bbox?.south ?: -85.0))                         })                     }                 }
maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.ktindex 8a8de8aca0..20e3331f16 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -55,7 +55,11 @@ fun MyMapLayers(     val context = LocalContext.current      LaunchedEffect(Unit) {-        OfflineRouter.initialize(context)+        // OfflineRouter.initialize does asset-listing I/O — push to IO. The+        // @Synchronized fun itself is idempotent so recomposition is safe.+        kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+            OfflineRouter.initialize(context)+        }     }      key(styleJson) {@@ -168,17 +172,19 @@ fun MyMapLayers(                 when (selectedFeature) {                     is SpecificFeature.Admin0Label -> {                         LaunchedEffect(selectedFeature, outlineSource, styleJson) {+                            // Loading the admin0 FlatGeobuf is a few MB ++                            // linear scan — do it on IO. And tolerate ISOs+                            // missing from the asset (small territories,+                            // Wikidata changes) instead of crashing.+                            val polygon = kotlinx.coroutines.withContext(+                                kotlinx.coroutines.Dispatchers.IO+                            ) {+                                runCatching { CountryMap.getAdmin0(context, selectedFeature.iso) }.getOrNull()+                            } ?: return@LaunchedEffect                             outlineSource.setData(                                 GeoJsonData.Features(                                     FeatureCollection(-                                        listOf(-                                            createInvertedMask(-                                                CountryMap.getAdmin0(-                                                    context,-                                                    selectedFeature.iso-                                                )!!-                                            )-                                        )+                                        listOf(createInvertedMask(polygon))                                     )                                 )                             )@@ -196,17 +202,15 @@ fun MyMapLayers(                     }                     is SpecificFeature.Admin1Label -> {                         LaunchedEffect(selectedFeature, outlineSource, styleJson) {+                            val polygon = kotlinx.coroutines.withContext(+                                kotlinx.coroutines.Dispatchers.IO+                            ) {+                                runCatching { CountryMap.getAdmin1(context, selectedFeature.iso) }.getOrNull()+                            } ?: return@LaunchedEffect                             outlineSource.setData(                                 GeoJsonData.Features(                                     FeatureCollection(-                                        listOf(-                                            createInvertedMask(-                                                CountryMap.getAdmin1(-                                                    context,-                                                    selectedFeature.iso-                                                )!!-                                            )-                                        )+                                        listOf(createInvertedMask(polygon))                                     )                                 )                             )
maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.ktindex 6d88a76125..af54b24c10 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/RestaurantBottomSheet.kt@@ -120,7 +120,11 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio             RestaurantItem(R.drawable.outline_menu_book_24, stringResource(R.string.menu_label)) { goto(context, it) }         }         feature.website?.let {-            RestaurantItem(R.drawable.outline_globe_24, it.toUri().host!!) { goto(context, it) }+            // OSM `website` tags can be malformed or non-http (e.g. plain+            // "facebook.com/foo", "mailto:..."). Fall back to the raw+            // string if URI parsing yields no host.+            val label = runCatching { it.toUri().host }.getOrNull()?.takeUnless { h -> h.isBlank() } ?: it+            RestaurantItem(R.drawable.outline_globe_24, label) { goto(context, it) }         }         feature.phone?.let {             RestaurantItem(R.drawable.outline_phone_enabled_24, it) { goto(context, "tel:$it") }@@ -193,7 +197,8 @@ fun RestaurantBottomSheet(viewModel: SelectedFeatureViewModel, inactiveNavigatio             }         }         feature.website?.let {-            RestaurantItem(R.drawable.outline_globe_24, it.toUri().host!!) { goto(context, it) }+            val label = runCatching { it.toUri().host }.getOrNull()?.takeUnless { h -> h.isBlank() } ?: it+            RestaurantItem(R.drawable.outline_globe_24, label) { goto(context, it) }         }         feature.phone?.let {             RestaurantItem(R.drawable.outline_phone_enabled_24, it) { goto(context, "tel:$it") }
maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.ktindex 7fa721b856..d33c284ce4 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt@@ -106,10 +106,18 @@ fun SearchPage(                             modifier = Modifier.clickable {                                 searchViewModel.resolveAmenity(amenity, db) { feature ->                                     if (idx != null) {-                                        val f = viewModel.selectedFeature.value as SpecificFeature.Route-                                        viewModel.set(f.copy(waypoints = f.waypoints.mapIndexed { idx2, it ->-                                            if (idx2 == idx) feature else it-                                        }))+                                        // The selection could have changed (e.g. user+                                        // navigated away and back) between launching the+                                        // resolve and the callback firing. Tolerate a+                                        // non-Route current selection rather than crashing.+                                        val current = viewModel.selectedFeature.value+                                        if (current is SpecificFeature.Route) {+                                            viewModel.set(current.copy(waypoints = current.waypoints.mapIndexed { idx2, it ->+                                                if (idx2 == idx) feature else it+                                            }))+                                        } else {+                                            viewModel.set(feature)+                                        }                                     } else {                                         viewModel.set(feature)                                     }
maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.ktindex b91c276f0a..2bb05a977e 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/FrameworkLocationManager.kt@@ -25,6 +25,8 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {     private var onUpdate: ((Position, Float) -> Unit)? = null     private var lastLocation: Location? = null     private var currentHeading: Float = 0f+    /** Listener we registered with the OS so [stop] can unregister it. */+    private var registeredLocationListener: LocationListener? = null      @SuppressLint("MissingPermission")     fun startUpdates(onUpdateReceived: (Position, Float) -> Unit): LocationListener {@@ -40,29 +42,38 @@ class FrameworkLocationManager(context: Context) : SensorEventListener {             }             override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}         }+        registeredLocationListener = locationListener          if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {             locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, locationListener)-            println("GPS")         }         if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {             locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 0f, locationListener)-            println("NET")         }          // 2. Setup Sensor Updates (Compass)         sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.also { acc ->             sensorManager.registerListener(this, acc, SensorManager.SENSOR_DELAY_UI)-            println("ACCEL")         }         sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)?.also { mag ->             sensorManager.registerListener(this, mag, SensorManager.SENSOR_DELAY_UI)-            println("MAG")         }          return locationListener     } +    /**+     * Tear down all OS-registered callbacks. MUST be called when the owning+     * scope (typically the ViewModel) is destroyed, or the GPS radio stays+     * powered and the accel/magnetometer listeners leak.+     */+    fun stop() {+        registeredLocationListener?.let { runCatching { locationManager.removeUpdates(it) } }+        registeredLocationListener = null+        runCatching { sensorManager.unregisterListener(this) }+        onUpdate = null+    }+     override fun onSensorChanged(event: SensorEvent) {         if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) {             accelerometerReading = event.values
maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt b/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.ktindex 099942c1b9..c7f530d090 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/GTFSProvider.kt@@ -3,9 +3,14 @@ package com.vayunmathur.maps.util import android.content.Context import java.io.BufferedReader import java.io.InputStreamReader+import java.util.concurrent.ConcurrentHashMap  object GTFSProvider {-    private val routeColors = mutableMapOf<String, String>() // Key: feedName:routeName, Value: #HEX+    // Accessed concurrently from OfflineRouter.getRoute (Dispatchers.Default)+    // and from MyMapLayers on the Main thread, so use a thread-safe map —+    // a plain HashMap mutation race can corrupt internal buckets and cause+    // ConcurrentModificationException or infinite get() loops.+    private val routeColors = ConcurrentHashMap<String, String>() // Key: feedName:routeName, Value: #HEX      fun getRouteColor(context: Context, feedName: String, routeName: String): String? {         val cacheKey = "$feedName:$routeName"
maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.ktindex 648bff6ad8..b0aa44d080 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -8,6 +8,8 @@ import com.vayunmathur.maps.data.AmenityEntity import com.vayunmathur.maps.data.OpeningHours import com.vayunmathur.maps.data.SpecificFeature import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow@@ -29,10 +31,17 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati     private val _results = MutableStateFlow<List<AmenityEntity>>(emptyList())     val results: StateFlow<List<AmenityEntity>> = _results.asStateFlow() +    /** In-flight search job — cancelled on each new keystroke so old DB queries+     *  don't race ahead of newer ones and overwrite the result list. */+    private var searchJob: Job? = null+     /**      * Updates the search text and (asynchronously) the result list filtered by      * the supplied bounding box. Queries shorter than two characters clear the      * results without hitting the DB.+     *+     * Debounced ~120 ms so fast typists don't stack a Room/FTS query per+     * keystroke; the previous job is cancelled on every call.      */     fun setQuery(         query: String,@@ -43,33 +52,38 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         north: Double,     ) {         _query.value = query-        viewModelScope.launch {-            _results.value = if (query.length >= 2) {-                withContext(Dispatchers.IO) {-                    db.amenityDao().getInBBox(-                        query = "*$query*",-                        latMin = south,-                        latMax = north,-                        lonMin = west,-                        lonMax = east,-                    )-                }-            } else {-                emptyList()+        searchJob?.cancel()+        if (query.length < 2) {+            _results.value = emptyList()+            return+        }+        searchJob = viewModelScope.launch {+            delay(120)+            val res = withContext(Dispatchers.IO) {+                db.amenityDao().getInBBox(+                    query = "*$query*",+                    latMin = south,+                    latMax = north,+                    lonMin = west,+                    lonMax = east,+                )             }+            _results.value = res         }     }      /** Resets the search state. */     fun reset() {+        searchJob?.cancel()         _query.value = ""         _results.value = emptyList()     }      /**      * Loads tags for [amenity], builds a [SpecificFeature.Restaurant], and-     * invokes [onFeature] back on the main thread. Used by composables to bind-     * the result into the selected-feature flow.+     * invokes [onFeature] back on the main thread. The launch runs in+     * `viewModelScope` so a navigation-away mid-resolve cleanly cancels the+     * callback rather than calling back into a stale UI.      */     fun resolveAmenity(         amenity: AmenityEntity,
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 9396b4db76..be99c42708 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -8,8 +8,10 @@ import com.vayunmathur.maps.R import com.vayunmathur.maps.data.SpecificFeature import java.io.File import java.io.OutputStream+import java.net.InetAddress import java.nio.ByteBuffer import java.nio.ByteOrder+import java.util.concurrent.Executors import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -31,12 +33,20 @@ object OfflineRouter {     private fun startLocalTileServer() {         Thread {             try {-                val serverSocket = java.net.ServerSocket(0)+                // Bind to loopback ONLY. The previous `ServerSocket(0)` defaulted+                // to 0.0.0.0 which let any app on the device (or anything on the+                // local network) hit /traffic/{z}/{x}/{y}.+                val serverSocket = java.net.ServerSocket(0, 50, InetAddress.getLoopbackAddress())                 serverPort = serverSocket.localPort-                Log.d("OFFLINE_ROUTER", "Tile server started on port $serverPort")-                while (true) {+                Log.d("OFFLINE_ROUTER", "Tile server started on port $serverPort (loopback only)")+                // Hand each client to a small pool so a slow tile doesn't block+                // MapLibre's concurrent tile requests behind the global mutex.+                val pool = Executors.newFixedThreadPool(4)+                while (!serverSocket.isClosed) {                     val client = serverSocket.accept()-                    handleClient(client)+                    // Prevent a half-open / hung client from holding a worker forever.+                    runCatching { client.soTimeout = 5_000 }+                    pool.execute { handleClient(client) }                 }             } catch (e: Exception) {                 Log.e("OFFLINE_ROUTER", "Tile server error", e)@@ -167,7 +177,13 @@ object OfflineRouter {         if (forceAsync) {             trafficScope.launch { block() }         } else {-            runBlocking(Dispatchers.IO) { block() }+            // Previously called runBlocking(Dispatchers.IO) which blocked the+            // native caller's thread (often a Dispatchers.Default worker via+            // getRoute) for an entire 60s HTTP round-trip. That starved the+            // Default pool. Always async; the native side reacts to+            // notifyTrafficUpdated / notifyTrafficFetchFinishedNative when the+            // HTTP response is processed.+            trafficScope.launch { block() }         }     } @@ -189,12 +205,13 @@ object OfflineRouter {      private var isInitialized = false +    @Synchronized     fun initialize(context: Context) {         if (isInitialized) return         val path = context.getExternalFilesDir(null)?.absolutePath ?: return         Log.d("OfflineRouter", "Initializing with path: $path")-        -        val presentFeeds = context.assets.list("")?.filter { ++        val presentFeeds = context.assets.list("")?.filter {             try { context.assets.list(it)?.contains("routes.txt") == true } catch(_: Exception) { false }         }?.toTypedArray() ?: emptyArray() 
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex 2316c7d0ea..33ec8546eb 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -39,6 +39,13 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli         }     } +    override fun onCleared() {+        // Unregister GPS + sensor listeners so the radio doesn't keep draining+        // battery after the user navigates away from the map module.+        locationManager.stop()+        super.onCleared()+    }+     fun set(feature: SpecificFeature?) {         _selectedFeature.value = feature     }
maps/src/main/java/com/vayunmathur/maps/util/ZoneDownloadManager.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/ZoneDownloadManager.kt b/maps/src/main/java/com/vayunmathur/maps/util/ZoneDownloadManager.ktindex c4c603f784..7a86c18e15 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/ZoneDownloadManager.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/ZoneDownloadManager.kt@@ -1,6 +1,7 @@ package com.vayunmathur.maps.util import android.app.DownloadManager import android.content.Context+import android.database.Cursor import androidx.core.net.toUri import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay@@ -27,60 +28,61 @@ class ZoneDownloadManager(private val context: Context) {              // 1. Get current system status for all zone downloads             val query = DownloadManager.Query()-            val cursor = downloadManager.query(query)-            -            // Map to track which parts of which zones we've found in the system-            val foundParts = mutableMapOf<Int, MutableSet<String>>()--            while (cursor.moveToNext()) {-                val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))-                if (title.startsWith("Map Zone ")) {-                    // Title format: "Map Zone $zoneId ($part)"-                    val zonePartString = title.removePrefix("Map Zone ")-                    val zoneId = zonePartString.substringBefore(" ").toIntOrNull()-                    val partName = zonePartString.substringAfter("(", "").substringBefore(")")--                    if (zoneId != null && partName.isNotEmpty()) {-                        val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))-                        val downloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))-                        val total = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))--                        val progress = when (status) {-                            DownloadManager.STATUS_SUCCESSFUL -> 1.0-                            DownloadManager.STATUS_FAILED -> 0.0-                            else -> if (total > 0) downloaded.toDouble() / total.toDouble() else 0.0-                        }--                        progressMap[zoneId] = progressMap.getOrDefault(zoneId, 0.0) + progress-                        foundParts.getOrPut(zoneId) { mutableSetOf() }.add(partName)--                        if (status == DownloadManager.STATUS_RUNNING ||-                            status == DownloadManager.STATUS_PENDING ||-                            status == DownloadManager.STATUS_PAUSED) {-                            activeZones.add(zoneId)+            // .use { } guarantees the Cursor is closed even if a column read+            // below throws — otherwise we leak a Cursor on every poll cycle.+            downloadManager.query(query).use { cursor ->+                // Map to track which parts of which zones we've found in the system+                val foundParts = mutableMapOf<Int, MutableSet<String>>()++                while (cursor.moveToNext()) {+                    val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+                    if (title.startsWith("Map Zone ")) {+                        // Title format: "Map Zone $zoneId ($part)"+                        val zonePartString = title.removePrefix("Map Zone ")+                        val zoneId = zonePartString.substringBefore(" ").toIntOrNull()+                        val partName = zonePartString.substringAfter("(", "").substringBefore(")")++                        if (zoneId != null && partName.isNotEmpty()) {+                            val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))+                            val downloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))+                            val total = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))++                            val progress = when (status) {+                                DownloadManager.STATUS_SUCCESSFUL -> 1.0+                                DownloadManager.STATUS_FAILED -> 0.0+                                else -> if (total > 0) downloaded.toDouble() / total.toDouble() else 0.0+                            }++                            progressMap[zoneId] = progressMap.getOrDefault(zoneId, 0.0) + progress+                            foundParts.getOrPut(zoneId) { mutableSetOf() }.add(partName)++                            if (status == DownloadManager.STATUS_RUNNING ||+                                status == DownloadManager.STATUS_PENDING ||+                                status == DownloadManager.STATUS_PAUSED) {+                                activeZones.add(zoneId)+                            }                         }                     }                 }-            }-            cursor.close()--            // 2. Cross-reference with disk for any parts not found in DownloadManager-            // (e.g. if system cleared the record but file exists)-            activeZones.forEach { zoneId ->-                val expectedParts = listOf("Map", "Nodes", "Graph", "Transit")-                val foundInDM = foundParts[zoneId] ?: emptySet()-                -                expectedParts.forEach { part ->-                    if (part !in foundInDM) {-                        val fileName = when(part) {-                            "Map" -> "zone_$zoneId.pmtiles"-                            "Nodes" -> "nodes_zone_$zoneId.bin"-                            "Graph" -> "edges_zone_$zoneId.bin"-                            else -> "transit_voyages_zone_$zoneId.bin"-                        }-                        val file = File(context.getExternalFilesDir(null), fileName)-                        if (file.exists()) {-                            progressMap[zoneId] = progressMap.getOrDefault(zoneId, 0.0) + 1.0++                // 2. Cross-reference with disk for any parts not found in DownloadManager+                // (e.g. if system cleared the record but file exists)+                activeZones.forEach { zoneId ->+                    val expectedParts = listOf("Map", "Nodes", "Graph", "Transit")+                    val foundInDM = foundParts[zoneId] ?: emptySet()++                    expectedParts.forEach { part ->+                        if (part !in foundInDM) {+                            val fileName = when(part) {+                                "Map" -> "zone_$zoneId.pmtiles"+                                "Nodes" -> "nodes_zone_$zoneId.bin"+                                "Graph" -> "edges_zone_$zoneId.bin"+                                else -> "transit_voyages_zone_$zoneId.bin"+                            }+                            val file = File(context.getExternalFilesDir(null), fileName)+                            if (file.exists()) {+                                progressMap[zoneId] = progressMap.getOrDefault(zoneId, 0.0) + 1.0+                            }                         }                     }                 }@@ -104,15 +106,15 @@ class ZoneDownloadManager(private val context: Context) {     fun deleteZone(zoneId: Int) {         // 1. Cancel active or pending downloads in the system         val query = DownloadManager.Query()-        val cursor = downloadManager.query(query)-        while (cursor.moveToNext()) {-            val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))-            if (title.startsWith("Map Zone $zoneId ")) {-                val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))-                downloadManager.remove(id)+        downloadManager.query(query).use { cursor ->+            while (cursor.moveToNext()) {+                val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+                if (title.startsWith("Map Zone $zoneId ")) {+                    val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))+                    downloadManager.remove(id)+                }             }         }-        cursor.close()          // 2. Remove the files from disk         val files = listOf(@@ -140,40 +142,45 @@ class ZoneDownloadManager(private val context: Context) {         .flowOn(Dispatchers.IO) // Run the disk/DB checks on a background thread      fun getDownloadedZones(): List<Int> {+        // Build the set of currently-downloading zone IDs ONCE per poll instead+        // of opening a DownloadManager cursor 64 times (one per zone).+        val downloadingZones = activeDownloadZoneIds()         return (0..63).filter { zoneId ->-            getZoneStatus(zoneId) == ZoneStatus.FINISHED+            getZoneStatus(zoneId, downloadingZones) == ZoneStatus.FINISHED         }     } -    fun getZoneStatus(zoneId: Int): ZoneStatus {+    /** Single-pass scan of the DownloadManager for zone download titles. */+    private fun activeDownloadZoneIds(): Set<Int> {+        val active = mutableSetOf<Int>()+        downloadManager.query(DownloadManager.Query()).use { cursor ->+            while (cursor.moveToNext()) {+                val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+                    ?: continue+                if (!title.startsWith("Map Zone ")) continue+                val id = title.removePrefix("Map Zone ").substringBefore(" ").toIntOrNull() ?: continue+                val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))+                if (status == DownloadManager.STATUS_RUNNING ||+                    status == DownloadManager.STATUS_PAUSED ||+                    status == DownloadManager.STATUS_PENDING) {+                    active.add(id)+                }+            }+        }+        return active+    }++    fun getZoneStatus(zoneId: Int, activeIds: Set<Int> = activeDownloadZoneIds()): ZoneStatus {         val pmtilesFile = File(context.getExternalFilesDir(null), "zone_$zoneId.pmtiles")         val nodesFile = File(context.getExternalFilesDir(null), "nodes_zone_$zoneId.bin")         val edgesFile = File(context.getExternalFilesDir(null), "edges_zone_$zoneId.bin")         val transitFile = File(context.getExternalFilesDir(null), "transit_voyages_zone_$zoneId.bin") -        val allFilesExist = pmtilesFile.exists() && nodesFile.exists() && +        val allFilesExist = pmtilesFile.exists() && nodesFile.exists() &&                           edgesFile.exists() && transitFile.exists()         if (allFilesExist) return ZoneStatus.FINISHED -        val query = DownloadManager.Query()-        val cursor = downloadManager.query(query)-        var isDownloading = false--        while (cursor.moveToNext()) {-            val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))-            if (title.startsWith("Map Zone $zoneId ")) {-                val systemStatus = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))-                if (systemStatus == DownloadManager.STATUS_RUNNING ||-                    systemStatus == DownloadManager.STATUS_PAUSED ||-                    systemStatus == DownloadManager.STATUS_PENDING) {-                    isDownloading = true-                    break-                }-            }-        }-        cursor.close()--        return if (isDownloading) ZoneStatus.DOWNLOADING else ZoneStatus.NOT_STARTED+        return if (zoneId in activeIds) ZoneStatus.DOWNLOADING else ZoneStatus.NOT_STARTED     }      fun startDownload(zoneId: Int) {
maps/src/main/res/xml/data_extraction_rules.xml
diff --git a/maps/src/main/res/xml/data_extraction_rules.xml b/maps/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..f92f799365--- /dev/null+++ b/maps/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,30 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+  Maps-specific backup/transfer rules. The shared library rules include+  `external` storage, but for this module that domain holds tens to hundreds+  of megabytes of downloaded offline-zone data (zone_*.pmtiles,+  nodes_zone_*.bin, edges_zone_*.bin, transit_voyages_zone_*.bin,+  amenities.db, metadata.bin, road_names.bin, world_z0-6.pmtiles).++  Cloud Auto Backup has a 25 MB quota; including these files would blow past+  it on the first sync and silently disable backup for the whole app. They're+  re-downloadable from data.vayunmathur.com on demand, so we exclude them.+-->+<data-extraction-rules>+    <cloud-backup>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <!-- external: deliberately excluded — see comment above. -->+    </cloud-backup>+    <device-transfer>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <!-- external IS included for device transfer so a new phone gets the+             user's already-downloaded zones rather than re-downloading them. -->+        <include domain="external" path="." />+    </device-transfer>+</data-extraction-rules>