Modern Apps git

← Modern-Apps.git

maps: search rows show "City, State, Country" from the archive (#mapsearch)

Commit
f7e4bdd2d79b9b00c4e563ff98199c4d5dd7491f
Author
Vayun Mathur <[email protected]>
When
2026-11-13 20:58 UTC (22 days ago)
Parents
1993301
Owner request: every search result row shows trailing text with the
place's locality — "City, State, Country", state only where present —
from the archive's boundary data, never a network call, cheap.

Reader (PoiIndexAdmin.kt):
* poi_admin.bin (archive kind 16, written by poi_extract, packed by
  mamaps_pack — previous two commits) is mapped by PoiArchive like the
  other POI sections (and from side files), validated (PAD1, version 1,
  header + entries + pool fit) and degrades as absent when malformed.
* A row's locality walks its poi_region boundary up the parent chain:
  city = first level 5-8 boundary on the way up (a level 9-10 district
  such as a Paris arrondissement yields to the city above it), state =
  the level-4 boundary (level 3 where a country has no level 4),
  country = level 2; consecutive repeats dropped. `name:en` is used
  when the device language is English and the boundary has one
  ("Cologne, Germany"), the local name otherwise. Binary search over
  fixed 32-byte entries, at most 16 parents (a corrupt cycle cannot
  spin).
* Without the section — planet4, which predates it — only the city can
  be derived: the POI's own addr:city, else the addr:city most POIs of
  the same boundary nearby agree on (a 1-4 km grid poll, 4,000 records
  max). Not the boundary's place label: neighbourhood labels link to
  the city boundary that contains them too, so near Union Square "the
  label with SF's id" came back "Castro District" and near the Louvre
  "Vaugirard" when tried.
* Cached per boundary (and language) per archive mapping, bounded; a
  page of 20 rows sharing a city costs one walk.

UI: SearchResult gains `locality`; the ViewModel resolves it for the
returned rows on the search lane (off the main thread) and drops the
city when a place label's own name would repeat it. SearchSheet shows
it as the ListItem's trailing text (bodySmall, onSurfaceVariant, end-
aligned, max 150 dp / 2 lines + ellipsis so it never squeezes the
name). The store-listing search preview (MetadataPreviews) shows it.

Measured on the planet archive (no kind 16): SF "pizza" rows all
"San Francisco", Paris "cafe" "Paris", NYC "New York", London
"London"; 20 rows resolve in ~7 ms cold-JVM, ~0.2 ms cached. With a
real poi_admin.bin (poi_extract over california-latest.osm.pbf:
867 boundaries, 38.5 KB) the same code yields "San Francisco,
California", "Los Angeles, California", "Sacramento, California" (the
US relation does not assemble from a state extract; on the planet it
adds ", United States", as the synthetic-PBF test in osm_ingest pins).

Also: PoiIndex.kt drops an orphaned KDoc for helpers that moved to
PoiIndexWords.kt and tightens two search docs, bringing it back under
the 800-line FileLength limit (the cancel-token and engine commits had
taken it to 806); maps/AGENTS.md lists the new search files.

Tests: PoiIndexAdminTest (Austin/Texas/US walk skipping district and
county, state only where present incl. level-3 fallback, name:en
preference, unknown boundary + parent cycle, joinLocality, malformed
table refused); PoiArchiveTest "region and admin sections give a
locality line" maps kinds 15 + 16 from a hand-built .mamaps.

Diff

