Modern Apps git

← Modern-Apps.git

maps: download OSM amenities for faster lookup

Commit
85922db94197d0b39fbcd8a9d7d578bfdb985de7
Author
Vayun Mathur <[email protected]>
When
2026-02-04 01:42 UTC (10 months ago)
Parents
325b2ca

Diff

library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex f9311b5d0d..1564e113f5 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -1,6 +1,9 @@ package com.vayunmathur.library.util  import android.content.Context+import androidx.compose.runtime.Composable+import androidx.compose.runtime.State+import androidx.compose.runtime.collectAsState import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences@@ -10,6 +13,8 @@ import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.launch  class DataStoreUtils private constructor(context: Context) {@@ -40,6 +45,11 @@ class DataStoreUtils private constructor(context: Context) {         return stateMap[longPreferencesKey(name)] as Long?     } +    @Composable+    fun getLongState(name: String, default: Long = 0L): State<Long> {+        return dataStore.data.mapNotNull { it[longPreferencesKey(name)] }.collectAsState(default)+    }+     suspend fun setLong(s: String, userid: Long, onlyIfAbsent: Boolean = false) {         dataStore.edit {             if(onlyIfAbsent && it.contains(longPreferencesKey(s))) return@edit
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 66fca3cdaf..f8e0262cc1 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -1,20 +1,142 @@ package com.vayunmathur.maps +import android.app.DownloadManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.os.Build import android.os.Bundle+import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Button+import androidx.compose.material3.Scaffold+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.core.net.toUri import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.maps.ui.MapPage+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking  class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()+        val ds = DataStoreUtils.getInstance(this)         setContent {             DynamicTheme {-                MapPage()+                val downloadedState by ds.getLongState("downloaded")+                val isDownloaded = downloadedState == 2L+                if(isDownloaded) {+                    MapPage()+                } else {+                    DownloadPage(ds)+                }             }         }     }+}++@Composable+fun DownloadPage(ds: DataStoreUtils) {+    val context = LocalContext.current+    val downloaded by ds.getLongState("downloaded")+    Scaffold() { paddingValues ->+        Box(Modifier.padding(paddingValues).fillMaxSize()) {+            if(downloaded == 0L) {+                Button({+                    val onDownloadComplete = object : BroadcastReceiver() {+                        override fun onReceive(context: Context, intent: Intent) {+                            val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)+                            println(id)+                            if (id != -1L) {+                                // Success! Now you can initialize your MappedByteBuffer+                                Toast.makeText(context, "OSM Data Ready", Toast.LENGTH_SHORT).show()+                                runBlocking {+                                    ds.setLong("downloaded", 2L) // done+                                }+                            }+                        }+                    }+                    val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)+                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                        context.registerReceiver(+                            onDownloadComplete,+                            filter,+                            Context.RECEIVER_NOT_EXPORTED // This is the magic flag+                        )+                    } else {+                        context.registerReceiver(onDownloadComplete, filter)+                    }++                    downloadOsmData(context, "https://api.vayunmathur.com/maps/amenities", ds)+                }, Modifier.align(Alignment.Center)) {+                    Text("Download")+                }+            } else {+                var progress by remember { mutableStateOf(0.0) }+                LaunchedEffect(Unit) {+                    val downloadID = ds.getLong("downloadID")!!+                    while(true) {+                        progress = getProgress(context, downloadID)+                        if(progress == 1.0) {+                            ds.setLong("downloaded", 2L)+                        }+                        delay(100)+                    }+                }+                Text("Downloading: ${progress*100}%", Modifier.align(Alignment.Center))+            }+        }+    }+}++fun getProgress(context: Context, downloadId: Long): Double {+    val q = DownloadManager.Query().setFilterById(downloadId)+    val cursor = (context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager).query(q)+    if (cursor.moveToFirst()) {+        val bytesDownloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))+        val bytesTotal = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))+        if (bytesTotal == 0L) return 0.0+        println(bytesDownloaded)+        println(bytesTotal)+        return ((bytesDownloaded).toDouble() / bytesTotal)+    }+    return 0.0+}++fun downloadOsmData(context: Context, url: String, ds: DataStoreUtils) {+    val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager++    val request = DownloadManager.Request(url.toUri())+        .setTitle("OSM Data Update")+        .setDescription("Downloading 2.5GB tag database...")+        .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)+        // Save to app-specific external storage (no permission needed)+        .setDestinationInExternalFilesDir(context, null, "amenities_indexed.bin")+        .setAllowedOverMetered(false) // Recommended for a 2.5GB file!+        .setRequiresCharging(false)++    val downloadId = downloadManager.enqueue(request)++    runBlocking {+        ds.setLong("downloaded", 1L)+        ds.setLong("downloadID", downloadId)+    } }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/OSM.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/OSM.kt b/maps/src/main/java/com/vayunmathur/maps/OSM.ktindex 41c45d8d56..d524ea9179 100644--- a/maps/src/main/java/com/vayunmathur/maps/OSM.kt+++ b/maps/src/main/java/com/vayunmathur/maps/OSM.kt@@ -1,28 +1,148 @@-package com.vayunmathur.maps--import io.ktor.client.HttpClient-import io.ktor.client.call.body-import io.ktor.client.plugins.contentnegotiation.ContentNegotiation-import io.ktor.client.request.get-import io.ktor.serialization.kotlinx.json.json-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.jsonArray-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive+package com.vayunmathur.maps // Update this to your actual package++import android.content.Context+import android.util.Log+import java.io.RandomAccessFile+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.MappedByteBuffer+import java.nio.channels.FileChannel+import java.io.File  object OSM {-    suspend fun getTags(id: ULong): Map<String, String> {-        val client = HttpClient() {-            install(ContentNegotiation) {-                json(Json{-                    ignoreUnknownKeys = true-                })+    private const val TAG = "OSM_Provider"++    // Segmented buffers to bypass the 2GB MappedByteBuffer limit+    private var idBuffer: MappedByteBuffer? = null+    private var keyOffsetBuffer: MappedByteBuffer? = null+    private var valOffsetBuffer: MappedByteBuffer? = null+    private var keysBlobBuffer: MappedByteBuffer? = null+    private var valsBlobBuffer: MappedByteBuffer? = null++    private var tripletCount: Long = 0++    /**+     * Maps the 2.5GB+ binary file into memory-mapped segments.+     * Call this after the download is complete.+     */+    fun initialize(context: Context) {+        try {+            val file = File(context.getExternalFilesDir(null), "amenities_indexed.bin")+            val raf = RandomAccessFile(file, "r")+            val channel = raf.channel+            val totalSize = raf.length()++            // 1. Read Header (8-byte Triplet Count)+            val headerBuf = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN)+            channel.read(headerBuf, 0)+            headerBuf.flip()+            tripletCount = headerBuf.long+            val n = tripletCount.toInt()++            // 2. Calculate Block Start Offsets+            val idStart = 8L+            val idSize = n * 8L++            val kOffStart = idStart + idSize+            val kOffSize = (n + 1) * 4L++            val vOffStart = kOffStart + kOffSize+            val vOffSize = (n + 1) * 4L++            val keysStart = vOffStart + vOffSize++            // Peek at the last key offset to determine keys blob size+            val lastKeyOffBuf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN)+            channel.read(lastKeyOffBuf, vOffStart - 4)+            lastKeyOffBuf.flip()+            val keysSize = lastKeyOffBuf.int.toLong()++            val valsStart = keysStart + keysSize+            val valsSize = totalSize - valsStart++            // 3. Map Segments (Individual columns < 2GB)+            idBuffer = channel.map(FileChannel.MapMode.READ_ONLY, idStart, idSize).apply {+                order(ByteOrder.LITTLE_ENDIAN)+            }+            keyOffsetBuffer = channel.map(FileChannel.MapMode.READ_ONLY, kOffStart, kOffSize).apply {+                order(ByteOrder.LITTLE_ENDIAN)+            }+            valOffsetBuffer = channel.map(FileChannel.MapMode.READ_ONLY, vOffStart, vOffSize).apply {+                order(ByteOrder.LITTLE_ENDIAN)+            }+            keysBlobBuffer = channel.map(FileChannel.MapMode.READ_ONLY, keysStart, keysSize)+            valsBlobBuffer = channel.map(FileChannel.MapMode.READ_ONLY, valsStart, valsSize)++            Log.d(TAG, "Successfully mapped $tripletCount triplets")+            raf.close() // The mapping persists even after closing the channel/file+        } catch (e: Exception) {+            Log.e(TAG, "Failed to initialize OSM data", e)+        }+    }++    /**+     * Retrieves all tags for a given Node ID using O(log n) search + O(1) jump.+     */+    suspend fun getTags(id: Long): Map<String, String> {+        val ids = idBuffer ?: return emptyMap()+        val n = tripletCount.toInt()++        // 1. Binary Search for any index matching this ID+        val matchIndex = findIndexById(id, n, ids)+        if (matchIndex == -1) return emptyMap()++        // 2. Sweep Left and Right to find the range of duplicate IDs+        var first = matchIndex+        while (first > 0 && ids.getLong((first - 1) * 8) == id) {+            first--+        }+        var last = matchIndex+        while (last < n - 1 && ids.getLong((last + 1) * 8) == id) {+            last+++        }++        // 3. Extract all Tag Triplets in the range [first, last]+        val resultMap = mutableMapOf<String, String>()++        // Use duplicated buffers for thread-safe concurrent access+        val kBlob = keysBlobBuffer?.duplicate() ?: return emptyMap()+        val vBlob = valsBlobBuffer?.duplicate() ?: return emptyMap()+        val kOffsets = keyOffsetBuffer ?: return emptyMap()+        val vOffsets = valOffsetBuffer ?: return emptyMap()++        for (i in first..last) {+            // Get Key+            val kStart = kOffsets.getInt(i * 4)+            val kEnd = kOffsets.getInt((i + 1) * 4)+            val keyBytes = ByteArray(kEnd - kStart)+            kBlob.position(kStart)+            kBlob.get(keyBytes)++            // Get Value+            val vStart = vOffsets.getInt(i * 4)+            val vEnd = vOffsets.getInt((i + 1) * 4)+            val valBytes = ByteArray(vEnd - vStart)+            vBlob.position(vStart)+            vBlob.get(valBytes)++            resultMap[String(keyBytes, Charsets.UTF_8)] = String(valBytes, Charsets.UTF_8)+        }++        return resultMap+    }++    private fun findIndexById(targetId: Long, n: Int, buf: MappedByteBuffer): Int {+        var low = 0+        var high = n - 1+        while (low <= high) {+            val mid = (low + high) ushr 1+            val midId = buf.getLong(mid * 8) // idBuffer starts at first ID, no header offset needed here+            when {+                midId < targetId -> low = mid + 1+                midId > targetId -> high = mid - 1+                else -> return mid             }         }-        val response = client.get("https://overpass-api.de/api/interpreter?data=[out:json];node($id);out;").body<JsonObject>()-        val tags = response["elements"]!!.jsonArray[0].jsonObject["tags"]!!.jsonObject.mapValues { it.value.jsonPrimitive.content }-        client.close()-        return tags+        return -1     } }\ No newline at end of file
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 49c44ed912..4955f41516 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -101,7 +101,7 @@ suspend fun parse(feature: Feature1): SpecificFeature? {             SpecificFeature.Admin1Label(wiki.getProperty("P300")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)         }         "restaurant", "fast_food", "cafe" -> {-            val tags = OSM.getTags(osmID)+            val tags = OSM.getTags(osmID.toLong())             println(properties)             println(tags)             SpecificFeature.Restaurant(tags["name"], tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) })@@ -114,8 +114,10 @@ suspend fun parse(feature: Feature1): SpecificFeature? { @Composable fun MapPage() {     var selectedFeature by remember { mutableStateOf<SpecificFeature?>(null) }+    val context = LocalContext.current      LaunchedEffect(Unit) {+        OSM.initialize(context)         outlineSource = GeoJsonSource("selected-country-geojson", GeoJsonData.Features(FeatureCollection1(listOf(             Feature1(Polygon(                 coordinates = listOf(