Modern Apps git

← Modern-Apps.git

maps: repair broken merge plus length limit fixes

Commit
d5d8aa626cd22929f4d85470be05f6dbcc4b9567
Author
vayun-mathur <[email protected]>
When
2026-09-19 16:48 UTC (2 months ago)
Parents
8437447

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 713e601bdb..f9207f23b8 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -298,10 +298,6 @@ fun Navigation(             MapPage(backStack, viewModel, savedPlacesViewModel, searchViewModel, settingsViewModel, parkingViewModel, transitViewModel)         }         entry<Route.SettingsPage>(metadata = ListDetailPage()) {-        entry<Route.MapPage> {-            MapPage(backStack, viewModel, savedPlacesViewModel, poiViewModel, searchViewModel, settingsViewModel, parkingViewModel, transitViewModel)-        }-        entry<Route.SettingsPage> {             MapSettingsPage(backStack, settingsViewModel)         }         entry<Route.SavedPlacesPage>(metadata = ListDetailPage()) {
maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.ktindex 7ace0bfb5f..021e19c1a0 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt@@ -9,14 +9,11 @@ package com.vayunmathur.maps.data object MapPreferences {     const val KEY_VOICE_GUIDANCE = "voice_guidance_enabled"     const val KEY_THEME_MODE = "theme_mode"-<<<<<<< Updated upstream     /**      * True-3D-sphere globe instead of the flat Mercator map. Maps-only: no other      * app reads this key or passes `globeEnabled`, so they keep the flat map.      */     const val KEY_GLOBE = "globe_enabled"-=======->>>>>>> Stashed changes      // Layer toggles surfaced in the P6 layers sheet.     const val KEY_LAYER_TRAFFIC = "layer_traffic"
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 90504e8c6a..6738878b99 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/BottomSheetContent.kt@@ -13,10 +13,6 @@ import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.IconHome-import com.vayunmathur.library.ui.IconWork-import com.vayunmathur.library.ui.LocalContentColor import com.vayunmathur.maps.R import com.vayunmathur.maps.data.SavedPlace import com.vayunmathur.maps.data.SpecificFeature@@ -29,8 +25,6 @@ import com.vayunmathur.maps.util.SavedPlacesViewModel import com.vayunmathur.maps.util.SelectedFeatureViewModel import com.vayunmathur.maps.util.TransitStopsViewModel import com.vayunmathur.maps.util.rememberPlacePanelState-import com.vayunmathur.maps.util.formatDistance-import org.maplibre.spatialk.geojson.Position  /**  * Everything on the map's bottom sheet below the fold — what expanding it reveals.@@ -156,155 +150,6 @@ fun BottomSheetContent(  */ @Composable private fun AdminLabelHeader(name: String, wikipedia: String?, modifier: Modifier = Modifier) {-fun RouteSheet(-    selectedFeature: SpecificFeature.Route,-    route: Map<RouteService.TravelMode, RouteService.RouteType?>,-    selectedRouteType: RouteService.TravelMode,-    setSelectedRouteType: (RouteService.TravelMode) -> Unit,-    navState: NavigationSessionManager.NavState = NavigationSessionManager.NavState.Idle,-    userPosition: Position? = null,-) {-    Column {-        PrimaryTabRow(route.entries.indexOfFirst { it.key == selectedRouteType }) {-            route.entries.forEach {-                Tab(-                    selectedRouteType == it.key,-                    { setSelectedRouteType(it.key) }) {-                    val label = when(it.key) {-                        RouteService.TravelMode.WALK -> stringResource(R.string.travel_mode_walk)-                        RouteService.TravelMode.BICYCLE -> stringResource(R.string.travel_mode_bicycle)-                        RouteService.TravelMode.DRIVE -> stringResource(R.string.travel_mode_drive)-                        RouteService.TravelMode.TRANSIT -> stringResource(R.string.travel_mode_transit)-                    }-                    Text(label)-                }-            }-        }-        val routeForMode = route[selectedRouteType]-        if(routeForMode != null) {-            if(routeForMode !is RouteService.EmptyRoute) {-                ListItem({ Text(routeForMode.duration.toString()) }, supportingContent = {-                    Text(formatDistance(routeForMode.distanceMeters))-                })-                // "Start Navigation" only when we have a concrete-                // Route (steps + polyline) and aren't already in-                // an active navigation session.-                //-                // We also hide the button for TRANSIT: the-                // navigation engine snaps GPS to the route-                // polyline and computes ETA from progress along-                // it, which doesn't model trains/buses well, and-                // mid-trip recalc would replace transit steps-                // with walking steps. Users can still see the-                // transit step list; we just don't offer to-                // "drive" them through it.-                val lastWaypoint = selectedFeature.waypoints.lastOrNull()-                val canStart = routeForMode is RouteService.Route &&-                        navState is NavigationSessionManager.NavState.Idle &&-                        selectedRouteType != RouteService.TravelMode.TRANSIT &&-                        lastWaypoint != null-                if (routeForMode is RouteService.Route &&-                    navState is NavigationSessionManager.NavState.Idle &&-                    selectedRouteType != RouteService.TravelMode.TRANSIT-                ) {-                    val context = LocalContext.current-                    Button(-                        onClick = {-                            if (lastWaypoint == null) return@Button-                            val destPos = lastWaypoint.position-                            val destName = lastWaypoint.name-                            val intent = Intent(context, NavigationService::class.java)-                            context.startForegroundService(intent)-                            NavigationSessionManager.init(context)-                            NavigationSessionManager.start(-                                route = routeForMode,-                                mode = selectedRouteType,-                                destination = destPos,-                                destinationLabel = destName,-                            )-                        },-                        enabled = canStart,-                        modifier = Modifier-                            .fillMaxWidth()-                            .padding(horizontal = 16.dp, vertical = 8.dp),-                        colors = ButtonDefaults.buttonColors(-                            containerColor = MaterialTheme.colorScheme.primary,-                            contentColor = MaterialTheme.colorScheme.onPrimary,-                        ),-                    ) {-                        Text(stringResource(R.string.nav_action_start))-                    }-                }-                // Taxi/ride option (P20): offer a ride for this route's origin→destination-                // via the MA taxi app. Origin is the first waypoint (or the user's live-                // position when the route starts "from here"); destination is the last.-                val taxiOrigin = selectedFeature.waypoints.firstOrNull()-                val taxiDest = selectedFeature.waypoints.lastOrNull()-                // Origin may be "from here" (a null waypoint) → the user's live position; the-                // destination must be a real waypoint, so it never falls back to userPosition.-                val taxiOriginPos = taxiOrigin?.position ?: userPosition-                val taxiDestPos = taxiDest?.position-                if (selectedFeature.waypoints.size >= 2 && taxiOriginPos != null && taxiDestPos != null) {-                    RouteTaxiOption(-                        originLat = taxiOriginPos.latitude,-                        originLng = taxiOriginPos.longitude,-                        originLabel = taxiOrigin?.name,-                        destLat = taxiDestPos.latitude,-                        destLng = taxiDestPos.longitude,-                        destLabel = taxiDest.name,-                    )-                }-                Spacer(Modifier.height(8.dp))-            }-            LazyColumn(verticalArrangement = Arrangement.spacedBy(2.dp)) {-                when (routeForMode) {-                    is RouteService.Route -> {-                        itemsIndexed(routeForMode.step) { idx, it ->-                            Card(shape = verticalShape(idx, routeForMode.step.size)) {-                                ListItem({-                                    Text(it.navInstruction.instructions)-                                }, leadingContent = {-                                    it.navInstruction.maneuver.iconContent()?.let { icon ->-                                        icon(Modifier, LocalContentColor.current)-                                    }-                                })-                            }-                        }-                    }--                    is RouteService.EmptyRoute -> {-                        item {-                            ListItem({-                                Text(stringResource(R.string.no_route_found))-                            })-                        }-                    }-                }-            }-        } else {-            ListItem({-                Text(stringResource(R.string.generating_route))-            })-        }-    }-}--/**- * The taxi/ride option shown under a route (P20): if the MA taxi app is installed, offer a ride- * for the route's origin→destination. When the signature-guarded estimate resolves, the fare/ETA- * is shown inline; "Book ride" opens the taxi app with the trip pre-filled. If taxi is absent the- * option renders nothing; if the estimate is unavailable it degrades to a launch-only button — no- * crash either way.- */-@Composable-private fun RouteTaxiOption(-    originLat: Double,-    originLng: Double,-    originLabel: String?,-    destLat: Double,-    destLng: Double,-    destLabel: String?,-) {     val context = LocalContext.current     Row(modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {         Text(
maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.ktindex 2cac89102c..9e20b5794e 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapContentBox.kt@@ -57,10 +57,10 @@ internal fun MapPageScope.MapContentBox(     // Earth) — there are no POIs to filter up there.     val showBodySwitch = globeEnabled && camera.position.zoom < GLOBE_DETAIL_ZOOM ||         body == MapBody.Moon-            // No app bar. The map is the whole screen and every piece of chrome floats over it,-            // which is also what keeps the renderer's surface edge-to-edge — a padded parent here-            // is what used to leave a dead strip along the navigation bar.-            Box(Modifier.fillMaxSize()) {+    // No app bar. The map is the whole screen and every piece of chrome floats over it,+    // which is also what keeps the renderer's surface edge-to-edge — a padded parent here+    // is what used to leave a dead strip along the navigation bar.+    Box(Modifier.fillMaxSize()) {                 MapSurface(                     camera = camera,                     chrome = chrome,
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 4dac653bc8..2d85bdeecc 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -62,12 +62,6 @@ import com.vayunmathur.maps.ui.streetview.StreetViewPegman import com.vayunmathur.maps.ui.theme.MapChromeMetrics import com.vayunmathur.maps.ui.map.MapChromeState import com.vayunmathur.maps.util.DeparturesState-import com.vayunmathur.maps.data.parse-import com.vayunmathur.maps.util.MapTileCache-import com.vayunmathur.maps.util.OfflineRouter-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.MoonAssetLoader@@ -88,29 +82,6 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.buildJsonArray-import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.jsonArray-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive-import kotlinx.serialization.json.put-import kotlinx.serialization.json.putJsonObject-import org.maplibre.compose.camera.CameraPosition-import org.maplibre.compose.camera.rememberCameraState-import org.maplibre.compose.map.GestureOptions-import org.maplibre.compose.map.MapOptions-import org.maplibre.compose.map.MaplibreMap-import org.maplibre.compose.map.OrnamentOptions-import org.maplibre.compose.map.RenderOptions-import org.maplibre.compose.style.BaseStyle-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.rememberReorderableLazyListState-import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.maps.R as MapsR  /** Cold-start camera: San Francisco at z14, where the baked POIs are dense enough to see. */@@ -136,8 +107,6 @@ fun MapPage(     parkingViewModel: com.vayunmathur.maps.util.ParkingViewModel,     transitViewModel: com.vayunmathur.maps.util.TransitStopsViewModel, ) {-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) {-    val selectedFeature by viewModel.selectedFeature.collectAsState()     val context = LocalContext.current     val coroutineScope = rememberCoroutineScope()     val messenger = rememberMessenger()@@ -163,103 +132,6 @@ fun MapPage(backStack: NavBackStack<Route>, viewModel: SelectedFeatureViewModel,     // learned ceiling from Details traps the taller Reviews list.     val poiSection by viewModel.poiSection.collectAsState()     val currentPoiInfo by viewModel.currentPoiInfo.collectAsState()--    // Parking memory (P9): the single active parking spot (pin + recall).-    val parkingSpot by parkingViewModel.active.collectAsState()-    var showParkingSheet by remember { mutableStateOf(false) }--    // Map-layer visibility toggles (P6 layers sheet, persisted via DataStore).-    val trafficEnabled by settingsViewModel.trafficLayer.collectAsState()-    val satelliteEnabled by settingsViewModel.satelliteLayer.collectAsState()-    val safetyEnabled by settingsViewModel.safetyLayer.collectAsState()-    val transitEnabled by settingsViewModel.transitLayer.collectAsState()-    var showLayersSheet by remember { mutableStateOf(false) }--    // Effective map palette (P14): resolve the P6 Map-theme setting against the-    // OS dark mode using the same rule DynamicTheme applies (a null override =-    // follow the system). Drives the runtime dark recolor of the basemap below,-    // so the map flips light<->dark together with the rest of the app chrome.-    val themeMode by settingsViewModel.themeMode.collectAsState()-    val darkMap = themeMode.darkOverride ?: isSystemInDarkTheme()--    // Public transit (P10): nearby stops overlay + live departure board. Stops-    // are only fetched/drawn while the Transit layer is on.-    val transitStops by transitViewModel.stops.collectAsState()-    val selectedTransitStop by transitViewModel.selected.collectAsState()-    val departuresState by transitViewModel.departures.collectAsState()--    // Google POI overlay pins (viewport scrape → custom layer, replacing the-    // suppressed native basemap POIs).-    val googlePins by poiViewModel.pins.collectAsState()--    // Search-result pins (from the Google search page) drawn on the map.-    val searchResults by searchViewModel.results.collectAsState()--    // Live family-location pins (P18): the findfamily bound service is bound-    // while this screen is composed (see rememberFamilyMembers' DisposableEffect)-    // and pushes updates only while bound. Empty when findfamily is absent.-    val familyMembers by com.vayunmathur.maps.ipc.rememberFamilyMembers()--    val camera = rememberCameraState(CameraPosition(target = Position(-118.243683,34.052235), zoom = 5.0))--    LaunchedEffect(camera.position, transitEnabled) {-        if (camera.position.zoom >= 11.0) {-            delay(300) // Debounce traffic loading-            val projection = camera.projection-            if (projection != null) {-                val bbox = projection.queryVisibleBoundingBox()-                // Only fetch live traffic when the layer is on. Fetching drives-                // trafficVersion, which in turn mounts the loopback traffic tile-                // layer (see MyMapLayers); skipping it when off avoids needless-                // network + native work and keeps the tile layer unmounted.-                if (trafficEnabled) {-                    // Load traffic for all four corners to ensure the current view is covered-                    OfflineRouter.ensureTrafficLoadedNative(bbox.north, bbox.east, true)-                    OfflineRouter.ensureTrafficLoadedNative(bbox.north, bbox.west, true)-                    OfflineRouter.ensureTrafficLoadedNative(bbox.south, bbox.east, true)-                    OfflineRouter.ensureTrafficLoadedNative(bbox.south, bbox.west, true)-                }-                // Refresh the Google POI overlay for the idle viewport (VM-                // debounces + LRU-caches the keyless scrape).-                poiViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west)-                // Refresh nearby transit stops (P10) only while the layer is on-                // (VM debounces + caches; wide views clear the overlay).-                if (transitEnabled) {-                    transitViewModel.onViewport(bbox.north, bbox.east, bbox.south, bbox.west)-                }-            }-        }-    }--    // Online-tiles-only: the basemap always streams live (offline zone tile-    // packs were removed). Offline ROUTING still works via the downloaded graph.-    val hybridUrl = MapTileCache.BASEMAP_PMTILES_URL--    // Inside MapPage-    var json by remember { mutableStateOf<String?>(null) }--    // Read the style asset on Dispatchers.IO (file open), then the hybrid-    // patch step is light enough to stay on the same coroutine. Re-runs on a-    // theme change (darkMap) so the recolored style reloads and flips live.-    LaunchedEffect(hybridUrl, darkMap) {-        val updatedStyle = withContext<String>(Dispatchers.IO) {-            val rawStyle = context.assets.open("style.json").bufferedReader().readText()-            patchStyleForHybrid(-                rawStyle,-                MapTileCache.BASEMAP_PMTILES_URL,-                hybridUrl,-                darkMap,-            )-        }-        Log.d(-            "MapPage",-            "style patched base=${MapTileCache.BASEMAP_PMTILES_URL} hybrid=$hybridUrl " +-                "darkMap=$darkMap jsonLen=${updatedStyle.length}",-        )-        json = updatedStyle-    }--    // --- LOCATION & OSM INITIALIZATION ---     val userPosition by viewModel.userPosition.collectAsState()     val userBearing by viewModel.userBearing.collectAsState()     val userHeadingAccuracy by viewModel.userHeadingAccuracy.collectAsState()@@ -450,151 +322,4 @@ internal fun stopNavigation(context: android.content.Context) {     context.stopService(         android.content.Intent(context, com.vayunmathur.maps.util.NavigationService::class.java)     )-// Native basemap layers suppressed at runtime — amenities are Google-only now-// (custom overlay layer). Keeping this in code (vs editing style.json) makes it-// OTA-swappable per Decision D1.-private val SUPPRESSED_LAYERS = setOf("pois")--fun patchStyleForHybrid(-    jsonString: String,-    baseLocalUrl: String,-    hybridUrl: String,-    dark: Boolean = false,-): String {-    val json = Json { ignoreUnknownKeys = true }-    val root = json.parseToJsonElement(jsonString).jsonObject--    val newSources = buildJsonObject {-        putJsonObject("protomaps_base") {-            put("type", "vector")-            put("url", baseLocalUrl)-        }-        putJsonObject("protomaps_hybrid") {-            put("type", "vector")-            put("url", hybridUrl)-        }-    }--    val oldLayers = root["layers"]?.jsonArray ?: buildJsonArray {}-    val newLayers = buildJsonArray {-        oldLayers.forEach { layerElement ->-            val layer = layerElement.jsonObject-            val id = layer["id"]?.jsonPrimitive?.content ?: ""-            val type = layer["type"]?.jsonPrimitive?.content ?: ""--            // Suppress native basemap POIs at runtime (Decision D1) — amenities-            // are Google-only now, rendered on the custom overlay layer. Dropping-            // the source layer here (rather than editing style.json) keeps it-            // OTA-swappable. Also drops the would-be _base/_hybrid variants.-            if (id in SUPPRESSED_LAYERS) return@forEach--            // Dark palette (P14): recolor the base Protomaps paint at runtime so-            // we don't duplicate the 3544-line style.json. Only colour keys are-            // swapped; width/opacity/dasharray expressions are preserved.-            val darkPaint = if (dark) darkenPaint(id, layer["paint"] as? JsonObject) else null--            if (type == "background") {-                add(buildJsonObject {-                    layer.forEach { (k, v) -> if (!(dark && k == "paint")) put(k, v) }-                    if (darkPaint != null) put("paint", darkPaint)-                })-            } else {-                // Zoom 0-7: Base Local-                add(buildJsonObject {-                    layer.forEach { (k, v) -> if (!(dark && k == "paint")) put(k, v) }-                    if (darkPaint != null) put("paint", darkPaint)-                    put("id", "${id}_base")-                    put("source", "protomaps_base")-                    put("maxzoom", 7)-                })-                // Zoom 7+: Hybrid (Local Only)-                add(buildJsonObject {-                    layer.forEach { (k, v) -> if (!(dark && k == "paint")) put(k, v) }-                    if (darkPaint != null) put("paint", darkPaint)-                    put("id", "${id}_hybrid")-                    put("source", "protomaps_hybrid")-                    put("minzoom", 7)-                })-            }-        }-    }--    return buildJsonObject {-        root.forEach { (k, v) -> if (k != "sources" && k != "layers") put(k, v) }-        put("sources", newSources)-        put("layers", newLayers)-    }.toString()-}--/**- * Rebuild a layer's `paint` for the dark palette (P14): copy every property- * verbatim and only swap the colour keys, so zoom-driven width/opacity/dasharray- * expressions keep working. `text-halo-width` etc. are left untouched. Layers- * without a colour key (e.g. the icon-only `roads_oneway`) come back unchanged.- */-private fun darkenPaint(id: String, paint: JsonObject?): JsonObject? {-    if (paint == null) return null-    val base = darkBaseColor(id)-    val (text, halo) = darkTextColors(id)-    return buildJsonObject {-        paint.forEach { (k, v) ->-            when (k) {-                "background-color", "fill-color", "line-color" -> put(k, base)-                "text-color" -> put(k, text)-                "text-halo-color" -> put(k, halo)-                else -> put(k, v)-            }-        }-    }-}--/**- * Dark fill/line/background colour for a base Protomaps layer. Keyed by layer id- * (the style's ids are stable), falling through prefix/substring rules for the- * many road variants. Casing colours must be matched before the highway/major- * rules because e.g. `roads_highway_casing_early` contains both tokens.- */-private fun darkBaseColor(id: String): String = when {-    id == "background" || id == "earth" -> "#1b1d22"-    id == "water" -> "#0d1b2a"-    id == "water_stream" || id == "water_river" -> "#24455f"-    id == "landcover" -> "#1f2a22"-    id == "landuse_park" -> "#1e2b20"-    id == "landuse_urban_green" -> "#23362a"-    id == "landuse_hospital" -> "#2b2528"-    id == "landuse_industrial" -> "#20262b"-    id == "landuse_school" -> "#282520"-    id == "landuse_beach" -> "#2c2a22"-    id == "landuse_zoo" -> "#213030"-    id == "landuse_aerodrome" -> "#212228"-    id == "landuse_runway" -> "#2b2d33"-    id == "landuse_pedestrian" -> "#242229"-    id == "landuse_pier" -> "#202225"-    id.startsWith("landuse") -> "#1f2126"-    id == "buildings" -> "#22262c"-    id.startsWith("boundaries") -> "#4a4f57"-    id == "roads_rail" -> "#3a3e45"-    id.startsWith("roads_runway") || id.startsWith("roads_taxiway") -> "#2b2d33"-    id.contains("casing") -> "#111318"-    id.startsWith("roads_tunnels") -> "#2b2e35"-    id.contains("highway") || id.contains("major") || id.contains("link") -> "#464b54"-    id.startsWith("roads") -> "#34383f"-    else -> "#26282e"-}--/**- * Dark (text-color, text-halo-color) for a label/POI symbol layer: light text on- * a near-black halo so labels stay legible over the dark basemap. Water labels- * keep a blue tint over the dark-navy water.- */-private fun darkTextColors(id: String): Pair<String, String> = when (id) {-    "places_locality" -> "#e4e8ee" to "#101216"-    "places_country" -> "#9aa0aa" to "#101216"-    "places_region" -> "#80868f" to "#101216"-    "places_subplace" -> "#b0b6c0" to "#101216"-    "earth_label_islands" -> "#9aa0aa" to "#101216"-    "water_waterway_label", "water_label_ocean", "water_label_lakes" -> "#6f8fce" to "#0d1b2a"-    "roads_shields" -> "#c8ccd4" to "#101216"-    "roads_labels_major", "roads_labels_minor", "address_label" -> "#b8bdc6" to "#101216"-    else -> "#c9ced6" to "#101216" }
maps/src/main/java/com/vayunmathur/maps/ui/MapScaleBar.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapScaleBar.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapScaleBar.ktindex 481b9dc7a1..fba86c7546 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapScaleBar.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapScaleBar.kt@@ -38,13 +38,6 @@ fun MapScaleBar(zoom: Double, latitude: Double, modifier: Modifier = Modifier) {     val imperial = isImperialUnits()     val (barMeters, label) = scaleBar(metersPerDp * MAX_BAR_DP, imperial)     val barWidth = (barMeters / metersPerDp).toFloat().dp-    // Ground resolution (meters per screen pixel) at this latitude and zoom.-    val metersPerPixel = 156543.03392 * cos(latitude * PI / 180.0) / 2.0.pow(zoom)-    if (!metersPerPixel.isFinite() || metersPerPixel <= 0.0) return--    val imperial = isImperialUnits()-    val (barMeters, label) = scaleBar(metersPerPixel * maxBarPx, imperial)-    val barWidth = with(density) { (barMeters / metersPerPixel).toFloat().toDp() }      Surface(         modifier = modifier,@@ -106,7 +99,6 @@ private fun niceRoundDistance(maxMeters: Double): Double {  * in METERS (for bar width) paired with the display label.  */ internal fun scaleBar(maxMeters: Double, imperial: Boolean): Pair<Double, String> {-private fun scaleBar(maxMeters: Double, imperial: Boolean): Pair<Double, String> {     if (imperial) {         val maxMiles = maxMeters / 1609.34         return if (maxMiles < 1.0) {
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.ktindex 0deb0d9678..4e118bd84c 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurface.kt@@ -15,8 +15,6 @@ import com.vayunmathur.library.map.LayerOptions import com.vayunmathur.library.map.MapBody import com.vayunmathur.library.map.MapOptions import com.vayunmathur.library.map.MoonTextures-import com.vayunmathur.library.map.RegionLevel-import com.vayunmathur.library.map.RegionMask import com.vayunmathur.library.map.TileSource import com.vayunmathur.library.map.UserPuck import com.vayunmathur.library.map.VectorMap@@ -188,19 +186,7 @@ fun MapSurface(         moonTextures = moonTextures,         options = mapOptions,         userPuck = userPuck,-        // The selected city/region's outline, dimmed outside. Derived from the sheet's own-        // selection rather than the tap, so a region picked from search masks too — and the-        // label's own kind supplies the admin level, because the point alone is inside every-        // region above it and would otherwise resolve to the smallest, not the one named.-        regionMask = when (selectedFeature) {-            is SpecificFeature.Admin0Label ->-                selectedFeature.position?.let { RegionMask(it, RegionLevel.COUNTRY) }-            is SpecificFeature.Admin1Label ->-                selectedFeature.position?.let { RegionMask(it, RegionLevel.REGION) }-            is SpecificFeature.Admin2Label ->-                selectedFeature.position?.let { RegionMask(it, RegionLevel.LOCALITY) }-            else -> null-        },+        regionMask = regionMaskFor(selectedFeature),         // The live traffic overlay: baked geometry gated by [LayerOptions.traffic] above,         // coloured by this id->ARGB table. Null clears it (toggle off / nothing to draw).         trafficColors = trafficColors,@@ -356,7 +342,3 @@ fun MapSurface(         )     } }--// STATION_POI_TYPE, TaggedFeature,-// traffic constants, prefetchTrafficSquares, buildTrafficColorTable, pinFeatures-// and buildMarkers live in MapSurfaceHelpers.kt.
maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.ktindex 1092d9c3aa..14dc9bcce0 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/MapSurfaceHelpers.kt@@ -256,3 +256,36 @@ internal suspend fun openVehicleTrip(     sheetState?.partialExpand()     return true }++/**+ * The selected city/region's outline, dimmed outside. Derived from the sheet's own+ * selection rather than the tap, so a region picked from search masks too — and the+ * label's own kind supplies the admin level, because the point alone is inside every+ * region above it and would otherwise resolve to the smallest, not the one named.+ */+internal fun regionMaskFor(+    selectedFeature: com.vayunmathur.maps.data.SpecificFeature?,+): com.vayunmathur.library.map.RegionMask? = when (selectedFeature) {+    is com.vayunmathur.maps.data.SpecificFeature.Admin0Label ->+        selectedFeature.position?.let {+            com.vayunmathur.library.map.RegionMask(+                it,+                com.vayunmathur.library.map.RegionLevel.COUNTRY,+            )+        }+    is com.vayunmathur.maps.data.SpecificFeature.Admin1Label ->+        selectedFeature.position?.let {+            com.vayunmathur.library.map.RegionMask(+                it,+                com.vayunmathur.library.map.RegionLevel.REGION,+            )+        }+    is com.vayunmathur.maps.data.SpecificFeature.Admin2Label ->+        selectedFeature.position?.let {+            com.vayunmathur.library.map.RegionMask(+                it,+                com.vayunmathur.library.map.RegionLevel.LOCALITY,+            )+        }+    else -> null+}
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.ktindex 24d0c3363f..d7b4d3c717 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouter.kt@@ -17,72 +17,9 @@ import kotlinx.coroutines.withContext import com.vayunmathur.library.map.GeoPoint  object OfflineRouter {-    private var serverPort = 0-    val trafficTileUrl: String get() = if (serverPort > 0) "http://localhost:$serverPort/traffic/{z}/{x}/{y}" else ""-     init {         System.loadLibrary("offlinerouter")-        startLocalTileServer()-    }--    private fun startLocalTileServer() {-        Thread {-            try {-                // Bind to loopback ONLY. The previous `ServerSocket(0)` defaulted-                // to 0.0.0.0 which let any app on the device (or anything on the-                // local network) hit /traffic/{z}/{x}/{y}.-                val serverSocket = java.net.ServerSocket(0, 50, InetAddress.getLoopbackAddress())-                serverPort = serverSocket.localPort-                Log.d("OFFLINE_ROUTER", "Tile server started on port $serverPort (loopback only)")-                // Hand each client to a small pool so a slow tile doesn't block-                // MapLibre's concurrent tile requests behind the global mutex.-                val pool = Executors.newFixedThreadPool(4)-                while (!serverSocket.isClosed) {-                    val client = serverSocket.accept()-                    // Prevent a half-open / hung client from holding a worker forever.-                    runCatching { client.soTimeout = 5_000 }-                    pool.execute { handleClient(client) }-                }-            } catch (e: Exception) {-                Log.e("OFFLINE_ROUTER", "Tile server error", e)-            }-        }.start()-    }--    private fun handleClient(client: java.net.Socket) {-        try {-            val reader = client.getInputStream().bufferedReader()-            val firstLine = reader.readLine() ?: return-            -            // Expected: GET /traffic/{z}/{x}/{y} HTTP/1.1-            val parts = firstLine.split(" ")-            if (parts.size >= 2 && parts[0] == "GET") {-                val pathParts = parts[1].removePrefix("/traffic/").split("/")-                if (pathParts.size == 3) {-                    val z = pathParts[0].toIntOrNull() ?: 0-                    val x = pathParts[1].toIntOrNull() ?: 0-                    val y = pathParts[2].substringBefore("?").toIntOrNull() ?: 0-                    -                    val bytes = getTrafficTileNative(z, x, y)-                    val output = client.getOutputStream()-                    if (bytes != null) {-                        output.write(("HTTP/1.1 200 OK\r\n" +-                                "Content-Type: application/vnd.mapbox-vector-tile\r\n" +-                                "Content-Encoding: gzip\r\n" +-                                "Content-Length: ${bytes.size}\r\n" +-                                "Access-Control-Allow-Origin: *\r\n\r\n").toByteArray())-                        output.write(bytes)-                    } else {-                        output.write("HTTP/1.1 204 No Content\r\n\r\n".toByteArray())-                    }-                    output.flush()-                }-            }-        } catch (e: Exception) {-            Log.e("OFFLINE_ROUTER", "Error handling client", e)-        } finally {-            client.close()-        }+        OfflineRouterTraffic.startLocalTileServer()     }      private external fun init(basePath: String): Boolean
maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.ktindex 57d4ad7370..d4fde64fac 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/OfflineRouterTraffic.kt@@ -123,4 +123,72 @@ internal object OfflineRouterTraffic {         lastPublished = null         _trafficComponents.value = TrafficComponents.EMPTY     }++    /**+     * Loopback-only tile server for `/traffic/{z}/{x}/{y}`, extracted from+     * [OfflineRouter] to keep that file under the length limit. Started once+     * from [OfflineRouter]'s init; the tile bytes still come from+     * [OfflineRouter.getTrafficTileNative].+     */+    private var serverPort = 0++    internal fun startLocalTileServer() {+        Thread {+            try {+                // Bind to loopback ONLY. The previous `ServerSocket(0)` defaulted+                // to 0.0.0.0 which let any app on the device (or anything on the+                // local network) hit /traffic/{z}/{x}/{y}.+                val serverSocket = java.net.ServerSocket(0, 50, java.net.InetAddress.getLoopbackAddress())+                serverPort = serverSocket.localPort+                android.util.Log.d("OFFLINE_ROUTER", "Tile server started on port $serverPort (loopback only)")+                // Hand each client to a small pool so a slow tile doesn't block+                // concurrent tile requests behind the global mutex.+                val pool = java.util.concurrent.Executors.newFixedThreadPool(4)+                while (!serverSocket.isClosed) {+                    val client = serverSocket.accept()+                    // Prevent a half-open / hung client from holding a worker forever.+                    runCatching { client.soTimeout = 5_000 }+                    pool.execute { handleClient(client) }+                }+            } catch (e: Exception) {+                android.util.Log.e("OFFLINE_ROUTER", "Tile server error", e)+            }+        }.start()+    }++    private fun handleClient(client: java.net.Socket) {+        try {+            val reader = client.getInputStream().bufferedReader()+            val firstLine = reader.readLine() ?: return++            // Expected: GET /traffic/{z}/{x}/{y} HTTP/1.1+            val parts = firstLine.split(" ")+            if (parts.size >= 2 && parts[0] == "GET") {+                val pathParts = parts[1].removePrefix("/traffic/").split("/")+                if (pathParts.size == 3) {+                    val z = pathParts[0].toIntOrNull() ?: 0+                    val x = pathParts[1].toIntOrNull() ?: 0+                    val y = pathParts[2].substringBefore("?").toIntOrNull() ?: 0++                    val bytes = OfflineRouter.getTrafficTileNative(z, x, y)+                    val output = client.getOutputStream()+                    if (bytes != null) {+                        output.write(("HTTP/1.1 200 OK\r\n" ++                                "Content-Type: application/vnd.mapbox-vector-tile\r\n" ++                                "Content-Encoding: gzip\r\n" ++                                "Content-Length: ${bytes.size}\r\n" ++                                "Access-Control-Allow-Origin: *\r\n\r\n").toByteArray())+                        output.write(bytes)+                    } else {+                        output.write("HTTP/1.1 204 No Content\r\n\r\n".toByteArray())+                    }+                    output.flush()+                }+            }+        } catch (e: Exception) {+            android.util.Log.e("OFFLINE_ROUTER", "Error handling client", e)+        } finally {+            client.close()+        }+    } }
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 419806e868..baed9fd8a7 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -296,6 +296,9 @@ object PoiIndex {     private var mapped: Mapped? = null     private var tried = false +    /** Read access for the extension queries in PoiIndexSpatial.kt / PoiIndexWords.kt. */+    internal fun mappedForQuery(): Mapped? = mapped+     /** True once both side files were mapped successfully. */     val available: Boolean get() = mapped != null @@ -667,66 +670,10 @@ object PoiIndex {         return out.take(limit).map { it.record }     } -    /**-     * Nearest POIs to ([lat],[lon]) within [maxMeters], closest first (bbox-     * pre-filter + squared-distance sort). Names are decoded only for the-     * returned winners. Empty when the index isn't loaded.-     */-    fun nearest(-        lat: Double,-        lon: Double,-        limit: Int = 20,-        maxMeters: Double = 250.0,-    ): List<PoiRecord> {-        val m = mapped ?: return emptyList()-        val dLat = maxMeters / 111_320.0-        val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(1e-6)-        val dLon = maxMeters / (111_320.0 * cosLat)-        val minLatE7 = ((lat - dLat) * 1e7).toInt()-        val maxLatE7 = ((lat + dLat) * 1e7).toInt()-        val minLonE7 = ((lon - dLon) * 1e7).toInt()-        val maxLonE7 = ((lon + dLon) * 1e7).toInt()--        val hits = ArrayList<Hit>()-        m.forEachInBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) { i, latE7, lonE7 ->-            hits.add(Hit(i, distanceSq(latE7 / 1e7, lonE7 / 1e7, lat, lon)))-            true-        }-        // Stable, so records at an equal distance stay in file order — the tie-break the-        // scan this replaced had, and what the equivalence test pins.-        hits.sortBy { it.distSq }-        return hits.take(limit).map { m.record(it.idx) }-    }--    /**-     * All POIs whose coordinate falls inside the [west]..[east] × [south]..[north]-     * bounding box, capped at [cap]. Names are decoded for each returned record.-     * Empty when the index isn't loaded; used to drive the ambient offline pin-     * overlay (P29).-     */-    fun inViewport(-        west: Double,-        south: Double,-        east: Double,-        north: Double,-        cap: Int = 300,-    ): List<PoiRecord> {-        val m = mapped ?: return emptyList()-        if (cap <= 0) return emptyList()-        val minLatE7 = (south * 1e7).toInt()-        val maxLatE7 = (north * 1e7).toInt()-        val minLonE7 = (west * 1e7).toInt()-        val maxLonE7 = (east * 1e7).toInt()-        val out = ArrayList<PoiRecord>(minOf(cap, m.count))-        m.forEachInBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) { i, _, _ ->-            out.add(m.record(i))-            out.size < cap-        }-        return out-    }+    // Spatial queries (nearest/inViewport) live in PoiIndexSpatial.kt as+    // extensions, alongside the grid they walk.      private class Ranked(val record: PoiRecord, val rank: Int, val distSq: Double)-    private class Hit(val idx: Int, val distSq: Double)      /**      * The attributes of the [ordinal]th index record, or null when there are none.
maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.ktindex fc7c92c163..83f6d417f6 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndexSpatial.kt@@ -66,3 +66,63 @@ internal fun PoiIndex.Mapped.forEachInCells(         if (!onHit(ordinal, latE7(ordinal), lonE7(ordinal))) return     } }++private class Hit(val idx: Int, val distSq: Double)++/**+ * Nearest POIs to ([lat],[lon]) within [maxMeters], closest first (bbox+ * pre-filter + squared-distance sort). Names are decoded only for the+ * returned winners. Empty when the index isn't loaded.+ */+internal fun PoiIndex.nearest(+    lat: Double,+    lon: Double,+    limit: Int = 20,+    maxMeters: Double = 250.0,+): List<PoiIndex.PoiRecord> {+    val m = mappedForQuery() ?: return emptyList()+    val dLat = maxMeters / 111_320.0+    val cosLat = Math.cos(Math.toRadians(lat)).coerceAtLeast(1e-6)+    val dLon = maxMeters / (111_320.0 * cosLat)+    val minLatE7 = ((lat - dLat) * 1e7).toInt()+    val maxLatE7 = ((lat + dLat) * 1e7).toInt()+    val minLonE7 = ((lon - dLon) * 1e7).toInt()+    val maxLonE7 = ((lon + dLon) * 1e7).toInt()++    val hits = ArrayList<Hit>()+    m.forEachInBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) { i, latE7, lonE7 ->+        hits.add(Hit(i, distanceSq(latE7 / 1e7, lonE7 / 1e7, lat, lon)))+        true+    }+    // Stable, so records at an equal distance stay in file order — the tie-break the+    // scan this replaced had, and what the equivalence test pins.+    hits.sortBy { it.distSq }+    return hits.take(limit).map { m.record(it.idx) }+}++/**+ * All POIs whose coordinate falls inside the [west]..[east] × [south]..[north]+ * bounding box, capped at [cap]. Names are decoded for each returned record.+ * Empty when the index isn't loaded; used to drive the ambient offline pin+ * overlay (P29).+ */+internal fun PoiIndex.inViewport(+    west: Double,+    south: Double,+    east: Double,+    north: Double,+    cap: Int = 300,+): List<PoiIndex.PoiRecord> {+    val m = mappedForQuery() ?: return emptyList()+    if (cap <= 0) return emptyList()+    val minLatE7 = (south * 1e7).toInt()+    val maxLatE7 = (north * 1e7).toInt()+    val minLonE7 = (west * 1e7).toInt()+    val maxLonE7 = (east * 1e7).toInt()+    val out = ArrayList<PoiIndex.PoiRecord>(minOf(cap, m.count))+    m.forEachInBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) { i, _, _ ->+        out.add(m.record(i))+        out.size < cap+    }+    return out+}