maps/AGENTS.md
diff --git a/maps/AGENTS.md b/maps/AGENTS.mdindex f1dc9daad8..7c8ef97d41 100644--- a/maps/AGENTS.md+++ b/maps/AGENTS.md@@ -168,6 +168,9 @@ _Install: ./install maps (dev by default)._ - com/vayunmathur/maps/util/PoiIndexSpatial.kt - com/vayunmathur/maps/util/PoiIndexWords.kt - com/vayunmathur/maps/util/PoiIndexRegion.kt — `poi_region` (kind 15) boundary links+- com/vayunmathur/maps/util/PoiIndexAdmin.kt — `poi_admin` (kind 16) hierarchy; search-row locality ("City, State, Country")+- com/vayunmathur/maps/util/PoiSearchEngine.kt — indexed name search (ordinal scans + grid join, blended text/distance rank)+- com/vayunmathur/maps/util/PoiSearchHits.kt — ordinal hit table for the search engine - com/vayunmathur/maps/util/PoiArchive.kt — POI sections out of the archive (per-section mmaps; planet is ~80 GB) - com/vayunmathur/maps/util/PoiCategories.kt - com/vayunmathur/maps/util/SpatialKey.kt
maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.ktindex 5a144f6a39..ccd7a0a525 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchSheet.kt@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable@@ -20,6 +21,8 @@ import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.EmptyState@@ -52,6 +55,9 @@ import com.vayunmathur.maps.util.SearchUiState  */ private val StatusBlockHeight = 120.dp +/** Widest the trailing locality text may grow before it wraps (two lines, then ellipsis). */+private val LocalityMaxWidth = 150.dp+ /**  * Search, as a sheet over the live map.  *@@ -155,6 +161,22 @@ private fun ResultsList(results: List<SearchResult>, actions: SearchActions) {                             ?: stringResource(R.string.coordinates, result.lat.round(4), result.lon.round(4))                     )                 },+                // Where the place is, so two same-named rows (every "Starbucks") can be told+                // apart at a glance. Capped in width and lines so a long "City, State,+                // Country" never squeezes the name itself.+                trailingContent = result.locality?.let { locality ->+                    {+                        Text(+                            locality,+                            modifier = Modifier.widthIn(max = LocalityMaxWidth),+                            style = MaterialTheme.typography.bodySmall,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                            textAlign = TextAlign.End,+                            maxLines = 2,+                            overflow = TextOverflow.Ellipsis,+                        )+                    }+                },                 modifier = Modifier.clickable { actions.selectResult(result) },             )             HorizontalDivider(Modifier.padding(horizontal = Spacing.lg))
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 3543c245ec..2d5d767c0a 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapsSearchViewModel.kt@@ -22,6 +22,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.library.util.DataStoreUtils+import java.util.Locale  /** The recency/favorites boost for one search; reads are in-memory, call off the main thread. */ private fun Application.searchBoost(): Map<String, Double> =@@ -49,6 +50,12 @@ data class SearchResult(      * masks without an admin-label upgrade round-trip.      */     val regionId: Long = 0L,+    /**+     * "City, State, Country" (state only where the archive has one), shown as the row's+     * trailing text; null when the archive cannot say. From the archive's boundary data,+     * never the network — see PoiIndexAdmin.kt.+     */+    val locality: String? = null, )  /**@@ -88,7 +95,7 @@ internal fun buildSearchBoost(     return boost } -private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult(+private fun PoiIndex.PoiRecord.toSearchResult(locality: String?) = SearchResult(     id = "poi:$latE7:$lonE7:${name.hashCode()}",     title = name,     subtitle = PoiCategories.label(type),@@ -96,6 +103,9 @@ private fun PoiIndex.PoiRecord.toSearchResult() = SearchResult(     lon = lon,     category = PoiCategories.label(type),     regionId = regionId,+    // A place label's locality starts with its own name ("Oakland" -> "Oakland, California, …");+    // the row already says it.+    locality = locality?.removePrefix("$name, ")?.takeUnless { it == name }, )  /**@@ -201,8 +211,7 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati                 // Offline OSM POI index only (P27). Addresses are not carried by                 // the index, so they resolve to empty. Any offline failure                 // (unmapped/poisoned index, decode error) is swallowed to empty.-                val offline = withContext(searchLane) { offlineSearch(query, nearLat, nearLon) }-                _results.value = offline.map { it.toSearchResult() }+                _results.value = withContext(searchLane) { offlineSearch(query, nearLat, nearLon) }             } finally {                 // `finally` because cancellation is the normal exit: every keystroke cancels                 // the previous job, and a cancelled search that never clears this flag leaves@@ -232,7 +241,6 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati         searchJob?.cancel()         searchJob = viewModelScope.launch {             val results = withContext(searchLane) { offlineSearch(query, nearLat, nearLon) }-                .map { it.toSearchResult() }             _results.value = results             onFirst(results.firstOrNull())         }@@ -280,22 +288,24 @@ class MapsSearchViewModel(application: Application) : AndroidViewModel(applicati     }      /**-     * The offline index search, run on [searchLane]. Any offline failure (unmapped/poisoned-     * index, decode error) is swallowed to empty; a cancelled caller makes it return early.+     * The offline index search plus each row's locality, run on [searchLane]. Any offline+     * failure (unmapped/poisoned index, decode error) is swallowed to empty; a cancelled+     * caller makes it return early.      */     private suspend fun offlineSearch(         query: String,         nearLat: Double,         nearLon: Double,-    ): List<PoiIndex.PoiRecord> {+    ): List<SearchResult> {         val app = getApplication<Application>()         val context = currentCoroutineContext()+        val english = Locale.getDefault().language == Locale.ENGLISH.language         return runCatching {             PoiIndex.initialize(app)             PoiIndex.searchByName(                 query, nearLat, nearLon, limit = 20, boost = app.searchBoost(),                 cancelled = { !context.isActive },-            )+            ).map { it.toSearchResult(PoiIndex.localityAt(it.ordinal, english)) }         }.getOrDefault(emptyList())     } 
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 ec68a4295c..e418e16017 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiArchive.kt@@ -11,9 +11,9 @@ import java.nio.channels.FileChannel /**  * Load the POI side files out of a single-archive `.mamaps` file.  *- * The archive carries the same six payloads as the side files (`poi_index`,+ * The archive carries the same payloads as the side files (`poi_index`,  * `poi_names`, and the optional `poi_attrs` / `poi_spatial` / `poi_name_index`- * / `poi_region` sections, kinds 8-12 and 15) after the tile data, each 8-byte aligned and named by+ * / `poi_region` / `poi_admin` sections, kinds 8-12, 15 and 16) after the tile data, each 8-byte aligned and named by  * the section directory + `MAMA8` footer. This reads the container (tile  * header, footer, directory) with positional reads, maps each POI section on  * its own, then runs the same validators the multi-file path runs@@ -71,6 +71,7 @@ object PoiArchive {     const val KIND_SPATIAL = 11     const val KIND_WORDS = 12     const val KIND_REGION = 15+    const val KIND_ADMIN = 16      /** Tile-header offsets this needs: `build_id` at 16, `file_len` at 24. */     private const val HEADER_BUILD_ID_OFF = 16@@ -190,7 +191,8 @@ object PoiArchive {             ?.let { PoiIndex.nameIndexFromBuffer(it, count) }         val region = overrideOrBase(overrides, KIND_REGION, sections, whole)             ?.let { regionFromBuffer(it, count) }-        return mappedOf(indexBuf, namesBuf, count, attrs, grid, words, region)+        val admin = overrideOrBase(overrides, KIND_ADMIN, sections, whole)?.let { adminFromBuffer(it) }+        return mappedOf(indexBuf, namesBuf, count, attrs, grid, words, region, admin)     }      /** The [PoiIndex.Mapped] for already-validated section buffers (absent ones degrade). */@@ -203,6 +205,7 @@ object PoiArchive {         grid: PoiIndex.Grid?,         words: Pair<MappedByteBuffer, Int>?,         region: MappedByteBuffer?,+        admin: AdminTable?,     ): PoiIndex.Mapped {         return PoiIndex.Mapped(             index = indexBuf,@@ -220,11 +223,12 @@ object PoiArchive {             nameIdx = words?.first,             entryCount = words?.second ?: 0,             region = region,+            admin = admin,         ).also {             Log.debug(                 TAG,                 "Loaded $count POI records from archive, " +-                    "grid=${it.cellCount} cells, words=${it.entryCount}",+                    "grid=${it.cellCount} cells, words=${it.entryCount}, admin=${admin?.count ?: 0}",             )         }     }
maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktindex bef99762c5..335c7e4912 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -106,18 +106,8 @@ object PoiIndex {     private const val NAME_INDEX_ENTRY_COUNT_OFF = 12     private const val NAME_INDEX_ENTRY_BYTES = 5L -    /**-     * ASCII-only lowercase, and deliberately not [Char.lowercase].-     *-     * `poi_name_index.bin` is sorted by the writer, so the reader has to reproduce that-     * order byte for byte. Rust's `to_lowercase` and Kotlin's `lowercase` do not agree on-     * every input, and here a disagreement is a POI that can never be found. See the-     * cross-language contract in `osm_ingest/src/poi_side.rs`.-     */-    // Attribute key constants and record decoding live in PoiIndexAttrs.kt.--    // asciiLower / isAsciiSpace / queryKey moved to PoiIndexWords.kt as shared-    // internal helpers (asciiLowerW etc. were duplicates of these).+    // Attribute keys/decoding live in PoiIndexAttrs.kt; the ASCII fold the word index is+    // sorted by (asciiLowerW, poiQueryKey) in PoiIndexWords.kt.      /** A single POI resolved from the index. */     data class PoiRecord(@@ -211,7 +201,12 @@ object PoiIndex {         internal val entryCount: Int = 0,         /** The region sidecar, or null when absent or mismatched. */         internal val region: MappedByteBuffer? = null,+        /** The boundary hierarchy (`poi_admin.bin`, archive kind 16), or null when absent. */+        internal val admin: AdminTable? = null,     ) {+        /** Locality lines already resolved, per boundary (see PoiIndexAdmin.kt). */+        internal val localityCache = LocalityCache()+         internal fun latE7(i: Int): Int = index.getInt(i * RECORD_BYTES)         internal fun lonE7(i: Int): Int = index.getInt(i * RECORD_BYTES + LON_FIELD_OFF)         internal fun nameOff(i: Int): Int = index.getInt(i * RECORD_BYTES + NAME_OFF_FIELD_OFF)@@ -632,11 +627,9 @@ object PoiIndex {      *      * Two implementations, picked by whether `poi_name_index.bin` was mapped:      *-     *  * **Indexed** — binary search to each token's range in the word-sorted index, then-     *    sequential scans of those ranges' ordinal arrays joined against the spatial grid-     *    around the bias point, so the cost is a few hundred page reads and names are-     *    decoded only for the rows returned (see PoiSearchEngine.kt). Because every word-     *    of a name is indexed, "pizza" still finds "Joe's Pizza".+     *  * **Indexed** — token ranges in the word index, scanned as ordinals and joined with+     *    the grid around the bias point; names decoded only for returned rows (see+     *    PoiSearchEngine.kt). Every word is indexed, so "pizza" finds "Joe's Pizza".      *  * **Scan** — the name pool, then every record. Two passes whose cost is the whole      *    dataset, kept only because the side file is optional.      *@@ -652,9 +645,8 @@ object PoiIndex {      * recents + saved places — earn distance credit); the scan fallback keeps      * rank-then-distance. [boost] never resurrects a non-match.      *-     * [cancelled] is polled between phases: a caller whose result is no longer wanted (the-     * user typed another character) gets an empty list back early instead of the lookup-     * running to completion beside its successor.+     * [cancelled] is polled during the search: a superseded caller (the user typed another+     * character) gets an empty list back early rather than running beside its successor.      */     @Suppress("LongParameterList") // query + bias point + limit + ranking signal + cancel token     fun searchByName(
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAdmin.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAdmin.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAdmin.ktnew file mode 100644index 0000000000..f6be25eb87--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexAdmin.kt@@ -0,0 +1,270 @@+package com.vayunmathur.maps.util++import com.vayunmathur.library.log.Log+import java.nio.ByteOrder+import java.nio.MappedByteBuffer++/**+ * The locality line of a search row — "City, State, Country" — from the archive alone.+ *+ * Two sources, best first:+ *+ *  * **`poi_admin.bin`** (archive kind 16, `osm_ingest/src/poi_admin.rs`): for every boundary+ *    a POI links to in `poi_region.bin`, and every boundary above it, the name, `name:en`,+ *    `admin_level` and parent. A row's locality is its own boundary walked up to the country:+ *    the city is the first level 5-8 boundary on the way up (a level 9-10 district such as a+ *    Paris arrondissement is skipped in favour of the city above it), the state the level-4+ *    boundary (level 3 where a country has no level 4), the country level 2.+ *  * **Without it** (planet4 predates the section) only the city can be derived: the POI's+ *    own `addr:city`, else the `addr:city` most POIs of the same boundary nearby agree on.+ *+ * Results are cached per boundary (the rows of one search nearly all share a handful), so a+ * page of 20 rows costs a few binary searches and no scan. Everything here is a mapped-file+ * read: call it off the main thread.+ */++/** `poi_admin.bin`, validated (see [adminFromBuffer]). */+internal class AdminTable(val buf: MappedByteBuffer, val count: Int, private val poolStart: Int, poolLen: Int) {+    private val poolEnd = poolStart + poolLen++    /** Entry index of [tagged], or -1. Entries are sorted ascending by tagged id. */+    fun find(tagged: Long): Int {+        var lo = 0+        var hi = count - 1+        while (lo <= hi) {+            val mid = (lo + hi) ushr 1+            val v = buf.getLong(entryAt(mid))+            when {+                v < tagged -> lo = mid + 1+                v > tagged -> hi = mid - 1+                else -> return mid+            }+        }+        return -1+    }++    fun parent(i: Int): Long = buf.getLong(entryAt(i) + PARENT_OFF)++    fun level(i: Int): Int = buf.get(entryAt(i) + LEVEL_OFF).toInt() and BYTE_MASK++    /** The entry's `name:en` when [english] and present, else its `name`; null when empty. */+    fun name(i: Int, english: Boolean): String? {+        val en = if (english) buf.getInt(entryAt(i) + NAME_EN_OFF) else NO_NAME+        val own = buf.getInt(entryAt(i) + NAME_OFF)+        return poolString(if (en != NO_NAME) en else own) ?: poolString(own)+    }++    private fun entryAt(i: Int): Int = HEADER_BYTES + ENTRY_BYTES * i++    private fun poolString(off: Int): String? {+        if (off < 0 || poolStart + off >= poolEnd) return null+        var end = poolStart + off+        while (end < poolEnd && buf.get(end).toInt() != 0) end+++        val n = end - poolStart - off+        if (n <= 0) return null+        val bytes = ByteArray(n)+        val dup = buf.duplicate()+        dup.position(poolStart + off)+        dup.get(bytes, 0, n)+        return String(bytes, Charsets.UTF_8)+    }++    internal companion object {+        const val HEADER_BYTES = 16+        const val ENTRY_BYTES = 32+        const val PARENT_OFF = 8+        const val NAME_OFF = 16+        const val NAME_EN_OFF = 20+        const val LEVEL_OFF = 24+        const val NO_NAME = -1+        const val BYTE_MASK = 0xFF+    }+}++const val ADMIN_FILE = "poi_admin.bin"++private const val TAG = "PoiIndex"+private val ADMIN_MAGIC = byteArrayOf('P'.code.toByte(), 'A'.code.toByte(), 'D'.code.toByte(), '1'.code.toByte())+private const val ADMIN_VERSION = 1+private const val ADMIN_COUNT_OFF = 8+private const val ADMIN_NAMES_LEN_OFF = 12+private const val ADMIN_VERSION_OFF = 4++/** The admin sidecar as an [AdminTable], or null when it is malformed (it then degrades as absent). */+internal fun adminFromBuffer(buf: MappedByteBuffer): AdminTable? {+    buf.order(ByteOrder.LITTLE_ENDIAN)+    return runCatching { readAdmin(buf) }.getOrElse { PoiIndex.bufferFailure(it, ADMIN_FILE) }+}++private fun readAdmin(buf: MappedByteBuffer): AdminTable? {+    if (buf.capacity() < AdminTable.HEADER_BYTES || ADMIN_MAGIC.indices.any { buf.get(it) != ADMIN_MAGIC[it] }) {+        Log.status(TAG, "$ADMIN_FILE has the wrong magic; ignoring it")+        return null+    }+    if (buf.getInt(ADMIN_VERSION_OFF) != ADMIN_VERSION) {+        Log.status(TAG, "$ADMIN_FILE version ${buf.getInt(ADMIN_VERSION_OFF)} unsupported; ignoring it")+        return null+    }+    val count = buf.getInt(ADMIN_COUNT_OFF)+    val namesLen = buf.getInt(ADMIN_NAMES_LEN_OFF)+    val poolStart = AdminTable.HEADER_BYTES.toLong() + AdminTable.ENTRY_BYTES.toLong() * count+    if (count < 0 || namesLen < 0 || poolStart + namesLen > buf.capacity()) {+        Log.status(TAG, "$ADMIN_FILE is truncated; ignoring it")+        return null+    }+    return AdminTable(buf, count, poolStart.toInt(), namesLen)+}++/** Admin levels: the band a city sits in, the state levels, and the country. */+private const val CITY_MIN_LEVEL = 5+private const val CITY_MAX_LEVEL = 8+private const val STATE_LEVEL = 4+private const val REGION_LEVEL = 3+private const val COUNTRY_LEVEL = 2++/** Cache-key bit for local-name walks (see [adminLocality]). */+private const val LOCAL_NAME_KEY_BIT = 1L shl 62++/** Parents followed at most (a corrupt cycle must not spin). */+private const val MAX_CHAIN = 16++/** Boxes (half-size, km) polled for a boundary's addresses, the votes wanted, the records read at most. */+private val CITY_BOX_KM = doubleArrayOf(1.0, 4.0)+private const val CITY_VOTES = 25+private const val CITY_VISIT_BUDGET = 4_000+private const val KM_PER_DEGREE = 111.32+private const val E7_PER_DEGREE = 1e7+private const val MIN_COS_LAT = 1e-6++/** Per-archive cache of boundary -> locality text, bounded. */+internal class LocalityCache {+    private val map = LinkedHashMap<Long, String>(CAPACITY, LOAD, true)+    private val none = HashSet<Long>()++    /** The cached text, "" for "known to have none", or null when not cached. */+    @Synchronized+    fun get(key: Long): String? = map[key] ?: if (key in none) "" else null++    @Synchronized+    fun put(key: Long, value: String?) {+        if (value == null) {+            if (none.size >= CAPACITY) none.clear()+            none.add(key)+        } else {+            if (map.size >= CAPACITY) map.remove(map.keys.first())+            map[key] = value+        }+    }++    private companion object {+        const val CAPACITY = 512+        const val LOAD = 0.75f+    }+}++/**+ * "City, State, Country" for POI [ordinal] (state only where a level-4/3 boundary exists),+ * or null when nothing is known. [english] prefers `name:en` over the local name.+ */+internal fun PoiIndex.localityAt(ordinal: Int, english: Boolean): String? {+    val m = mappedForQuery() ?: return null+    if (ordinal !in 0 until m.count) return null+    val region = m.regionId(ordinal)+    return m.adminLocality(region, english)+        // No hierarchy (or none for this boundary): the city alone, from the POI's own+        // address or the one its boundary's other POIs agree on.+        ?: attributesAt(ordinal)?.city?.takeIf { it.isNotBlank() }+        ?: m.cachedBoundaryCity(region, ordinal)+}++/** The cached hierarchy walk for [region], or null without a table or a hit. */+private fun PoiIndex.Mapped.adminLocality(region: Long, english: Boolean): String? {+    val table = admin+    if (table == null || region == REGION_NONE) return null+    // Tagged ids stay below 2^62 (60-bit OSM ids << 2), so the three key spaces are disjoint:+    // English walks negative, local-name walks at 2^62 and up, the fallback the plain id.+    val key = if (english) region.inv() else region or LOCAL_NAME_KEY_BIT+    localityCache.get(key)?.let { cached -> return cached.ifEmpty { null } }+    return table.localityOf(region, english).also { localityCache.put(key, it) }+}++/** [boundaryCity] for [region] around POI [ordinal], cached per boundary. */+private fun PoiIndex.Mapped.cachedBoundaryCity(region: Long, ordinal: Int): String? {+    if (region == REGION_NONE) return null+    localityCache.get(region)?.let { cached -> return cached.ifEmpty { null } }+    return boundaryCity(region, latE7(ordinal), lonE7(ordinal)).also { localityCache.put(region, it) }+}++/** The hierarchy walk for boundary [tagged]; see the file comment for the level rules. */+internal fun AdminTable.localityOf(tagged: Long, english: Boolean): String? {+    var city: String? = null+    var deepest: String? = null+    var state: String? = null+    var region: String? = null+    var country: String? = null+    var at = find(tagged)+    var steps = 0+    while (at >= 0 && steps < MAX_CHAIN) {+        val level = level(at)+        val name = name(at, english)+        when {+            level == COUNTRY_LEVEL -> country = country ?: name+            level == REGION_LEVEL -> region = region ?: name+            level == STATE_LEVEL -> state = state ?: name+            level in CITY_MIN_LEVEL..CITY_MAX_LEVEL -> city = city ?: name+            level > CITY_MAX_LEVEL -> deepest = deepest ?: name+        }+        val parent = parent(at)+        at = if (parent == REGION_NONE) -1 else find(parent)+        steps+++    }+    return joinLocality(city ?: deepest, state ?: region, country)+}++/** The non-blank parts joined with ", ", consecutive repeats dropped ("Singapore, Singapore"). */+internal fun joinLocality(vararg parts: String?): String? {+    val out = ArrayList<String>()+    for (p in parts) {+        val s = p?.trim()+        if (!s.isNullOrEmpty() && out.lastOrNull() != s) out.add(s)+    }+    return out.joinToString(", ").ifEmpty { null }+}++/**+ * The city most POIs linked to boundary [tagged] around ([latE7], [lonE7]) give in their own+ * `addr:city`, or null.+ *+ * Not the boundary's place label: neighbourhood labels (place=suburb/neighbourhood) link to+ * the city boundary that contains them too, so "the label with this boundary id" near Union+ * Square is as likely to be "Castro District" as "San Francisco". The addresses of the POIs+ * around it agree on the city instead. Reads each nearby record's link (region section) and,+ * for linked ones, its attributes, under a budget; cached per boundary by the caller.+ */+private fun PoiIndex.Mapped.boundaryCity(tagged: Long, latE7: Int, lonE7: Int): String? {+    val lat = latE7 / E7_PER_DEGREE+    val lon = lonE7 / E7_PER_DEGREE+    val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(MIN_COS_LAT)+    val votes = HashMap<String, Int>()+    var voters = 0+    var visited = 0+    for (half in CITY_BOX_KM) {+        val dLat = half / KM_PER_DEGREE+        val dLon = half / (KM_PER_DEGREE * cosLat)+        forEachGridOrdinal(+            ((lat - dLat) * E7_PER_DEGREE).toInt(), ((lat + dLat) * E7_PER_DEGREE).toInt(),+            ((lon - dLon) * E7_PER_DEGREE).toInt(), ((lon + dLon) * E7_PER_DEGREE).toInt(),+        ) { o ->+            visited+++            if (regionId(o) == tagged) {+                PoiIndex.attributesAt(o)?.city?.trim()?.takeIf { it.isNotEmpty() }?.let {+                    votes[it] = (votes[it] ?: 0) + 1+                    voters+++                }+            }+            voters < CITY_VOTES && visited < CITY_VISIT_BUDGET+        }+        if (voters >= CITY_VOTES || visited >= CITY_VISIT_BUDGET) break+    }+    return votes.maxByOrNull { it.value }?.key+}
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.ktindex dfc73b6b15..cb533070f3 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSideFiles.kt@@ -25,6 +25,7 @@ internal object PoiIndexSideFiles {         val grid = openSpatial(File(dir, PoiIndex.SPATIAL_FILE), count)         val words = openNameIndex(File(dir, PoiIndex.NAME_INDEX_FILE), count)         val region = openRegion(File(dir, REGION_FILE), count)+        val admin = File(dir, ADMIN_FILE).takeIf { it.isFile }?.let { adminFromBuffer(PoiIndex.mapReadOnly(it)) }         return PoiIndex.Mapped(             index = indexBuf,             names = namesBuf,@@ -41,6 +42,7 @@ internal object PoiIndexSideFiles {             nameIdx = words?.first,             entryCount = words?.second ?: 0,             region = region,+            admin = admin,         )     } 
maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt
diff --git a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.ktindex a24991ee08..9852514d86 100644--- a/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt+++ b/maps/src/screenshotTest/kotlin/com/vayunmathur/maps/ui/MetadataPreviews.kt@@ -30,6 +30,9 @@ private const val PHONE = "spec:width=411dp,height=891dp,dpi=420" /** Desktop-shaped: exercises the side panel at a width where map and panel sit side by side. */ private const val EXPANDED = "spec:width=1280dp,height=800dp,dpi=240" +/** The locality line the search preview rows show (from poi_admin on a device). */+private const val SF_LOCALITY = "San Francisco, California, United States"+ /**  * Store listing images for `:maps`. See `common-conventions-preview-metadata`.  *@@ -93,10 +96,10 @@ class MetadataPreviews {                         SearchUiState(                             query = "ferry",                             results = listOf(-                                SearchResult("1", "Ferry Building Marketplace", "1 Ferry Building, San Francisco", 37.7955, -122.3933, "Marketplace"),-                                SearchResult("2", "Ferry Plaza Farmers Market", "1 Ferry Building, San Francisco", 37.7959, -122.3937, "Farmers market"),-                                SearchResult("3", "Golden Gate Ferry Terminal", "Pier 1, San Francisco", 37.7936, -122.3927, "Ferry terminal"),-                                SearchResult("4", "Oakland Ferry Dock", "Clay St, Oakland", 37.7947, -122.2783, "Ferry terminal"),+                                SearchResult("1", "Ferry Building Marketplace", "1 Ferry Building, San Francisco", 37.7955, -122.3933, "Marketplace", locality = SF_LOCALITY),+                                SearchResult("2", "Ferry Plaza Farmers Market", "1 Ferry Building, San Francisco", 37.7959, -122.3937, "Farmers market", locality = SF_LOCALITY),+                                SearchResult("3", "Golden Gate Ferry Terminal", "Pier 1, San Francisco", 37.7936, -122.3927, "Ferry terminal", locality = SF_LOCALITY),+                                SearchResult("4", "Oakland Ferry Dock", "Clay St, Oakland", 37.7947, -122.2783, "Ferry terminal", locality = "Oakland, California, United States"),                             ),                             // Explicitly not searching: with results present and this left at its                             // default the state would resolve to Results anyway, but the listing@@ -210,10 +213,10 @@ class MetadataPreviews {                         searchState = SearchUiState(                             query = "ferry",                             results = listOf(-                                SearchResult("1", "Ferry Building Marketplace", "1 Ferry Building, San Francisco", 37.7955, -122.3933, "Marketplace"),-                                SearchResult("2", "Ferry Plaza Farmers Market", "1 Ferry Building, San Francisco", 37.7959, -122.3937, "Farmers market"),-                                SearchResult("3", "Golden Gate Ferry Terminal", "Pier 1, San Francisco", 37.7936, -122.3927, "Ferry terminal"),-                                SearchResult("4", "Oakland Ferry Dock", "Clay St, Oakland", 37.7947, -122.2783, "Ferry terminal"),+                                SearchResult("1", "Ferry Building Marketplace", "1 Ferry Building, San Francisco", 37.7955, -122.3933, "Marketplace", locality = SF_LOCALITY),+                                SearchResult("2", "Ferry Plaza Farmers Market", "1 Ferry Building, San Francisco", 37.7959, -122.3937, "Farmers market", locality = SF_LOCALITY),+                                SearchResult("3", "Golden Gate Ferry Terminal", "Pier 1, San Francisco", 37.7936, -122.3927, "Ferry terminal", locality = SF_LOCALITY),+                                SearchResult("4", "Oakland Ferry Dock", "Clay St, Oakland", 37.7947, -122.2783, "Ferry terminal", locality = "Oakland, California, United States"),                             ),                             searching = false,                         ),
maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.ktindex ff2afc2062..6e61a442e4 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiArchiveTest.kt@@ -140,6 +140,36 @@ class PoiArchiveTest {         assertEquals(2, box.size)     } +    /**+     * Kinds 15 + 16 together: both records link to Paris (relation 71525), and the admin+     * table walks Paris up to France, so the archive alone yields the row's locality line.+     */+    @Test+    fun `region and admin sections give a locality line`() {+        val paris = (71_525L shl 2) or 3L+        val france = (2_202_162L shl 2) or 3L+        val region = ByteBuffer.allocate(12 + 16).order(ByteOrder.LITTLE_ENDIAN)+        region.put("PRG1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(2).putLong(paris).putLong(paris)+        val pool = "Paris\u0000France\u0000".toByteArray(Charsets.UTF_8)+        val admin = ByteBuffer.allocate(16 + 64 + pool.size).order(ByteOrder.LITTLE_ENDIAN)+        admin.put("PAD1".toByteArray(Charsets.US_ASCII)).putInt(1).putInt(2).putInt(pool.size)+        // Ascending tagged ids: Paris (smaller id) first.+        admin.putLong(paris).putLong(france).putInt(0).putInt(-1).put(8.toByte()).put(ByteArray(7))+        admin.putLong(france).putLong(0L).putInt(6).putInt(-1).put(2.toByte()).put(ByteArray(7))+        admin.put(pool)+        val f = writeArchive(+            listOf(+                indexPayload(),+                Triple(PoiArchive.KIND_NAMES, namesBytes(), 0L),+                Triple(PoiArchive.KIND_REGION, region.array(), 0L),+                Triple(PoiArchive.KIND_ADMIN, admin.array(), 0L),+            ),+        )+        assertTrue(PoiIndex.reloadArchive(f), "archive did not map")+        assertEquals("Paris, France", PoiIndex.localityAt(0, english = true))+        assertEquals("Paris, France", PoiIndex.localityAt(1, english = false))+    }+     @Test     fun `bad magic is refused`() {         val bytes = archive(
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexAdminTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexAdminTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexAdminTest.ktnew file mode 100644index 0000000000..58beaa5000--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexAdminTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.maps.util++import java.io.ByteArrayOutputStream+import java.io.File+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++/**+ * The locality line ("City, State, Country") read from `poi_admin.bin` — the layout+ * `osm_ingest/src/poi_admin.rs` writes and pins from its side.+ */+class PoiIndexAdminTest {++    private var temp: File? = null++    @AfterTest+    fun tearDown() {+        temp?.deleteRecursively()+        temp = null+    }++    private class Entry(val tagged: Long, val parent: Long, val level: Int, val name: String, val en: String? = null)++    private fun tag(relation: Long): Long = (relation shl 2) or 3L++    /** Serialise [entries] exactly as `write_admin` does (sorted, 32-byte entries, NUL pool). */+    private fun table(entries: List<Entry>): AdminTable {+        val sorted = entries.sortedBy { it.tagged }+        val pool = ByteArrayOutputStream()+        val offsets = HashMap<String, Int>()+        fun intern(s: String): Int = offsets.getOrPut(s) {+            pool.size().also { pool.write(s.toByteArray(Charsets.UTF_8)); pool.write(0) }+        }+        val body = ByteBuffer.allocate(32 * sorted.size).order(ByteOrder.LITTLE_ENDIAN)+        for (e in sorted) {+            body.putLong(e.tagged)+            body.putLong(e.parent)+            body.putInt(intern(e.name))+            body.putInt(e.en?.let { intern(it) } ?: -1)+            body.put(e.level.toByte())+            body.put(ByteArray(7))+        }+        val header = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)+        header.put("PAD1".toByteArray(Charsets.US_ASCII))+        header.putInt(1)+        header.putInt(sorted.size)+        header.putInt(pool.size())+        val dir = Files.createTempDirectory("poiadmin").toFile()+        temp = dir+        val file = File(dir, ADMIN_FILE)+        file.writeBytes(header.array() + body.array() + pool.toByteArray())+        return assertNotNull(adminFromBuffer(PoiIndex.mapReadOnly(file)))+    }++    private val us = Entry(tag(148_838), 0, 2, "United States")+    private val texas = Entry(tag(114_690), us.tagged, 4, "Texas")+    private val travis = Entry(tag(1_837_698), texas.tagged, 6, "Travis County")+    private val austin = Entry(tag(113_314), travis.tagged, 8, "Austin")+    private val downtown = Entry(tag(9_000_001), austin.tagged, 10, "Downtown")+    private val france = Entry(tag(2_202_162), 0, 2, "France")+    private val metropole = Entry(tag(1_403_916), france.tagged, 3, "France métropolitaine")+    private val paris = Entry(tag(71_525), metropole.tagged, 8, "Paris")+    private val koeln = Entry(tag(62_578), tag(51_477), 6, "Köln", en = "Cologne")+    private val germany = Entry(tag(51_477), 0, 2, "Deutschland", en = "Germany")++    @Test+    fun `a POI walks its boundary up to city, state and country`() {+        val t = table(listOf(us, texas, travis, austin, downtown))+        // The district below the city and the county above it are skipped.+        assertEquals("Austin, Texas, United States", t.localityOf(downtown.tagged, english = false))+        assertEquals("Austin, Texas, United States", t.localityOf(austin.tagged, english = false))+    }++    @Test+    fun `state appears only where the country has one`() {+        val t = table(listOf(france, metropole, paris))+        // France has no level-4 boundary in this table: the level-3 region stands in for it.+        assertEquals("Paris, France métropolitaine, France", t.localityOf(paris.tagged, english = false))+        val noState = table(listOf(france, Entry(paris.tagged, france.tagged, 8, "Paris")))+        assertEquals("Paris, France", noState.localityOf(paris.tagged, english = false))+    }++    @Test+    fun `english names are preferred when asked for and present`() {+        val t = table(listOf(germany, koeln))+        assertEquals("Köln, Deutschland", t.localityOf(koeln.tagged, english = false))+        assertEquals("Cologne, Germany", t.localityOf(koeln.tagged, english = true))+    }++    @Test+    fun `an unknown boundary has no locality and a cycle does not spin`() {+        val t = table(listOf(Entry(tag(1), tag(2), 8, "A"), Entry(tag(2), tag(1), 8, "B")))+        assertNull(t.localityOf(tag(99), english = false))+        assertEquals("A", t.localityOf(tag(1), english = false))+    }++    @Test+    fun `joinLocality drops blanks and consecutive repeats`() {+        assertEquals("Singapore", joinLocality("Singapore", null, "Singapore"))+        assertEquals("Monaco, France", joinLocality("Monaco", " ", "France"))+        assertNull(joinLocality(null, "", null))+    }++    @Test+    fun `a malformed table is refused`() {+        val dir = Files.createTempDirectory("poiadminbad").toFile()+        temp = dir+        val file = File(dir, ADMIN_FILE)+        file.writeBytes("PAD1".toByteArray() + ByteArray(12) { if (it == 0) 1 else if (it == 4) 5 else 0 }) // v1, count 5, no entries+        assertNull(adminFromBuffer(PoiIndex.mapReadOnly(file)))+    }+}