Modern Apps git

← Modern-Apps.git

maps: download DB instead of building

Commit
05eb71bfe68e592cbb32970b80e604ec19e2f4c3
Author
Vayun Mathur <[email protected]>
When
2026-02-10 08:20 UTC (9 months ago)
Parents
1321908

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 1564e113f5..0d82966a7e 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -7,12 +7,15 @@ import androidx.compose.runtime.collectAsState import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.Preferences+import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.byteArrayPreferencesKey+import androidx.datastore.preferences.core.doublePreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.launch@@ -45,6 +48,17 @@ class DataStoreUtils private constructor(context: Context) {         return stateMap[longPreferencesKey(name)] as Long?     } +    @Composable+    fun booleanFlow(name: String): Flow<Boolean> {+        return dataStore.data.mapNotNull { it[booleanPreferencesKey(name)] }+    }++    suspend fun setBoolean(name: String, value: Boolean) {+        dataStore.edit {+            it[booleanPreferencesKey(name)] = value+        }+    }+     @Composable     fun getLongState(name: String, default: Long = 0L): State<Long> {         return dataStore.data.mapNotNull { it[longPreferencesKey(name)] }.collectAsState(default)@@ -57,6 +71,16 @@ class DataStoreUtils private constructor(context: Context) {         }     } +    fun doubleFlow(string: String): Flow<Double> {+        return dataStore.data.mapNotNull { it[doublePreferencesKey(string)] }+    }++    suspend fun setDouble(string: String, progress: Double) {+        dataStore.edit {+            it[doublePreferencesKey(string)] = progress+        }+    }+     companion object {         @Volatile         private var instance: DataStoreUtils? = null
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 9292105000..f9ef17527f 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -12,6 +12,7 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button@@ -19,6 +20,7 @@ import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember@@ -26,6 +28,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.navigation3.runtime.NavKey import com.vayunmathur.library.ui.DynamicTheme@@ -33,7 +36,8 @@ import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.util.rememberNavBackStack-import com.vayunmathur.maps.data.TagDatabase+import com.vayunmathur.maps.data.AmenityDatabase+import com.vayunmathur.maps.data.buildAmenityDatabase import com.vayunmathur.maps.ui.DownloadedMapsPage import com.vayunmathur.maps.ui.MapPage import kotlinx.coroutines.async@@ -62,22 +66,42 @@ class MainActivity : ComponentActivity() {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         val ds = DataStoreUtils.getInstance(this)-        val db = buildDatabase<TagDatabase>();-        val localPath = ensurePmtilesReady(this)+        ensurePmtilesReady(this)         setContent {             DynamicTheme {-                val downloadedState by ds.getLongState("downloaded")-                val isDownloaded = downloadedState == 2L-                if(isDownloaded) {+                val dbSetup by ds.booleanFlow("dbSetupComplete").collectAsState(false)+                if(dbSetup) {+                    val db = remember { buildAmenityDatabase(this@MainActivity) }                     Navigation(ds, db)                 } else {-                    DownloadPage(ds, db)+                    DatabaseSetup(ds)                 }             }         }     } } +@Composable+fun DatabaseSetup(ds: DataStoreUtils) {+    val context = LocalContext.current+    val progress by ds.doubleFlow("downloadProgress").collectAsState(0.0)+    LaunchedEffect(Unit) {+        val id = downloadOsmData(context, "https://data.vayunmathur.com/amenities.db")+        while(progress != 1.0) {+            ds.setDouble("downloadProgress", getProgress(context, id))+            delay(100)+        }+        ds.setBoolean("dbSetupComplete", true)+    }+    Scaffold() { paddingValues ->+        Box(Modifier.padding(paddingValues).fillMaxSize(), contentAlignment = Alignment.Center) {+            Box(Modifier.padding(16.dp)) {+                Text((progress*100).toString())+            }+        }+    }+}+ @Serializable sealed interface Route: NavKey {     @Serializable@@ -87,7 +111,7 @@ sealed interface Route: NavKey { }  @Composable-fun Navigation(ds: DataStoreUtils, db: TagDatabase) {+fun Navigation(ds: DataStoreUtils, db: AmenityDatabase) {     val backStack = rememberNavBackStack<Route>(Route.MapPage)     val context = LocalContext.current     MainNavigation(backStack) {@@ -100,37 +124,6 @@ fun Navigation(ds: DataStoreUtils, db: TagDatabase) {     } } -@Composable-fun DownloadPage(ds: DataStoreUtils, db: TagDatabase) {-    val context = LocalContext.current-    val downloaded by ds.getLongState("downloaded")-    Scaffold() { paddingValues ->-        Box(Modifier.padding(paddingValues).fillMaxSize()) {-            if(downloaded == 0L) {-                Button({-                    downloadOsmData(context, "https://api.vayunmathur.com/maps/amenities", "https://api.vayunmathur.com/maps/search", ds)-                }, Modifier.align(Alignment.Center)) {-                    Text("Download")-                }-            } else {-                var progress by remember { mutableStateOf(0.0) }-                LaunchedEffect(Unit) {-                    val downloadID = ds.getLong("downloadID")!!-                    val downloadID2 = ds.getLong("downloadID2")!!-                    while(true) {-                        progress = getProgress(context, downloadID) + getProgress(context, downloadID2)-                        if(progress == 2.0) {-                            ds.setLong("downloaded", 2L)-                        }-                        delay(100)-                    }-                }-                Text("Downloading: ${progress/2*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)@@ -138,41 +131,48 @@ fun getProgress(context: Context, downloadId: Long): Double {         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, url1: String, url2: String, ds: DataStoreUtils) {+fun downloadOsmData(context: Context, url: String): Long {     val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager+    val fileName = "amenities.db" -    val request = DownloadManager.Request(url1.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)+    // 1. Check if the download is already in progress or completed+    val query = DownloadManager.Query()+    val cursor = downloadManager.query(query) +    if (cursor != null) {+        while (cursor.moveToNext()) {+            val title = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE))+            val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)) -    val request2 = DownloadManager.Request(url2.toUri())+            // Check by title or destination (Title is more reliable for filtering here)+            if (title == "OSM Data Update") {+                val id = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID))++                // If it's running, pending, or successful, return the existing ID+                if (status == DownloadManager.STATUS_RUNNING ||+                    status == DownloadManager.STATUS_PENDING ||+                    status == DownloadManager.STATUS_SUCCESSFUL) {+                    cursor.close()+                    return id+                }+            }+        }+        cursor.close()+    }++    // 2. If no active/completed download found, start a new one+    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, "names_only.bin")-        .setAllowedOverMetered(false) // Recommended for a 2.5GB file!+        .setDestinationInExternalFilesDir(context, null, fileName)+        .setAllowedOverMetered(false)         .setRequiresCharging(false) -    val downloadId = downloadManager.enqueue(request)-    val downloadId2 = downloadManager.enqueue(request2)--    runBlocking {-        ds.setLong("downloaded", 1L)-        ds.setLong("downloadID", downloadId)-        ds.setLong("downloadID2", downloadId2)-    }+    return downloadManager.enqueue(request) }\ 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.ktdeleted file mode 100644index d524ea9179..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/OSM.kt+++ /dev/null@@ -1,148 +0,0 @@-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 {-    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-            }-        }-        return -1-    }-}\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/OSM2.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/OSM2.kt b/maps/src/main/java/com/vayunmathur/maps/OSM2.ktdeleted file mode 100644index 685152e474..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/OSM2.kt+++ /dev/null@@ -1,90 +0,0 @@-package com.vayunmathur.maps--import android.content.Context-import android.util.Log-import androidx.room.withTransaction-import com.vayunmathur.library.util.DataStoreUtils-import com.vayunmathur.maps.data.NameSearchEntity-import com.vayunmathur.maps.data.TagDatabase-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext-import java.io.RandomAccessFile-import java.nio.ByteBuffer-import java.nio.ByteOrder-import java.nio.channels.FileChannel--object OSM2 {-    private lateinit var db: TagDatabase-    private const val TAG = "OSM_Search"--    fun init(context: Context, ds: DataStoreUtils, database: TagDatabase) {-        this.db = database--        CoroutineScope(Dispatchers.IO).launch {-            if(ds.getLong("searchIndex") != 1L) {-                Log.d(TAG, "Search index empty. Building from binary...")-                buildIndex(context)-                ds.setLong("searchIndex", 1L)-            }-            Log.d(TAG, "Search index ready.")-        }-    }--    suspend fun search(query: String): List<Long> = withContext(Dispatchers.IO) {-        if (query.isBlank()) return@withContext emptyList()-        db.searchDao().search(query)-    }--    private suspend fun buildIndex(context: Context) {-        val file = context.getExternalFilesDir(null)?.resolve("names_only.bin") ?: return-        if (!file.exists()) return--        withContext(Dispatchers.IO) {-            // 1. Configure the connection OUTSIDE the transaction-            val sdb = db.openHelper.writableDatabase-            sdb.query("PRAGMA journal_mode = WAL").close()-            sdb.query("PRAGMA synchronous = NORMAL").close()--            // 2. Now start the heavy lifting-            db.withTransaction {-                RandomAccessFile(file, "r").use { raf ->-                    val channel = raf.channel-                    channel.position(8) // Skip count header--                    val buffer = ByteBuffer.allocateDirect(1024 * 1024).order(ByteOrder.LITTLE_ENDIAN)-                    val batch = mutableListOf<NameSearchEntity>()--                    while (channel.read(buffer) != -1) {-                        buffer.flip()-                        while (buffer.remaining() >= 9) {-                            buffer.mark()-                            val nodeID = buffer.long-                            val nameLen = buffer.get().toInt() and 0xFF--                            if (buffer.remaining() >= nameLen) {-                                val nameBytes = ByteArray(nameLen)-                                buffer.get(nameBytes)-                                batch.add(NameSearchEntity(String(nameBytes), nodeID))--                                if (batch.size >= 10000) {-                                    db.searchDao().insertAll(batch)-                                    batch.clear()-                                }-                            } else {-                                buffer.reset()-                                break-                            }-                        }-                        buffer.compact()-                    }-                    if (batch.isNotEmpty()) db.searchDao().insertAll(batch)--                    // 3. Optimize FTS4 (Still inside transaction is fine for this)-                    sdb.execSQL("INSERT INTO name_search(name_search) VALUES('optimize')")-                }-            }-        }-    }-}\ No newline at end of file
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 d10d749976..a219f059ea 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/SpecificFeature.kt@@ -1,6 +1,5 @@ package com.vayunmathur.maps.data -import com.vayunmathur.maps.OSM import com.vayunmathur.maps.Wikidata import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive@@ -26,9 +25,8 @@ typealias Feature1 = Feature<Geometry, JsonObject?>  fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content -suspend fun parse(feature: Feature1): SpecificFeature? {+suspend fun parse(feature: Feature1, db: AmenityDatabase): SpecificFeature? {     val id = feature.id?.jsonPrimitive?.content?.toULong() ?: 0uL-    val osmID = id and ((1uL shl 44) - 1uL)     val geometry = feature.geometry     val properties = feature.properties ?: return null     return when(properties.string("kind")) {@@ -41,7 +39,7 @@ suspend fun parse(feature: Feature1): SpecificFeature? {             SpecificFeature.Admin1Label(wiki.getProperty("P300")!!, wiki.getWikipedia()!!, properties.string("name:en")!!)         }         "restaurant", "fast_food", "cafe", "bar" -> {-            val tags = OSM.getTags(osmID.toLong())+            val tags = db.tagDao().getTags(id.toLong()).associate { it.key to it.value }             println(properties)             println(tags)             SpecificFeature.Restaurant(tags["name"] ?: "", tags["phone"], tags["website"], tags["website:menu"], tags["opening_hours"]?.let { OpeningHours.from(it) }, (geometry as Point).coordinates)
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 bb151b262f..f9a3d65859 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt@@ -1,33 +1,74 @@ package com.vayunmathur.maps.data +import android.content.Context import androidx.room.ColumnInfo import androidx.room.Dao import androidx.room.Database import androidx.room.Entity import androidx.room.Fts4+import androidx.room.Index import androidx.room.Insert+import androidx.room.PrimaryKey import androidx.room.Query+import androidx.room.Room import androidx.room.RoomDatabase+import androidx.sqlite.db.SupportSQLiteDatabase+import androidx.sqlite.db.SupportSQLiteOpenHelper+import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory+import java.io.File -@Fts4(tokenizer = "unicode61")-@Entity(tableName = "name_search")-data class NameSearchEntity(-    @ColumnInfo(name = "value") val name: String,-    @ColumnInfo(name = "nodeID") val nodeID: Long+@Entity+data class AmenityTag(+    @ColumnInfo(index = true)+    val nodeID: Long,+    val key: String,+    val value: String,+    @PrimaryKey(autoGenerate = true) val id: Long = 0 )+ @Dao-interface SearchDao {+interface TagDao {     @Insert-    suspend fun insertAll(list: List<NameSearchEntity>)--    @Query("SELECT nodeID FROM name_search WHERE value MATCH :query || '*' LIMIT 50")-    suspend fun search(query: String): List<Long>+    suspend fun insert(tag: AmenityTag)+    @Insert+    suspend fun insertAll(tags: List<AmenityTag>)+    @Query("SELECT * FROM AmenityTag WHERE nodeID = :nodeID")+    suspend fun getTags(nodeID: Long): List<AmenityTag>+} -    @Query("SELECT COUNT(*) FROM name_search")-    suspend fun getCount(): Long+@Database(entities = [AmenityTag::class], version = 1)+abstract class AmenityDatabase : RoomDatabase() {+    abstract fun tagDao(): TagDao } -@Database(entities = [NameSearchEntity::class], version = 1)-abstract class TagDatabase : RoomDatabase() {-    abstract fun searchDao(): SearchDao+class DirectFileOpenHelperFactory(private val path: String) : SupportSQLiteOpenHelper.Factory {+    override fun create(configuration: SupportSQLiteOpenHelper.Configuration): SupportSQLiteOpenHelper {+        // We override the configuration name to be the absolute path+        val directConfig = SupportSQLiteOpenHelper.Configuration.builder(configuration.context)+            .name(path) // This is the secret sauce: use the absolute path as the name+            .callback(configuration.callback)+            .build()++        return FrameworkSQLiteOpenHelperFactory().create(directConfig)+    } }++fun buildAmenityDatabase(context: Context): AmenityDatabase {+    val dbFile = File(context.getExternalFilesDir(null), "amenities.db")++    return Room.databaseBuilder(+        context,+        AmenityDatabase::class.java,+        "amenities.db" // This name is ignored by our custom factory+    )+        .openHelperFactory(DirectFileOpenHelperFactory(dbFile.absolutePath))+        .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")+            }+        })+        .build()+}\ 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 eaf097021c..5c402b6dd2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -1,50 +1,27 @@ package com.vayunmathur.maps.ui -import android.content.Context import androidx.activity.compose.BackHandler import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.Canvas-import androidx.compose.foundation.background-import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.shape.CircleShape-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.foundation.verticalScroll import androidx.compose.material3.BottomSheetScaffold import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults-import androidx.compose.material3.CardElevation import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults-import androidx.compose.material3.MaterialTheme-import androidx.compose.material3.OutlinedTextField-import androidx.compose.material3.PrimaryTabRow import androidx.compose.material3.Scaffold-import androidx.compose.material3.SecondaryTabRow import androidx.compose.material3.SheetValue-import androidx.compose.material3.Surface-import androidx.compose.material3.Tab import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults@@ -61,57 +38,30 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.geometry.Size-import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.PaintingStyle.Companion.Stroke-import androidx.compose.ui.graphics.StrokeCap-import androidx.compose.ui.graphics.drawscope.DrawScope-import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource-import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp-import androidx.core.graphics.toColor-import androidx.core.graphics.toColorInt import androidx.navigation3.runtime.NavBackStack import com.vayunmathur.library.R import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.readLines-import com.vayunmathur.library.util.round-import com.vayunmathur.maps.CountryMap import com.vayunmathur.maps.FrameworkLocationManager-import com.vayunmathur.maps.OSM2-import com.vayunmathur.maps.OSM import com.vayunmathur.maps.Route import com.vayunmathur.maps.RouteService import com.vayunmathur.maps.TransitRoute-import com.vayunmathur.maps.Wikidata import com.vayunmathur.maps.ZoneDownloadManager-import com.vayunmathur.maps.data.OpeningHours+import com.vayunmathur.maps.data.AmenityDatabase import com.vayunmathur.maps.data.SpecificFeature-import com.vayunmathur.maps.data.TagDatabase import com.vayunmathur.maps.data.parse import com.vayunmathur.maps.ensurePmtilesReady import com.vayunmathur.maps.ui.components.BottomSheetContent import com.vayunmathur.maps.ui.components.MyMapLayers import com.vayunmathur.maps.ui.components.UserIcon import kotlinx.coroutines.launch-import kotlinx.datetime.LocalTime-import kotlinx.datetime.TimeZone-import kotlinx.datetime.format-import kotlinx.datetime.format.Padding-import kotlinx.datetime.toLocalDateTime import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray-import kotlinx.serialization.json.JsonElement-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonArray@@ -121,49 +71,22 @@ import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject import okio.source import org.maplibre.compose.camera.CameraPosition-import org.maplibre.compose.camera.CameraState import org.maplibre.compose.camera.rememberCameraState-import org.maplibre.compose.expressions.ast.Expression-import org.maplibre.compose.expressions.dsl.const-import org.maplibre.compose.expressions.dsl.convertToColor-import org.maplibre.compose.expressions.dsl.eq-import org.maplibre.compose.expressions.dsl.feature-import org.maplibre.compose.expressions.dsl.rem-import org.maplibre.compose.expressions.value.ExpressionValue-import org.maplibre.compose.expressions.value.IntValue-import org.maplibre.compose.expressions.value.LineCap-import org.maplibre.compose.expressions.value.StringValue-import org.maplibre.compose.layers.FillLayer-import org.maplibre.compose.layers.LineLayer import org.maplibre.compose.map.GestureOptions import org.maplibre.compose.map.MapOptions import org.maplibre.compose.map.MaplibreMap import org.maplibre.compose.map.OrnamentOptions import org.maplibre.compose.map.RenderOptions-import org.maplibre.compose.sources.GeoJsonData-import org.maplibre.compose.sources.GeoJsonOptions-import org.maplibre.compose.sources.GeoJsonSource import org.maplibre.compose.style.BaseStyle-import org.maplibre.compose.style.rememberStyleState import org.maplibre.compose.util.ClickResult-import org.maplibre.compose.util.MaplibreComposable-import org.maplibre.spatialk.geojson.Feature-import org.maplibre.spatialk.geojson.FeatureCollection-import org.maplibre.spatialk.geojson.Geometry-import org.maplibre.spatialk.geojson.LineString-import org.maplibre.spatialk.geojson.MultiPolygon-import org.maplibre.spatialk.geojson.Point-import org.maplibre.spatialk.geojson.PointGeometry-import org.maplibre.spatialk.geojson.Polygon import org.maplibre.spatialk.geojson.Position import sh.calvin.reorderable.ReorderableItem import sh.calvin.reorderable.rememberReorderableLazyListState import java.io.File-import kotlin.time.Duration  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun MapPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, db: TagDatabase) {+fun MapPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, db: AmenityDatabase) {     var selectedFeature by remember { mutableStateOf<SpecificFeature?>(null) }     val context = LocalContext.current     val coroutineScope = rememberCoroutineScope()@@ -231,13 +154,6 @@ fun MapPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, db: TagDatabase)         onDispose { locationManager.stopUpdates(listener) }     } -    LaunchedEffect(Unit) {-        OSM.initialize(context)-        OSM2.init(context, ds, db)-        // Debug search example-        println("SUBWAY SEARCH: ${OSM2.search("Galero Grill").map { OSM.getTags(it) }}")-    }-     var inactiveNavigation: SpecificFeature.Route? by remember { mutableStateOf(null) }      // --- ROUTE COMPUTATION ---@@ -310,7 +226,7 @@ fun MapPage(backStack: NavBackStack<Route>, ds: DataStoreUtils, db: TagDatabase)                                 listOf("${it}_base", "${it}_hybrid")                             }.toSet()) ?: emptyList()                             println("FEATURES: $features")-                            val listedFeatures = features.mapNotNull { parse(it) }+                            val listedFeatures = features.mapNotNull { parse(it, db) }                             println("LISTED FEATURES: $listedFeatures")                              listedFeatures.firstOrNull()?.let {