Modern Apps git

← Modern-Apps.git

maps: mechanical hygiene pass over the map UI

Commit
5567f04d00af291b6e0d47316a98575aba80940a
Author
vayun-mathur <[email protected]>
When
2026-08-21 16:41 UTC (3 months ago)
Parents
e912e05

Diff

maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 807906ff0b..184e46e394 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -40,7 +40,6 @@ import com.vayunmathur.maps.util.OfflineRouter import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel-import com.vayunmathur.maps.util.GooglePoiMapViewModel import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle@@ -275,7 +274,6 @@ fun Navigation(     viewModel: SelectedFeatureViewModel = viewModel(),     searchViewModel: MapsSearchViewModel = viewModel(),     savedPlacesViewModel: SavedPlacesViewModel = viewModel(),-    poiViewModel: GooglePoiMapViewModel = viewModel(),     settingsViewModel: MapSettingsViewModel = viewModel(),     parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel = viewModel(),     transitViewModel: com.vayunmathur.maps.util.TransitStopsViewModel = viewModel(),@@ -283,7 +281,7 @@ fun Navigation(     val backStack = rememberNavBackStack<Route>(Route.MapPage)     MainNavigation(backStack) {         entry<Route.MapPage> {-            MapPage(backStack, viewModel, savedPlacesViewModel, poiViewModel, searchViewModel, settingsViewModel, parkingViewModel, transitViewModel)+            MapPage(backStack, viewModel, savedPlacesViewModel, searchViewModel, settingsViewModel, parkingViewModel, transitViewModel)         }         entry<Route.SettingsPage> {             MapSettingsPage(backStack, settingsViewModel)
maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.ktindex 2c1a925cca..c574eb24ca 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -126,9 +126,9 @@ fun BottomSheetContent(  * it read as noise and — being plain text — could not actually be opened.  */ @Composable-private fun AdminLabelHeader(name: String, wikipedia: String) {+private fun AdminLabelHeader(name: String, wikipedia: String, modifier: Modifier = Modifier) {     val context = LocalContext.current-    Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {+    Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {         Text(             name,             style = MaterialTheme.typography.titleLarge,@@ -155,8 +155,9 @@ fun RouteSheet(     setSelectedRouteType: (RouteService.TravelMode) -> Unit,     navState: NavigationSessionManager.NavState = NavigationSessionManager.NavState.Idle,     userPosition: Position? = null,+    modifier: Modifier = Modifier, ) {-    Column {+    Column(modifier) {         PrimaryTabRow(route.entries.indexOfFirst { it.key == selectedRouteType }) {             route.entries.forEach {                 Tab(
maps/src/main/java/com/vayunmathur/maps/ui/ContactAddressButton.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/ContactAddressButton.kt b/maps/src/main/java/com/vayunmathur/maps/ui/ContactAddressButton.ktindex b51c6af164..958af8d2b9 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/ContactAddressButton.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/ContactAddressButton.kt@@ -3,19 +3,10 @@ package com.vayunmathur.maps.ui import android.Manifest import android.app.Activity import android.content.ActivityNotFoundException-import android.content.Context-import android.content.Intent-import android.database.Cursor import android.net.Uri import android.os.Build-import android.provider.ContactsContract-import android.provider.ContactsContract.CommonDataKinds.StructuredPostal-import android.provider.ContactsPickerSessionContract-import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts-import androidx.annotation.RequiresApi import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn@@ -37,8 +28,16 @@ import com.vayunmathur.library.ui.IconContacts import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.rememberPermissionRequest+import com.vayunmathur.maps.util.launchContactPicker+import com.vayunmathur.maps.util.launchPostalPicker+import com.vayunmathur.maps.util.newSystemContactPickerIntent+import com.vayunmathur.maps.util.readAddress+import com.vayunmathur.maps.util.readContactAddresses+import com.vayunmathur.maps.util.readSessionAddresses import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.maps.R as MapsR import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -93,6 +92,9 @@ import kotlinx.coroutines.withContext fun ContactAddressButton(onAddress: (String) -> Unit, modifier: Modifier = Modifier) {     val context = LocalContext.current     val scope = rememberCoroutineScope()+    val messenger = rememberMessenger()+    val noPickerMessage = stringResource(MapsR.string.no_contact_picker)+    val reportNoPicker = { messenger.show(noPickerMessage) }      // A whole-contact URI whose postal read was refused for lack of READ_CONTACTS;     // retried once the permission is granted. Null while nothing is pending.@@ -149,12 +151,12 @@ fun ContactAddressButton(onAddress: (String) -> Unit, modifier: Modifier = Modif             } else {                 // Row carried no address (or wasn't a postal row) — fall back to                 // the whole-contact picker.-                launchContactPicker(context, contactPicker)+                launchContactPicker(contactPicker, reportNoPicker)             }         } catch (_: SecurityException) {             // The implicit per-row grant didn't cover the query on this OEM —             // fall back to the whole-contact picker + READ_CONTACTS path.-            launchContactPicker(context, contactPicker)+            launchContactPicker(contactPicker, reportNoPicker)         }     } @@ -182,18 +184,12 @@ fun ContactAddressButton(onAddress: (String) -> Unit, modifier: Modifier = Modif                 try {                     addressPicker.launch(newSystemContactPickerIntent())                 } catch (_: ActivityNotFoundException) {-                    runCatching {-                        Toast.makeText(-                            context,-                            context.getString(com.vayunmathur.maps.R.string.no_contact_picker),-                            Toast.LENGTH_SHORT,-                        ).show()-                    }+                    reportNoPicker()                 }             } else {                 // Older devices: the legacy postal-row ACTION_PICK also returns a                 // row URI with an implicit read grant (no READ_CONTACTS).-                launchPostalPicker(context, postalPicker, contactPicker)+                launchPostalPicker(postalPicker, contactPicker, reportNoPicker)             }         },         modifier = modifier,@@ -240,181 +236,3 @@ private fun AddressChooserDialog(     ) } -/**- * Build the Android 17 system Contact Picker intent: request the postal-address- * field only (so the user picks an ADDRESS), single-select. All extras below are- * compile-time String constants and are therefore inlined, so referencing the- * new [ContactsPickerSessionContract] symbols is safe even on older runtimes;- * the call is additionally gated on [Build.VERSION_CODES.CINNAMON_BUN].- */-@RequiresApi(Build.VERSION_CODES.CINNAMON_BUN)-private fun newSystemContactPickerIntent(): Intent =-    Intent(ContactsPickerSessionContract.ACTION_PICK_CONTACTS).apply {-        // Also engage the system picker when targeting a lower SDK on Android 17.-        putExtra(Intent.EXTRA_USE_SYSTEM_CONTACTS_PICKER, true)-        // Ask only for postal-address rows.-        putStringArrayListExtra(-            ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS,-            arrayListOf(StructuredPostal.CONTENT_ITEM_TYPE),-        )-        putExtra(ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_SELECTION_LIMIT, 1)-    }--/** Legacy postal-picker path: try the postal-row picker, then the whole-contact- *  picker. Never throws. */-private fun launchPostalPicker(-    context: Context,-    postalPicker: ActivityResultLauncher<Intent>,-    contactPicker: ActivityResultLauncher<Void?>,-) {-    val postalIntent = Intent(Intent.ACTION_PICK).apply {-        type = StructuredPostal.CONTENT_TYPE-    }-    try {-        postalPicker.launch(postalIntent)-    } catch (_: ActivityNotFoundException) {-        // No postal picker on this device — try the universal contact picker.-        launchContactPicker(context, contactPicker)-    }-}--/** Launch the whole-contact picker, degrading to a quiet toast if even that has- *  no handler (some stripped OEM images). Never throws. */-private fun launchContactPicker(-    context: Context,-    contactPicker: ActivityResultLauncher<Void?>,-) {-    try {-        contactPicker.launch(null)-    } catch (_: ActivityNotFoundException) {-        runCatching {-            Toast.makeText(context, context.getString(com.vayunmathur.maps.R.string.no_contact_picker), Toast.LENGTH_SHORT).show()-        }-    }-}--/**- * Read every postal address from the Android 17 picker's [sessionUri]. The session- * URI is a pre-scoped view of exactly what the user chose, so it does NOT support- * selection / selectionArgs (passing them throws) — query with nulls. We iterate- * the returned rows and collect each StructuredPostal address (de-duplicated,- * order preserved). With SELECTION_LIMIT=1 this is normally one address; if an OEM- * returns the whole chosen contact's several addresses, the caller shows a chooser.- */-private fun readSessionAddresses(context: Context, sessionUri: Uri): List<String> {-    val out = LinkedHashSet<String>()-    context.contentResolver.query(sessionUri, SESSION_PROJECTION, null, null, null)?.use { cursor ->-        val mimeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)-        while (cursor.moveToNext()) {-            val mime = if (mimeIdx >= 0) cursor.getString(mimeIdx) else null-            if (mime == null || mime == StructuredPostal.CONTENT_ITEM_TYPE) {-                cursor.postalAddress()?.let { out.add(it) }-            }-        }-    }-    return out.toList()-}--/**- * Read the postal address at [rowUri] (a StructuredPostal data row). Prefers the- * pre-formatted [StructuredPostal.FORMATTED_ADDRESS]; if that's blank it- * composes the address from the individual components. Returns null when the- * row is gone or holds no address. May throw [SecurityException] when the- * caller lacks read access to the row.- */-private fun readAddress(context: Context, rowUri: Uri): String? {-    context.contentResolver.query(rowUri, POSTAL_PROJECTION, null, null, null)?.use { cursor ->-        if (!cursor.moveToFirst()) return null-        return cursor.postalAddress()-    }-    return null-}--/**- * Resolve all postal addresses of the whole contact at [contactUri] (as returned- * by [ActivityResultContracts.PickContact]). Looks up the contact id, then reads- * its StructuredPostal data rows (de-duplicated, order preserved). Returns empty- * when the contact has no postal address. Requires READ_CONTACTS (may throw- * [SecurityException]).- */-private fun readContactAddresses(context: Context, contactUri: Uri): List<String> {-    val contactId = context.contentResolver.query(-        contactUri,-        arrayOf(ContactsContract.Contacts._ID),-        null,-        null,-        null,-    )?.use { c -> if (c.moveToFirst()) c.getString(0) else null } ?: return emptyList()--    val selection =-        "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?"-    val args = arrayOf(-        contactId,-        StructuredPostal.CONTENT_ITEM_TYPE,-    )-    val out = LinkedHashSet<String>()-    context.contentResolver.query(-        ContactsContract.Data.CONTENT_URI,-        POSTAL_PROJECTION,-        selection,-        args,-        null,-    )?.use { cursor ->-        while (cursor.moveToNext()) {-            cursor.postalAddress()?.let { out.add(it) }-        }-    }-    return out.toList()-}--/** Pull a display address out of a StructuredPostal cursor row: the formatted- *  address if present, else the composed components. Null when the row is empty. */-private fun Cursor.postalAddress(): String? {-    fun col(name: String): String? = getColumnIndex(name)-        .takeIf { it >= 0 }-        ?.let { getString(it) }-        ?.takeIf { it.isNotBlank() }--    col(StructuredPostal.FORMATTED_ADDRESS)-        ?.normalizeAddress()-        ?.takeIf { it.isNotBlank() }-        ?.let { return it }--    return listOfNotNull(-        col(StructuredPostal.STREET),-        col(StructuredPostal.CITY),-        col(StructuredPostal.REGION),-        col(StructuredPostal.POSTCODE),-        col(StructuredPostal.COUNTRY),-    ).joinToString(", ").ifBlank { null }-}--/** Collapse a multi-line postal address to one comma-separated line so it makes- *  a valid single-line search query (FORMATTED_ADDRESS embeds newlines). Runs of- *  whitespace within a line collapse to a single space; blank lines are dropped. */-private fun String.normalizeAddress(): String =-    lines()-        .map { it.replace(Regex("\\s+"), " ").trim() }-        .filter { it.isNotEmpty() }-        .joinToString(", ")--/** Projection for the Android 17 session URI: MIMETYPE (to spot the postal row)- *  plus the postal columns. */-private val SESSION_PROJECTION = arrayOf(-    ContactsContract.Data.MIMETYPE,-    StructuredPostal.FORMATTED_ADDRESS,-    StructuredPostal.STREET,-    StructuredPostal.CITY,-    StructuredPostal.REGION,-    StructuredPostal.POSTCODE,-    StructuredPostal.COUNTRY,-)--private val POSTAL_PROJECTION = arrayOf(-    StructuredPostal.FORMATTED_ADDRESS,-    StructuredPostal.STREET,-    StructuredPostal.CITY,-    StructuredPostal.REGION,-    StructuredPostal.POSTCODE,-    StructuredPostal.COUNTRY,-)
maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.ktindex 005ebf975b..c8c470aeca 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/DeparturesSheet.kt@@ -120,7 +120,7 @@ fun DeparturesSheet( /** Group departures by line (ordered by the soonest departure in each group)  *  and render each as a coloured line badge + its upcoming trips. */ @Composable-private fun DepartureList(departures: List<Departure>, now: Long) {+private fun DepartureList(departures: List<Departure>, now: Long, modifier: Modifier = Modifier) {     val groups = remember(departures) {         departures             .sortedBy { it.realtimeMillis }@@ -129,7 +129,7 @@ private fun DepartureList(departures: List<Departure>, now: Long) {             .sortedBy { entry -> entry.value.minOfOrNull { it.realtimeMillis } ?: Long.MAX_VALUE }     } -    LazyColumn(Modifier.fillMaxWidth().heightIn(max = 420.dp)) {+    LazyColumn(modifier.fillMaxWidth().heightIn(max = 420.dp)) {         items(groups, key = { it.key }) { (line, trips) ->             Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {                 LineBadge(line, trips.first().routeColor)@@ -144,9 +144,9 @@ private fun DepartureList(departures: List<Departure>, now: Long) { }  @Composable-private fun DepartureRow(dep: Departure, now: Long) {+private fun DepartureRow(dep: Departure, now: Long, modifier: Modifier = Modifier) {     Row(-        Modifier.fillMaxWidth().padding(vertical = 4.dp),+        modifier.fillMaxWidth().padding(vertical = 4.dp),         horizontalArrangement = Arrangement.SpaceBetween,         verticalAlignment = Alignment.CenterVertically,     ) {
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 503ef27d7d..436bd2bf3a 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -4,7 +4,6 @@ import android.content.Context import android.util.Log import androidx.activity.compose.BackHandler import androidx.compose.animation.core.animateDpAsState-import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Arrangement@@ -24,7 +23,6 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape-import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.IconDragHandle import com.vayunmathur.library.ui.FreeHeightBottomSheetScaffold@@ -42,7 +40,6 @@ import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults import com.vayunmathur.library.ui.SheetValue import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.rememberFreeHeightSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect@@ -57,9 +54,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.dp@@ -74,12 +69,13 @@ import com.vayunmathur.maps.data.parse import com.vayunmathur.maps.util.MapTileCache import com.vayunmathur.maps.util.RouteService import com.vayunmathur.maps.util.SavedPlacesViewModel-import com.vayunmathur.maps.util.GooglePoiMapViewModel import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.maps.util.MapsSearchViewModel import com.vayunmathur.maps.util.PoiIndex import com.vayunmathur.maps.ui.theme.BasemapPalette+import com.vayunmathur.maps.ui.theme.MapChromeMetrics import com.vayunmathur.maps.util.SelectedFeatureViewModel+import com.vayunmathur.maps.util.visibleBoundsOrWorld import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext@@ -104,16 +100,18 @@ import org.maplibre.compose.util.ClickResult import org.maplibre.spatialk.geojson.Position import com.vayunmathur.library.ui.ReorderableItem import com.vayunmathur.library.ui.draggableHandle+import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.ui.rememberReorderableLazyListState-import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.maps.R as MapsR  @OptIn(ExperimentalMaterial3Api::class) @Composable-fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, savedPlacesViewModel: SavedPlacesViewModel, poiViewModel: GooglePoiMapViewModel, searchViewModel: MapsSearchViewModel, settingsViewModel: MapSettingsViewModel, parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel, transitViewModel: com.vayunmathur.maps.util.TransitStopsViewModel) {+fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel, savedPlacesViewModel: SavedPlacesViewModel, searchViewModel: MapsSearchViewModel, settingsViewModel: MapSettingsViewModel, parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel, transitViewModel: com.vayunmathur.maps.util.TransitStopsViewModel) {     val selectedFeature by viewModel.selectedFeature.collectAsState()     val context = LocalContext.current     val coroutineScope = rememberCoroutineScope()+    val messenger = rememberMessenger()+    val noResultsMessage = stringResource(MapsR.string.no_results_found)      val savedHome by savedPlacesViewModel.home.collectAsState()     val savedWork by savedPlacesViewModel.work.collectAsState()@@ -262,33 +260,10 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,         sheetState.hide()     } -    fun openSearch() {-        // Style may not have finished loading — fall back to a world-spanning-        // bbox so the search query still works.-        val bbox = camera.projection?.queryVisibleBoundingBox()+    fun openSearch(query: String? = null) {+        val bbox = camera.visibleBoundsOrWorld()         backStack.add(-            Route.SearchPage(-                null,-                bbox?.east ?: 180.0,-                bbox?.west ?: -180.0,-                bbox?.north ?: 85.0,-                bbox?.south ?: -85.0,-            )-        )-    }--    // Browse category chip → open search pre-filled with the category query.-    fun openCategorySearch(query: String) {-        val bbox = camera.projection?.queryVisibleBoundingBox()-        backStack.add(-            Route.SearchPage(-                null,-                bbox?.east ?: 180.0,-                bbox?.west ?: -180.0,-                bbox?.north ?: 85.0,-                bbox?.south ?: -85.0,-                query,-            )+            Route.SearchPage(null, bbox.east, bbox.west, bbox.north, bbox.south, query)         )     } @@ -359,7 +334,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,         Column(Modifier.padding(horizontal = 16.dp).padding(top = 8.dp)) {             BottomSheetContent(viewModel, selectedFeature, { viewModel.set(it) }, route, selectedRouteType, { selectedRouteType = it }, inactiveNavigation, savedPlacesViewModel, transitViewModel, navState)         }-    }, Modifier, sheetState, 170.dp, contentKey = listOf(selectedFeature, selectedRouteType)) { paddingValues ->+    }, Modifier, sheetState, MapChromeMetrics.sheetPeekHeight, contentKey = listOf(selectedFeature, selectedRouteType)) { paddingValues ->         AppScaffold(             title = {                 // Search bar lives IN the top app bar (Google-Maps style).@@ -384,14 +359,12 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         // DIRECTLY (fly there + peek pane) — never through the                         // search box (no query prefill, no results list).                         ContactAddressButton(onAddress = { address ->-                            val bbox = camera.projection?.queryVisibleBoundingBox()-                            val nearLat = ((bbox?.north ?: 85.0) + (bbox?.south ?: -85.0)) / 2.0-                            val nearLon = ((bbox?.east ?: 180.0) + (bbox?.west ?: -180.0)) / 2.0+                            val bbox = camera.visibleBoundsOrWorld()+                            val nearLat = (bbox.north + bbox.south) / 2.0+                            val nearLon = (bbox.east + bbox.west) / 2.0                             searchViewModel.resolveAndSelect(address, nearLat, nearLon) { place ->                                 if (place != null) {-                                    if (selectedFeature is SpecificFeature.Route) {-                                        viewModel.setInactiveNavigation(selectedFeature as SpecificFeature.Route)-                                    }+                                    viewModel.stashRouteSelection()                                     // Fly to the resolved place + open the peek pane                                     // (Vela place-card), the same direct-open path as                                     // a geo:/maps deep link.@@ -400,19 +373,13 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                         zoom = maxOf(camera.position.zoom, 14.0),                                     )                                 } else {-                                    runCatching {-                                        android.widget.Toast.makeText(-                                            context,-                                            context.getString(MapsR.string.no_results_found),-                                            android.widget.Toast.LENGTH_SHORT,-                                        ).show()-                                    }+                                    messenger.show(noResultsMessage)                                 }                             }                         })                         // Voice search (P8): a transcript opens the search page                         // pre-filled, which runs the P3 Google search.-                        VoiceSearchButton(onResult = { openCategorySearch(it) })+                        VoiceSearchButton(onResult = { openSearch(it) })                     }                 }             },@@ -453,7 +420,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                 // around the touch point so tapping NEAR a small                                 // POI glyph still selects it, instead of only                                 // registering on a pixel-exact hit.-                                val pad = 22.dp+                                val pad = MapChromeMetrics.hitSlop                                 val hitBox = DpRect(offset.x - pad, offset.y - pad, offset.x + pad, offset.y + pad)                                 // Parking pin (P9): tapping the saved car spot                                 // opens the parking sheet instead of selecting a@@ -504,9 +471,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                         setOf(MA_POIS_LAYER_ID)                                     )?.firstNotNullOfOrNull { it.toSelectedMaPoi() }                                 if (pinHit != null) {-                                    if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(-                                        selectedFeature as SpecificFeature.Route-                                    )+                                    viewModel.stashRouteSelection()                                     viewModel.set(pinHit)                                     sheetState.partialExpand()                                     return@launch@@ -533,9 +498,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                 }                                  if (firstFeature != null) {-                                    if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(-                                        selectedFeature as SpecificFeature.Route-                                    )+                                    viewModel.stashRouteSelection()                                     viewModel.set(firstFeature)                                     sheetState.partialExpand()                                     return@launch@@ -546,9 +509,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                 // FTS geocoder — online-only (Decision D2).                                 searchViewModel.reverseGeocode(latLng.latitude, latLng.longitude) { place ->                                     if (place != null) {-                                        if (selectedFeature is SpecificFeature.Route) viewModel.setInactiveNavigation(-                                            selectedFeature as SpecificFeature.Route-                                        )+                                        viewModel.stashRouteSelection()                                         viewModel.set(place)                                         coroutineScope.launch { sheetState.partialExpand() }                                     }@@ -563,7 +524,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                  // ROUTE OVERLAY HEADERS                 if(selectedFeature is SpecificFeature.Route || inactiveNavigation != null) {-                    val routeFeature = if(selectedFeature is SpecificFeature.Route) selectedFeature as SpecificFeature.Route else inactiveNavigation!!+                    val routeFeature = (selectedFeature as? SpecificFeature.Route) ?: inactiveNavigation!!                     val listState = rememberLazyListState()                     val state = rememberReorderableLazyListState(listState, onMove = { from, to ->                         // swap their indices in the list@@ -589,15 +550,9 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                                 ?: stringResource(MapsR.string.your_location)                                         )                                     }, Modifier.clickable {-                                        // Style may not have finished loading-                                        // — fall back to a world-spanning bbox-                                        // so the search query still works.-                                        val bbox = camera.projection?.queryVisibleBoundingBox()+                                        val bbox = camera.visibleBoundsOrWorld()                                         backStack.add(Route.SearchPage(idx,-                                            bbox?.east ?: 180.0,-                                            bbox?.west ?: -180.0,-                                            bbox?.north ?: 85.0,-                                            bbox?.south ?: -85.0))+                                            bbox.east, bbox.west, bbox.north, bbox.south))                                     }, trailingContent = {                                         Row(verticalAlignment = Alignment.CenterVertically) {                                             if(idx > 0 && idx < routeFeature.waypoints.size - 1) {@@ -652,15 +607,15 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                         modifier = Modifier                             .align(Alignment.BottomStart)                             .windowInsetsPadding(WindowInsets.systemBars)-                            .padding(16.dp),+                            .padding(MapChromeMetrics.chromeMargin),                     )                     Column(                         modifier = Modifier                             .align(Alignment.BottomEnd)                             .windowInsetsPadding(WindowInsets.systemBars)-                            .padding(16.dp),+                            .padding(MapChromeMetrics.chromeMargin),                         horizontalAlignment = Alignment.End,-                        verticalArrangement = Arrangement.spacedBy(12.dp),+                        verticalArrangement = Arrangement.spacedBy(MapChromeMetrics.fabSpacing),                     ) {                         // Compass sits on top and only shows when the map is                         // rotated; layers in the middle; my-location is the@@ -740,6 +695,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                     northUp = navNorthUp,                     onToggleNorthUp = { navNorthUp = !navNorthUp },                     destinationName = com.vayunmathur.maps.util.NavigationSessionManager.destinationName,+                    darkBasemap = darkMap,                 )                  // Map-layers toggle sheet (P6), opened from the LayersButton.@@ -772,9 +728,7 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,                                 val feature = spot.toFeature(                                     context.getString(MapsR.string.parking_title)                                 )-                                if (selectedFeature is SpecificFeature.Route) {-                                    viewModel.setInactiveNavigation(selectedFeature as SpecificFeature.Route)-                                }+                                viewModel.stashRouteSelection()                                 viewModel.set(SpecificFeature.Route(listOf(null, feature)))                                 showParkingSheet = false                                 coroutineScope.launch { sheetState.partialExpand() }
maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.ktindex 3835f183cf..47bb46e38c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/NavigationOverlay.kt@@ -2,6 +2,7 @@ package com.vayunmathur.maps.ui  import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer@@ -41,7 +42,9 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.SmallFloatingActionButton import com.vayunmathur.library.ui.Text import com.vayunmathur.maps.R+import com.vayunmathur.library.ui.Spacing import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.ui.theme.MapChromeMetrics import com.vayunmathur.maps.ui.nav.ArrivalSummary import com.vayunmathur.maps.ui.nav.ManeuverBanner import com.vayunmathur.maps.ui.nav.SpeedWidget@@ -74,52 +77,42 @@ fun NavigationOverlay(     northUp: Boolean = false,     onToggleNorthUp: () -> Unit = {},     destinationName: String? = null,+    darkBasemap: Boolean = false,+    modifier: Modifier = Modifier, ) {     if (navState is NavigationSessionManager.NavState.Idle) return      var showSteps by remember { mutableStateOf(false) } -    Box(Modifier.fillMaxSize()) {+    Box(modifier.fillMaxSize()) {         // ---- Top maneuver banner / status ----         when (navState) {             is NavigationSessionManager.NavState.Navigating -> {                 ManeuverBanner(                     progress = navState.progress,                     steps = steps,-                    modifier = Modifier-                        .align(Alignment.TopCenter)-                        .windowInsetsPadding(WindowInsets.statusBars)-                        .padding(horizontal = 12.dp, vertical = 8.dp),+                    modifier = navTopSlot(),                 )             }             NavigationSessionManager.NavState.Starting -> {                 StatusCard(                     text = stringResource(R.string.nav_status_starting),                     showProgress = true,-                    modifier = Modifier-                        .align(Alignment.TopCenter)-                        .windowInsetsPadding(WindowInsets.statusBars)-                        .padding(horizontal = 12.dp, vertical = 8.dp),+                    modifier = navTopSlot(),                 )             }             NavigationSessionManager.NavState.Recalculating -> {                 StatusCard(                     text = stringResource(R.string.nav_off_route),                     showProgress = true,-                    modifier = Modifier-                        .align(Alignment.TopCenter)-                        .windowInsetsPadding(WindowInsets.statusBars)-                        .padding(horizontal = 12.dp, vertical = 8.dp),+                    modifier = navTopSlot(),                 )             }             is NavigationSessionManager.NavState.Failed -> {                 FailureCard(                     reason = navState.reason,                     onDismiss = onDismissArrival,-                    modifier = Modifier-                        .align(Alignment.TopCenter)-                        .windowInsetsPadding(WindowInsets.statusBars)-                        .padding(horizontal = 12.dp, vertical = 8.dp),+                    modifier = navTopSlot(),                 )             }             else -> {}@@ -130,8 +123,8 @@ fun NavigationOverlay(             Column(                 modifier = Modifier                     .align(Alignment.CenterEnd)-                    .padding(16.dp),-                verticalArrangement = Arrangement.spacedBy(12.dp),+                    .padding(MapChromeMetrics.chromeMargin),+                verticalArrangement = Arrangement.spacedBy(MapChromeMetrics.fabSpacing),                 horizontalAlignment = Alignment.End,             ) {                 SmallFloatingActionButton(onClick = onToggleNorthUp) {@@ -155,10 +148,14 @@ fun NavigationOverlay(             SpeedWidget(                 speedMps = navState.progress.speedMps,                 postedLimit = postedLimit,+                darkBasemap = darkBasemap,                 modifier = Modifier                     .align(Alignment.BottomStart)                     .windowInsetsPadding(WindowInsets.systemBars)-                    .padding(start = 16.dp, bottom = 96.dp),+                    .padding(+                        start = MapChromeMetrics.chromeMargin,+                        bottom = MapChromeMetrics.aboveEtaStrip,+                    ),             )         } @@ -168,11 +165,14 @@ fun NavigationOverlay(                 steps = steps,                 currentStepIndex = navState.progress.currentStepIndex,                 onClose = { showSteps = false },+                // Insets before the clearance padding, matching the speedometer above. The+                // two were in opposite orders, which shifted them apart by the nav-bar+                // height on top of the clearance they already disagreed on.                 modifier = Modifier                     .align(Alignment.BottomCenter)                     .fillMaxWidth()-                    .padding(bottom = 84.dp)-                    .windowInsetsPadding(WindowInsets.systemBars),+                    .windowInsetsPadding(WindowInsets.systemBars)+                    .padding(bottom = MapChromeMetrics.aboveEtaStripTight),             )         } @@ -197,7 +197,7 @@ fun NavigationOverlay(                         .align(Alignment.BottomCenter)                         .fillMaxWidth()                         .windowInsetsPadding(WindowInsets.systemBars)-                        .padding(16.dp),+                        .padding(MapChromeMetrics.chromeMargin),                 )             }             else -> {}@@ -205,6 +205,17 @@ fun NavigationOverlay(     } } +/**+ * The top status slot: whichever single card the nav state calls for, tucked under the status+ * bar. One function because all four callers want byte-identical geometry — they were four+ * copies of the same chain, which is how they would have drifted apart.+ */+@Composable+private fun BoxScope.navTopSlot(): Modifier = Modifier+    .align(Alignment.TopCenter)+    .windowInsetsPadding(WindowInsets.statusBars)+    .padding(horizontal = Spacing.md, vertical = Spacing.sm)+ @Composable private fun StatusCard(     text: String,
maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.ktindex 5d95a6eda6..dee98ed478 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PlaceSheet.kt@@ -12,7 +12,6 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape@@ -196,8 +195,8 @@ private fun StreetViewEntry(feature: SpecificFeature.RoutableFeature) { }  @Composable-private fun PlaceHeader(name: String, poi: GooglePoiInfo?, hasOsmHours: Boolean) {-    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+private fun PlaceHeader(name: String, poi: GooglePoiInfo?, hasOsmHours: Boolean, modifier: Modifier = Modifier) {+    Column(modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) {         Text(name, style = MaterialTheme.typography.titleLarge)          val subtitle = listOfNotNull(poi?.category?.ifBlank { null }, poi?.priceText?.ifBlank { null })@@ -233,9 +232,16 @@ private fun PlaceHeader(name: String, poi: GooglePoiInfo?, hasOsmHours: Boolean)     } } +/**+ * Five stars, filled up to [rating].+ *+ * `Double` rather than `Int` because Google's place rating is fractional; a review's own+ * rating is a whole number and converts. There used to be one of these per file, differing+ * only in that parameter type.+ */ @Composable-private fun RatingStars(rating: Double) {-    Row {+internal fun RatingStars(rating: Double, modifier: Modifier = Modifier) {+    Row(modifier) {         repeat(5) { i ->             if (i < rating.toInt()) IconStar(Modifier.size(16.dp), tint = MaterialTheme.colorScheme.tertiary)             else IconStarBorder(Modifier.size(16.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)@@ -252,6 +258,7 @@ private fun PlaceActionRow(     savedPlacesViewModel: SavedPlacesViewModel,     requestDirections: () -> Unit,     orderDeepLink: String?,+    modifier: Modifier = Modifier, ) {     val context = LocalContext.current     val saved by savedPlacesViewModel.saved.collectAsState()
maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt b/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.ktindex 2457536de8..82e1448932 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/PoiEnrichment.kt@@ -6,7 +6,6 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn@@ -38,7 +37,6 @@ import com.vayunmathur.library.ui.IconInfo import com.vayunmathur.library.ui.IconPhotoLibrary import com.vayunmathur.library.ui.IconSchedule import com.vayunmathur.library.ui.IconStar-import com.vayunmathur.library.ui.IconStarBorder import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.ListItemDefaults import com.vayunmathur.library.ui.MaterialTheme@@ -196,7 +194,7 @@ private fun ReviewCard(review: GoogleReview) {                     }                 }             }-            if (review.rating in 1..5) RatingStars(review.rating)+            if (review.rating in 1..5) RatingStars(review.rating.toDouble())             review.text?.let {                 Text(it, style = MaterialTheme.typography.bodyMedium, maxLines = 6)             }@@ -216,16 +214,6 @@ private fun ReviewCard(review: GoogleReview) {     } } -@Composable-private fun RatingStars(rating: Int) {-    Row {-        repeat(5) { i ->-            if (i < rating) IconStar(Modifier.size(16.dp), tint = MaterialTheme.colorScheme.tertiary)-            else IconStarBorder(Modifier.size(16.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)-        }-    }-}- @Composable private fun PopularTimesSection(popularTimes: PoiPopularTimes) {     // Show today's histogram (falling back to the first day Google returned).
maps/src/main/java/com/vayunmathur/maps/ui/SafetyLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SafetyLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SafetyLayer.ktindex 82628d1c36..17f166aed2 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SafetyLayer.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SafetyLayer.kt@@ -4,7 +4,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap-import androidx.compose.ui.unit.dp import com.vayunmathur.maps.util.MapTileCache import org.maplibre.compose.expressions.dsl.case import org.maplibre.compose.expressions.dsl.const
maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesPage.ktindex f56ad7c869..ce6edd36d3 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SavedPlacesPage.kt@@ -199,9 +199,11 @@ private fun SavedPlaceRow(     onRename: () -> Unit,     onAddToList: () -> Unit,     onRemove: () -> Unit,+    modifier: Modifier = Modifier, ) {     var menuOpen by remember { mutableStateOf(false) }     SettingsRow(+        modifier = modifier,         title = place.name,         leadingContent = { IconStar() },         trailingContent = {
maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.ktindex 3d23cdc57b..8dee0bef7d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/SearchPage.kt@@ -228,8 +228,8 @@ fun SearchScreen(state: SearchUiState, actions: SearchActions) { }  @Composable-private fun ResultsList(results: List<SearchResult>, actions: SearchActions) {-    LazyColumn(modifier = Modifier.fillMaxSize()) {+private fun ResultsList(results: List<SearchResult>, actions: SearchActions, modifier: Modifier = Modifier) {+    LazyColumn(modifier = modifier.fillMaxSize()) {         items(results, key = { it.id }) { result ->             ListItem(                 content = { Text(result.title) },@@ -247,8 +247,8 @@ private fun ResultsList(results: List<SearchResult>, actions: SearchActions) { }  @Composable-private fun RecentsList(recents: List<String>, actions: SearchActions) {-    LazyColumn(modifier = Modifier.fillMaxSize()) {+private fun RecentsList(recents: List<String>, actions: SearchActions, modifier: Modifier = Modifier) {+    LazyColumn(modifier = modifier.fillMaxSize()) {         item {             Row(                 modifier = Modifier
maps/src/main/java/com/vayunmathur/maps/ui/nav/ManeuverBanner.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/ManeuverBanner.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/ManeuverBanner.ktindex abbedbb4c3..7ef0fcf3a5 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/ManeuverBanner.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/ManeuverBanner.kt@@ -1,6 +1,5 @@ package com.vayunmathur.maps.ui.nav -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer
maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.ktindex 09e306a3b2..128392fd5d 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/SpeedWidget.kt@@ -43,6 +43,7 @@ fun SpeedWidget(     postedLimit: PostedLimit?,     modifier: Modifier = Modifier,     defaultMph: Boolean = isImperialUnits(),+    darkBasemap: Boolean = false, ) {     val useMph = postedLimit?.displayIsMph ?: defaultMph     val speed = if (useMph) (speedMps * MPS_TO_MPH).roundToInt() else (speedMps * MPS_TO_KMH).roundToInt()@@ -83,13 +84,26 @@ fun SpeedWidget(         // Posted-limit sign (only when we have a limit). White disc, red ring, near-black         // numerals in BOTH themes: this is a reproduction of a legal road sign, and there is         // no dark-mode variant of one. The speed pill beside it does follow the theme.+        //+        // Over a dark basemap the white disc is the brightest thing on screen, so it gains a+        // hairline ring in the ink colour. Drawn INSIDE the fixed 56 dp box (ring, then 1 dp+        // of padding, then the disc) so the sign's colours and its footprint both stay put —+        // an outer ring would paint under the red one, and a larger box would make the widget+        // change size with the theme.         if (limitValue != null) {             Box(                 Modifier                     .shadow(4.dp, CircleShape)+                    .size(56.dp)+                    .then(+                        if (darkBasemap) {+                            Modifier.border(1.dp, SpeedSign.ink, CircleShape).padding(1.dp)+                        } else {+                            Modifier+                        }+                    )                     .background(SpeedSign.disc, CircleShape)-                    .border(4.dp, SpeedSign.ring, CircleShape)-                    .size(56.dp),+                    .border(4.dp, SpeedSign.ring, CircleShape),                 contentAlignment = Alignment.Center,             ) {                 Text(
maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt b/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.ktindex 8e31ab7f1e..01c574e0c8 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/nav/StepsSheet.kt@@ -1,6 +1,5 @@ package com.vayunmathur.maps.ui.nav -import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer
maps/src/main/java/com/vayunmathur/maps/util/CameraBounds.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/CameraBounds.kt b/maps/src/main/java/com/vayunmathur/maps/util/CameraBounds.ktnew file mode 100644index 0000000000..e414ae0898--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/CameraBounds.kt@@ -0,0 +1,24 @@+package com.vayunmathur.maps.util++import org.maplibre.compose.camera.CameraState+import org.maplibre.spatialk.geojson.BoundingBox++/**+ * The world, used when the camera cannot say what is on screen.+ *+ * Latitude stops at ±85° rather than ±90° because that is where the web-mercator projection+ * the basemap uses runs out; the poles are not addressable in it.+ */+private val World = BoundingBox(west = -180.0, south = -85.0, east = 180.0, north = 85.0)++/**+ * The visible map bounds, falling back to the whole world.+ *+ * `camera.projection` is null until the style finishes loading, which is a state a user can+ * reach — tapping search during the first frames after launch. Every caller wants the same+ * fallback for the same reason (a search biased to the world still works; a search biased to+ * nothing does not), and each was spelling out four `?:` defaults, so a typo in any one of+ * them would have silently biased results to the wrong hemisphere.+ */+fun CameraState.visibleBoundsOrWorld(): BoundingBox =+    projection?.queryVisibleBoundingBox() ?: World
maps/src/main/java/com/vayunmathur/maps/util/ContactLookup.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/ContactLookup.kt b/maps/src/main/java/com/vayunmathur/maps/util/ContactLookup.ktnew file mode 100644index 0000000000..106db039f1--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/ContactLookup.kt@@ -0,0 +1,209 @@+package com.vayunmathur.maps.util++import android.content.ActivityNotFoundException+import android.content.Context+import android.content.Intent+import android.database.Cursor+import android.net.Uri+import android.os.Build+import android.provider.ContactsContract+import android.provider.ContactsContract.CommonDataKinds.StructuredPostal+import android.provider.ContactsPickerSessionContract+import androidx.activity.result.ActivityResultLauncher+import androidx.annotation.RequiresApi++/**+ * Reading postal addresses out of the contacts provider, and launching the pickers that+ * produce the URIs to read.+ *+ * Split out of `ui/ContactAddressButton.kt`, which was one small composable on top of this:+ * cursor projections, three provider query shapes, and the picker-intent fallback chain. None+ * of it is UI, none of it needs a composition, and all of it is the part with edge cases worth+ * reading on its own — Android 17's session URIs, the legacy postal-row picker, and OEM images+ * that ship neither.+ *+ * Everything here is main-thread-unsafe (it queries a ContentProvider); callers dispatch to IO.+ */++/**+ * Build the Android 17 system Contact Picker intent: request the postal-address+ * field only (so the user picks an ADDRESS), single-select. All extras below are+ * compile-time String constants and are therefore inlined, so referencing the+ * new [ContactsPickerSessionContract] symbols is safe even on older runtimes;+ * the call is additionally gated on [Build.VERSION_CODES.CINNAMON_BUN].+ */+@RequiresApi(Build.VERSION_CODES.CINNAMON_BUN)+fun newSystemContactPickerIntent(): Intent =+    Intent(ContactsPickerSessionContract.ACTION_PICK_CONTACTS).apply {+        // Also engage the system picker when targeting a lower SDK on Android 17.+        putExtra(Intent.EXTRA_USE_SYSTEM_CONTACTS_PICKER, true)+        // Ask only for postal-address rows.+        putStringArrayListExtra(+            ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_REQUESTED_DATA_FIELDS,+            arrayListOf(StructuredPostal.CONTENT_ITEM_TYPE),+        )+        putExtra(ContactsPickerSessionContract.EXTRA_PICK_CONTACTS_SELECTION_LIMIT, 1)+    }++/**+ * Legacy postal-picker path: try the postal-row picker, then the whole-contact picker, then+ * give up via [onNoPicker]. Never throws.+ *+ * [onNoPicker] rather than a `Toast` from in here: telling the user is the UI layer's job, and+ * a toast ignores the app theme, cannot carry an action, and may be dropped outright while+ * backgrounded.+ */+fun launchPostalPicker(+    postalPicker: ActivityResultLauncher<Intent>,+    contactPicker: ActivityResultLauncher<Void?>,+    onNoPicker: () -> Unit,+) {+    val postalIntent = Intent(Intent.ACTION_PICK).apply {+        type = StructuredPostal.CONTENT_TYPE+    }+    try {+        postalPicker.launch(postalIntent)+    } catch (_: ActivityNotFoundException) {+        // No postal picker on this device — try the universal contact picker.+        launchContactPicker(contactPicker, onNoPicker)+    }+}++/** Launch the whole-contact picker, reporting through [onNoPicker] if even that has no+ *  handler (some stripped OEM images). Never throws. */+fun launchContactPicker(+    contactPicker: ActivityResultLauncher<Void?>,+    onNoPicker: () -> Unit,+) {+    try {+        contactPicker.launch(null)+    } catch (_: ActivityNotFoundException) {+        onNoPicker()+    }+}++/**+ * Read every postal address from the Android 17 picker's [sessionUri]. The session+ * URI is a pre-scoped view of exactly what the user chose, so it does NOT support+ * selection / selectionArgs (passing them throws) — query with nulls. We iterate+ * the returned rows and collect each StructuredPostal address (de-duplicated,+ * order preserved). With SELECTION_LIMIT=1 this is normally one address; if an OEM+ * returns the whole chosen contact's several addresses, the caller shows a chooser.+ */+fun readSessionAddresses(context: Context, sessionUri: Uri): List<String> {+    val out = LinkedHashSet<String>()+    context.contentResolver.query(sessionUri, SESSION_PROJECTION, null, null, null)?.use { cursor ->+        val mimeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE)+        while (cursor.moveToNext()) {+            val mime = if (mimeIdx >= 0) cursor.getString(mimeIdx) else null+            if (mime == null || mime == StructuredPostal.CONTENT_ITEM_TYPE) {+                cursor.postalAddress()?.let { out.add(it) }+            }+        }+    }+    return out.toList()+}++/**+ * Read the postal address at [rowUri] (a StructuredPostal data row). Prefers the+ * pre-formatted [StructuredPostal.FORMATTED_ADDRESS]; if that's blank it+ * composes the address from the individual components. Returns null when the+ * row is gone or holds no address. May throw [SecurityException] when the+ * caller lacks read access to the row.+ */+fun readAddress(context: Context, rowUri: Uri): String? {+    context.contentResolver.query(rowUri, POSTAL_PROJECTION, null, null, null)?.use { cursor ->+        if (!cursor.moveToFirst()) return null+        return cursor.postalAddress()+    }+    return null+}++/**+ * Resolve all postal addresses of the whole contact at [contactUri] (as returned+ * by `ActivityResultContracts.PickContact`). Looks up the contact id, then reads+ * its StructuredPostal data rows (de-duplicated, order preserved). Returns empty+ * when the contact has no postal address. Requires READ_CONTACTS (may throw+ * [SecurityException]).+ */+fun readContactAddresses(context: Context, contactUri: Uri): List<String> {+    val contactId = context.contentResolver.query(+        contactUri,+        arrayOf(ContactsContract.Contacts._ID),+        null,+        null,+        null,+    )?.use { c -> if (c.moveToFirst()) c.getString(0) else null } ?: return emptyList()++    val selection =+        "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} = ?"+    val args = arrayOf(+        contactId,+        StructuredPostal.CONTENT_ITEM_TYPE,+    )+    val out = LinkedHashSet<String>()+    context.contentResolver.query(+        ContactsContract.Data.CONTENT_URI,+        POSTAL_PROJECTION,+        selection,+        args,+        null,+    )?.use { cursor ->+        while (cursor.moveToNext()) {+            cursor.postalAddress()?.let { out.add(it) }+        }+    }+    return out.toList()+}++/** Pull a display address out of a StructuredPostal cursor row: the formatted+ *  address if present, else the composed components. Null when the row is empty. */+private fun Cursor.postalAddress(): String? {+    fun col(name: String): String? = getColumnIndex(name)+        .takeIf { it >= 0 }+        ?.let { getString(it) }+        ?.takeIf { it.isNotBlank() }++    col(StructuredPostal.FORMATTED_ADDRESS)+        ?.normalizeAddress()+        ?.takeIf { it.isNotBlank() }+        ?.let { return it }++    return listOfNotNull(+        col(StructuredPostal.STREET),+        col(StructuredPostal.CITY),+        col(StructuredPostal.REGION),+        col(StructuredPostal.POSTCODE),+        col(StructuredPostal.COUNTRY),+    ).joinToString(", ").ifBlank { null }+}++/** Collapse a multi-line postal address to one comma-separated line so it makes+ *  a valid single-line search query (FORMATTED_ADDRESS embeds newlines). Runs of+ *  whitespace within a line collapse to a single space; blank lines are dropped. */+internal fun String.normalizeAddress(): String =+    lines()+        .map { it.replace(Regex("\\s+"), " ").trim() }+        .filter { it.isNotEmpty() }+        .joinToString(", ")++/** Projection for the Android 17 session URI: MIMETYPE (to spot the postal row)+ *  plus the postal columns. */+private val SESSION_PROJECTION = arrayOf(+    ContactsContract.Data.MIMETYPE,+    StructuredPostal.FORMATTED_ADDRESS,+    StructuredPostal.STREET,+    StructuredPostal.CITY,+    StructuredPostal.REGION,+    StructuredPostal.POSTCODE,+    StructuredPostal.COUNTRY,+)++private val POSTAL_PROJECTION = arrayOf(+    StructuredPostal.FORMATTED_ADDRESS,+    StructuredPostal.STREET,+    StructuredPostal.CITY,+    StructuredPostal.REGION,+    StructuredPostal.POSTCODE,+    StructuredPostal.COUNTRY,+)
maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.ktindex 1e7ce6c5b0..61e65fee43 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/SelectedFeatureViewModel.kt@@ -89,6 +89,18 @@ class SelectedFeatureViewModel(application: Application): AndroidViewModel(appli         _inactiveNavigation.value = route     } +    /**+     * Park the current route, if the selection is one, before selecting something else.+     *+     * Tapping a place while directions are up should keep the route recoverable rather than+     * discard it, which is why every such tap handler did this. They each did it with an+     * unchecked `as SpecificFeature.Route` guarded by a separate `is` check, so the cast was+     * only safe by inspection; reading the selection once here makes it safe by construction.+     */+    fun stashRouteSelection() {+        (_selectedFeature.value as? SpecificFeature.Route)?.let { _inactiveNavigation.value = it }+    }+     /**      * Keyless Google Maps enrichment (rating, reviews, hours, photos, price,      * popular times, …) for the currently selected restaurant or generic place.