Modern Apps git

← Modern-Apps.git

maps: start working on search (it doesn't work yet)

Commit
2861a6e466f5068fd6b15ca8628a160d04b9b261
Author
Vayun Mathur <[email protected]>
When
2026-02-05 03:53 UTC (10 months ago)
Parents
64725c5

Diff

maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 52e005af55..96cf728e77 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -1,3 +1,7 @@+plugins {+    alias(libs.plugins.ksp)+}+ android {     defaultConfig {         applicationId = "com.vayunmathur.maps"@@ -16,4 +20,9 @@ dependencies {     implementation(libs.ktor.serialization.kotlinx.json)      implementation("org.wololo:flatgeobuf:3.28.2")++    // room+    implementation(libs.androidx.room.runtime)+    implementation(libs.androidx.room.ktx)+    ksp(libs.androidx.room.compiler) }\ No newline at end of file
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 f8e0262cc1..527932bf93 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -29,6 +29,8 @@ 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.library.util.buildDatabase+import com.vayunmathur.maps.data.TagDatabase import com.vayunmathur.maps.ui.MapPage import kotlinx.coroutines.async import kotlinx.coroutines.delay@@ -39,14 +41,15 @@ class MainActivity : ComponentActivity() {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         val ds = DataStoreUtils.getInstance(this)+        val db = buildDatabase<TagDatabase>();         setContent {             DynamicTheme {                 val downloadedState by ds.getLongState("downloaded")                 val isDownloaded = downloadedState == 2L                 if(isDownloaded) {-                    MapPage()+                    MapPage(ds, db)                 } else {-                    DownloadPage(ds)+                    DownloadPage(ds, db)                 }             }         }@@ -54,38 +57,14 @@ class MainActivity : ComponentActivity() { }  @Composable-fun DownloadPage(ds: DataStoreUtils) {+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({-                    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)+                    downloadOsmData(context, "https://api.vayunmathur.com/maps/amenities", "https://api.vayunmathur.com/maps/search", ds)                 }, Modifier.align(Alignment.Center)) {                     Text("Download")                 }@@ -93,15 +72,16 @@ fun DownloadPage(ds: DataStoreUtils) {                 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)-                        if(progress == 1.0) {+                        progress = getProgress(context, downloadID) + getProgress(context, downloadID2)+                        if(progress == 2.0) {                             ds.setLong("downloaded", 2L)                         }                         delay(100)                     }                 }-                Text("Downloading: ${progress*100}%", Modifier.align(Alignment.Center))+                Text("Downloading: ${progress/2*100}%", Modifier.align(Alignment.Center))             }         }     }@@ -121,10 +101,10 @@ fun getProgress(context: Context, downloadId: Long): Double {     return 0.0 } -fun downloadOsmData(context: Context, url: String, ds: DataStoreUtils) {+fun downloadOsmData(context: Context, url1: String, url2: String, ds: DataStoreUtils) {     val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager -    val request = DownloadManager.Request(url.toUri())+    val request = DownloadManager.Request(url1.toUri())         .setTitle("OSM Data Update")         .setDescription("Downloading 2.5GB tag database...")         .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)@@ -133,10 +113,22 @@ fun downloadOsmData(context: Context, url: String, ds: DataStoreUtils) {         .setAllowedOverMetered(false) // Recommended for a 2.5GB file!         .setRequiresCharging(false) ++    val request2 = DownloadManager.Request(url2.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!+        .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)     } }\ 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.ktnew file mode 100644index 0000000000..685152e474--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/OSM2.kt@@ -0,0 +1,90 @@+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/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.ktnew file mode 100644index 0000000000..bb151b262f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/data/Tag.kt@@ -0,0 +1,33 @@+package com.vayunmathur.maps.data++import androidx.room.ColumnInfo+import androidx.room.Dao+import androidx.room.Database+import androidx.room.Entity+import androidx.room.Fts4+import androidx.room.Insert+import androidx.room.Query+import androidx.room.RoomDatabase++@Fts4(tokenizer = "unicode61")+@Entity(tableName = "name_search")+data class NameSearchEntity(+    @ColumnInfo(name = "value") val name: String,+    @ColumnInfo(name = "nodeID") val nodeID: Long+)+@Dao+interface SearchDao {+    @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>++    @Query("SELECT COUNT(*) FROM name_search")+    suspend fun getCount(): Long+}++@Database(entities = [NameSearchEntity::class], version = 1)+abstract class TagDatabase : RoomDatabase() {+    abstract fun searchDao(): SearchDao+}
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 a1aaa4536c..42006daeb5 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -64,15 +64,18 @@ import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.core.graphics.toColor import androidx.core.graphics.toColorInt+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.RouteService import com.vayunmathur.maps.TransitRoute import com.vayunmathur.maps.Wikidata import com.vayunmathur.maps.data.OpeningHours+import com.vayunmathur.maps.data.TagDatabase import kotlinx.coroutines.launch import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone@@ -163,7 +166,7 @@ suspend fun parse(feature: Feature1): SpecificFeature? {  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun MapPage() {+fun MapPage(ds: DataStoreUtils, db: TagDatabase) {     var selectedFeature by remember { mutableStateOf<SpecificFeature?>(null) }     val context = LocalContext.current @@ -184,6 +187,11 @@ fun MapPage() {      LaunchedEffect(Unit) {         OSM.initialize(context)+        OSM2.init(context, ds,db)+        println("SUBWAY SEARCH")+        println(OSM2.search("Galero Grill").map{+            OSM.getTags(it)+        })         outlineSource = GeoJsonSource("selected-country-geojson", GeoJsonData.Features(             Feature1(Polygon(                 coordinates = listOf(