Modern Apps git

← Modern-Apps.git

maps: fix detekt and lint errors

Commit
0d0ee89a4f6e157515fcd5fbe08c6a5a305b40e4
Author
Vayun Mathur <[email protected]>
When
2026-11-01 02:26 UTC (1 month ago)
Parents
905d6de
Split MapOverlayWorker.doWork and MainActivity.navigateTo, name magic numbers, drop 5-way destructuring in NavigationService, simplify PoiArchive.buildMapped, and move the CPU pin hit-test out of MapSurface to get it under the 350-line FileLength limit.

Diff

maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex ea1ca50547..e30a7d5f7a 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -216,33 +216,7 @@ class MainActivity : MaActivity() {     private fun navigateTo(link: MapLink) {         lifecycleScope.launch {             val mode = link.mode ?: RouteService.TravelMode.DRIVE-            // Destination position: an explicit coord, else geocode the query.-            val destPos: GeoPoint?-            val destName: String-            if (link.lat != null && link.lng != null) {-                destPos = GeoPoint(link.lng, link.lat)-                destName = link.query ?: getString(R.string.dropped_pin)-            } else if (!link.query.isNullOrBlank()) {-                val near = biasPosition()-                // Offline OSM POI search (no query-bar side effects: this path-                // must not prefill the search text like searchAndSelectFirst-                // does). Free-text addresses have no OSM path and stay-                // unresolvable, handled below.-                val query = link.query-                val first = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {-                    runCatching {-                        com.vayunmathur.maps.util.PoiIndex.initialize(applicationContext)-                        com.vayunmathur.maps.util.PoiIndex.searchByName(-                            query, near.latitude, near.longitude, limit = 1,-                        ).firstOrNull()-                    }.getOrNull()-                }-                destPos = first?.let { GeoPoint(it.lon, it.lat) }-                destName = first?.name ?: query-            } else {-                destPos = null-                destName = getString(R.string.dropped_pin)-            }+            val (destPos, destName) = resolveDestination(link)             if (destPos == null) {                 Log.status(TAG, "navigateTo: could not resolve destination for $link")                 return@launch@@ -291,6 +265,29 @@ class MainActivity : MaActivity() {         }     } +    /** The link's destination: an explicit coord, else an offline POI lookup of the query. */+    private suspend fun resolveDestination(link: MapLink): Pair<GeoPoint?, String> {+        if (link.lat != null && link.lng != null) {+            return GeoPoint(link.lng, link.lat) to (link.query ?: getString(R.string.dropped_pin))+        }+        val query = link.query+        if (query.isNullOrBlank()) return null to getString(R.string.dropped_pin)+        val near = biasPosition()+        // Offline OSM POI search (no query-bar side effects: this path+        // must not prefill the search text like searchAndSelectFirst+        // does). Free-text addresses have no OSM path and stay+        // unresolvable, handled by the caller.+        val first = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+            runCatching {+                com.vayunmathur.maps.util.PoiIndex.initialize(applicationContext)+                com.vayunmathur.maps.util.PoiIndex.searchByName(+                    query, near.latitude, near.longitude, limit = 1,+                ).firstOrNull()+            }.getOrNull()+        }+        return first?.let { GeoPoint(it.lon, it.lat) } to (first?.name ?: query)+    }+     /** First valid GPS fix within [timeoutMs], or null. (0,0) means "no fix yet". */     private suspend fun awaitUserPosition(timeoutMs: Long = 8_000): GeoPoint? =         withTimeoutOrNull(timeoutMs) {
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.ktindex 98a510d48c..564fa3063c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt@@ -211,28 +211,13 @@ fun MapSurface(                 val offset = click.screen                 // Renderer-drawn pins resolve through the GPU id buffer first: correct under tilt,                 // and never a frame behind the basemap the way the old Compose hit-test was. On a-                // miss (e.g. a pin pushed this very frame, before the id buffer caught up) fall back-                // to the CPU hit-test over the same features, which is tilt-aware via Projection.+                // miss fall back to the CPU hit-test over the same features.                 val hit = markerHits[projection.pickMarker(offset.x.value, offset.y.value)]-                    ?: run {-                        val pins = pinFeatures(-                            searchResults = searchResults,-                            savedPlaces = savedPlaces,-                            parkingSpot = parkingSpot,-                            familyMembers = familyMembers,-                        )-                        val picker = MapFeaturePicker(-                            source = FeatureSource { box, layerIds ->-                                featuresInBox(-                                    pins.filter { it.layerId in layerIds }.map { it.feature },-                                    box,-                                    projection,-                                )-                            },-                            transitEnabled = transitEnabled,-                        )-                        picker.pickPin(offset)-                    }+                    ?: pickPinOnCpu(+                        offset, projection,+                        searchResults, savedPlaces, parkingSpot, familyMembers,+                        transitEnabled,+                    )                  when (hit) {                     MapHit.Parking -> {@@ -303,7 +288,6 @@ fun MapSurface(                 // pick, so this is populated whenever a placed label is under the finger;                 // when nothing is, it falls through to reverse-geocode exactly like a                 // blank tap.-                // to reverse-geocode exactly like a blank tap.                 // A slop box, not the bare point: a place label is a thin line of text, and a                 // zero-size query only hit when the finger landed exactly on a glyph — so a tap                 // "on" a city almost always fell through to reverse-geocode. The same
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.ktindex c4d39dd45d..f89d379360 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt@@ -241,6 +241,38 @@ internal fun pickVehicle(     return best } +/**+ * CPU hit-test over the app's pins: the fallback when the GPU id buffer misses (e.g. a pin+ * pushed this very frame, before the id buffer caught up). Tilt-aware via [projection].+ */+internal suspend fun pickPinOnCpu(+    offset: androidx.compose.ui.unit.DpOffset,+    projection: com.vayunmathur.library.map.Projection,+    searchResults: List<SearchResult>,+    savedPlaces: List<SavedPlace>,+    parkingSpot: ParkingSpot?,+    familyMembers: List<FamilyMember>,+    transitEnabled: Boolean,+): MapHit? {+    val pins = pinFeatures(+        searchResults = searchResults,+        savedPlaces = savedPlaces,+        parkingSpot = parkingSpot,+        familyMembers = familyMembers,+    )+    val picker = MapFeaturePicker(+        source = FeatureSource { box, layerIds ->+            featuresInBox(+                pins.filter { it.layerId in layerIds }.map { it.feature },+                box,+                projection,+            )+        },+        transitEnabled = transitEnabled,+    )+    return picker.pickPin(offset)+}+ /**  * Open the trip sheet for the vehicle sprite under [offset]. True when a  * sprite was hit (the caller returns from the tap); false to fall through to
maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.ktindex 887a1821b7..53ae377381 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt@@ -146,7 +146,10 @@ object MapOverlay {      * Build ids are opaque equality tokens here (match the base or refuse).      */     fun parseBuildId(raw: String): Long =-        raw.removePrefix("0x").removePrefix("0X").toLongOrNull(16) ?: 0L+        raw.removePrefix("0x").removePrefix("0X").toLongOrNull(BUILD_ID_RADIX) ?: 0L++    /** Build ids are hex in the manifest and in logs. */+    const val BUILD_ID_RADIX = 16      /** On-disk file for segment [seg] of overlay [overlaySeq] under [root]. */     fun segmentFile(root: File, overlaySeq: Long, seg: SegmentRef): File =
maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.ktindex 5c8283e09e..ff32bbe7df 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt@@ -46,7 +46,6 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) :         // WorkManager can cold-start the process without MainActivity's TLS         // init; without it the pinned manifest fetch below has no trust store.         NetworkClient.init(applicationContext, TrustBundle.FIRST_PARTY)-        val ds = DataStoreUtils.getInstance(applicationContext)         val root = applicationContext.getExternalFilesDir(null) ?: return Result.failure()         recoverRebaseCrash(root)         // No base, no overlay: the startup gate owns the full download.@@ -60,8 +59,18 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) :             Log.status(TAG, "manifest unparseable or too new; skipping")             return Result.success()         }+        val ds = DataStoreUtils.getInstance(applicationContext)         ds.setString(KEY_LAST_MANIFEST, text.take(MANIFEST_TEXT_CAP))         ds.setLong(KEY_LAST_CHECK, System.currentTimeMillis())+        return applyManifest(root, ds, manifest, text)+    }++    private suspend fun applyManifest(+        root: File,+        ds: DataStoreUtils,+        manifest: MapOverlay.Manifest,+        text: String,+    ): Result {         val pinned = MapOverlay.pinned(root)         if (pinned != null && pinned.overlaySeq >= manifest.overlaySeq) {             Log.status(TAG, "overlay seq ${manifest.overlaySeq} already applied")@@ -80,40 +89,37 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) :             return Result.success()         }         val missing = MapOverlay.missing(root, manifest)-        if (missing.isEmpty()) {-            MapOverlay.pin(root, text)-            ds.setLong(KEY_APPLIED_SEQ, manifest.overlaySeq)-            return Result.success()+        if (missing.isNotEmpty() && !downloadSegments(root, ds, manifest, missing)) return Result.retry()+        if (!MapOverlay.isApplied(root, manifest)) {+            Log.status(TAG, "segments landed but failed verification")+            return Result.retry()         }+        MapOverlay.pin(root, text)+        ds.setLong(KEY_APPLIED_SEQ, manifest.overlaySeq)+        ds.setLong(KEY_PENDING_BYTES, 0L)+        Log.status(TAG, "overlay seq ${manifest.overlaySeq} stored (${missing.size} segments)")+        return Result.success()+    }++    /** Download [missing] sequentially, one segment at a time: peak transient is one segment. */+    private suspend fun downloadSegments(+        root: File,+        ds: DataStoreUtils,+        manifest: MapOverlay.Manifest,+        missing: List<MapOverlay.SegmentRef>,+    ): Boolean {         ds.setLong(KEY_PENDING_BYTES, missing.sumOf { it.len })-        val items = missing.map { seg ->+        return missing.all { seg ->             val file = MapOverlay.segmentFile(root, manifest.overlaySeq, seg)             val rel = root.toURI().relativize(file.toURI()).path-            ModelDownloadItem(+            val item = ModelDownloadItem(                 url = seg.url,                 fileName = rel,                 description = "Map update ${manifest.overlaySeq} part ${seg.seq + 1}/${manifest.segments.size}",                 sha256 = seg.sha256,             )+            downloadModels(applicationContext, ds, listOf(item))         }-        // Sequential, one segment at a time: peak transient is one segment.-        var ok = true-        for (item in items) {-            if (!downloadModels(applicationContext, ds, listOf(item))) {-                ok = false-                break-            }-        }-        if (!ok) return Result.retry()-        if (!MapOverlay.isApplied(root, manifest)) {-            Log.status(TAG, "segments landed but failed verification")-            return Result.retry()-        }-        MapOverlay.pin(root, text)-        ds.setLong(KEY_APPLIED_SEQ, manifest.overlaySeq)-        ds.setLong(KEY_PENDING_BYTES, 0L)-        Log.status(TAG, "overlay seq ${manifest.overlaySeq} stored (${items.size} segments)")-        return Result.success()     }      private fun recoverRebaseCrash(root: File) {@@ -138,7 +144,8 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) :         }         val id = readBaseBuildId(File(root, MapTileCache.BASEMAP_ARCHIVE_FILE)) ?: return false         if (id != manifest.baseBuildId) {-            Log.status(TAG, "base build ${id.toString(16)} != manifest ${manifest.baseBuildId.toString(16)}")+            val radix = MapOverlay.BUILD_ID_RADIX+            Log.status(TAG, "base build ${id.toString(radix)} != manifest ${manifest.baseBuildId.toString(radix)}")             return false         }         return true@@ -276,6 +283,10 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) :     } } +private const val HTTP_OK = 200+private const val BUILD_ID_OFFSET = 16L+private const val BUILD_ID_BYTES = 8+ /**  * GET [url] as text over the pinned FIRST_PARTY bundle, or null on any  * failure (caller retries). Pinned, not plain HTTPS: the manifest names@@ -284,16 +295,16 @@ class MapOverlayWorker(context: Context, params: WorkerParameters) :  */ private suspend fun fetchText(url: String): String? = runCatching {     val (status, body) = NetworkClient.performRequestBytes(url)-    if (status != 200) return null+    if (status != HTTP_OK) return null     body.toString(Charsets.UTF_8) }.getOrNull()  /** The base archive's header `build_id` (bytes 16..24 LE), or null. */ private fun readBaseBuildId(file: File): Long? = runCatching {-    if (!file.isFile || file.length() < 24) return null+    if (!file.isFile || file.length() < BUILD_ID_OFFSET + BUILD_ID_BYTES) return null     java.io.RandomAccessFile(file, "r").use { raf ->-        raf.seek(16)-        val buf = ByteArray(8)+        raf.seek(BUILD_ID_OFFSET)+        val buf = ByteArray(BUILD_ID_BYTES)         raf.readFully(buf)         java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN).long     }
maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.ktindex 3ea8d481fa..1a40eb6916 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt@@ -206,14 +206,14 @@ class NavigationService : Service() {         val destLabel = NavigationSessionManager.session.value.destinationName             ?: getString(R.string.nav_default_destination) -        val (title, content, progressPercent, chipText, smallIcon) = describe(state, mode, destLabel)+        val info = describe(state, mode, destLabel)         val isOngoing = state !is NavigationSessionManager.NavState.Arrived &&             state !is NavigationSessionManager.NavState.Failed          val builder = NotificationCompat.Builder(this, CHANNEL_ID)-            .setContentTitle(title)-            .setContentText(content)-            .setSmallIcon(smallIcon)+            .setContentTitle(info.title)+            .setContentText(info.content)+            .setSmallIcon(info.smallIcon)             .setOngoing(isOngoing)             .setSilent(true)             .setOnlyAlertOnce(true)@@ -243,10 +243,10 @@ class NavigationService : Service() {             }             builder.setStyle(                 NotificationCompat.ProgressStyle()-                    .setProgressSegments(listOf(NotificationCompat.ProgressStyle.Segment(100)))+                    .setProgressSegments(listOf(NotificationCompat.ProgressStyle.Segment(FULL_PROGRESS_PERCENT)))                     .setProgress(percent),             )-            if (chipText != null) builder.setShortCriticalText(chipText)+            info.chipText?.let { builder.setShortCriticalText(it) }             if (isOngoing && state !is NavigationSessionManager.NavState.Failed &&                 LiveUpdateSupport.canPostPromoted(this)             ) {@@ -254,7 +254,7 @@ class NavigationService : Service() {                 builder.setRequestPromotedOngoing(true)             }         } else {-            progressPercent?.let { p -> builder.setProgress(FULL_PROGRESS_PERCENT, p, false) }+            info.progressPercent?.let { p -> builder.setProgress(FULL_PROGRESS_PERCENT, p, false) }         }         return builder.build()     }
maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.ktindex 2bb91522fa..a0bd3718a3 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt@@ -127,19 +127,11 @@ object PoiArchive {         if (!paired) {             Log.status(TAG, "half-paired POI override; using base index+names")         }-        val indexBuf = if (paired) {-            overrideIndex ?: slice(whole, sections, KIND_INDEX)-        } else {-            slice(whole, sections, KIND_INDEX)-        } ?: run {+        val indexBuf = overrideIndex.takeIf { paired } ?: slice(whole, sections, KIND_INDEX) ?: run {             Log.status(TAG, "archive carries no POI index section")             return null         }-        val namesBuf = if (paired) {-            overrideNames ?: slice(whole, sections, KIND_NAMES)-        } else {-            slice(whole, sections, KIND_NAMES)-        } ?: run {+        val namesBuf = overrideNames.takeIf { paired } ?: slice(whole, sections, KIND_NAMES) ?: run {             Log.status(TAG, "archive carries a POI index but no POI names")             return null         }