maps: overlay manifest download plus settings
- Commit
6e04f8305ef81fa2fae36eb3e24eda671d662ed6- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 00:05 UTC (1 month ago)
- Parents
d5202e5
Diff
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 5e0008f4b0..aa6eb8e920 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -37,6 +37,12 @@ dependencies { implementation(project(":library:downloadservice")) + // WorkManager: the map-overlay check worker outlives the settings screen.+ implementation(project(":library:work"))++ // Manifest JSON parsing (pure JVM: unit-testable, unlike org.json).+ implementation(libs.kotlinx.serialization.json)+ // Android Auto (P12): AndroidX Car App Library. `app` provides the // CarAppService/Session/Screen/template model; `app-projected` provides the // phone-projected (Android Auto) host connection. Only pulled into the car
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 3a1bfec987..ebd946aa45 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/MapPreferences.kt@@ -39,8 +39,16 @@ object MapPreferences { const val KEY_LAST_LON = "last_lon" const val KEY_LAST_LAT = "last_lat" + /**+ * Auto-update map data on unmetered networks. On: [MapOverlayWorker]+ * checks the manifest periodically over WiFi; off: updates only happen+ * from the Settings row.+ */+ const val KEY_MAP_AUTO_UPDATE = "map_auto_update"+ const val DEFAULT_VOICE_GUIDANCE = true const val DEFAULT_GLOBE = false+ const val DEFAULT_MAP_AUTO_UPDATE = true const val DEFAULT_LAYER_TRAFFIC = true const val DEFAULT_LAYER_SATELLITE = false const val DEFAULT_LAYER_SAFETY = false
maps/src/main/java/com/vayunmathur/maps/ui/settings/MapSettingsPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/settings/MapSettingsPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/settings/MapSettingsPage.ktindex 4355381231..b20d412cb7 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/settings/MapSettingsPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/settings/MapSettingsPage.kt@@ -9,6 +9,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api@@ -23,6 +24,7 @@ import com.vayunmathur.maps.R import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.maps.Route import com.vayunmathur.maps.data.ThemeMode+import com.vayunmathur.maps.util.MapOverlayWorker import com.vayunmathur.maps.util.MapSettingsViewModel import com.vayunmathur.library.util.NavBackStack @@ -47,6 +49,11 @@ fun MapSettingsPage(backStack: NavBackStack<Route>, viewModel: MapSettingsViewMo val voice by viewModel.voiceGuidance.collectAsState() val globe by viewModel.globeEnabled.collectAsState() val googleServices by viewModel.googleServices.collectAsState()+ val autoUpdate by viewModel.mapAutoUpdate.collectAsState()+ val appliedSeq by viewModel.overlayAppliedSeq.collectAsState()+ val pendingBytes by viewModel.overlayPendingBytes.collectAsState()+ val lastCheck by viewModel.overlayLastCheck.collectAsState()+ val context = LocalContext.current // Pre-resolve option labels — the SettingsSelectRow `label` lambda is a plain // (non-@Composable) function, so stringResource can't be called inside it.@@ -114,6 +121,42 @@ fun MapSettingsPage(backStack: NavBackStack<Route>, viewModel: MapSettingsViewMo leadingContent = { IconStar() }, ) }++ SettingsSection(title = stringResource(R.string.settings_section_map_data)) {+ com.vayunmathur.library.ui.SettingsRow(+ title = stringResource(R.string.settings_map_update),+ supportingText = updateSupportingText(appliedSeq, pendingBytes, lastCheck),+ onClick = { MapOverlayWorker.checkManual(context) },+ leadingContent = { IconStar() },+ )+ SettingsSwitchRow(+ title = stringResource(R.string.settings_map_auto_update),+ supportingText = stringResource(R.string.settings_map_auto_update_desc),+ checked = autoUpdate,+ onCheckedChange = { viewModel.setMapAutoUpdate(it) },+ leadingContent = { IconStar() },+ )+ } } } }++/**+ * One-line overlay status: applied sequence, pending bytes, or last check.+ * Formatting lives here (not in strings.xml) because it composes three+ * live values no single string template covers.+ */+@Composable+private fun updateSupportingText(appliedSeq: Long, pendingBytes: Long, lastCheck: Long): String? {+ if (pendingBytes > 0) {+ val mb = pendingBytes / 1_000_000+ return stringResource(R.string.settings_map_update_pending, mb)+ }+ if (appliedSeq > 0) {+ return stringResource(R.string.settings_map_update_applied, appliedSeq)+ }+ if (lastCheck > 0) {+ return stringResource(R.string.settings_map_update_current)+ }+ return null+}
maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.ktnew file mode 100644index 0000000000..f8df5e124f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlay.kt@@ -0,0 +1,184 @@+package com.vayunmathur.maps.util++import java.io.File+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.long+import kotlinx.serialization.json.int++/**+ * The client half of incremental map updates: the `planet3.manifest.json`+ * model, the on-disk overlay layout, and the queries the Settings UI and the+ * check worker drive.+ *+ * Layout under the app's external files dir (next to `basemap.mamaps`):+ * ```+ * basemap.mamaps the immutable base (never rewritten)+ * overlay/manifest.json the pinned manifest (last applied check)+ * overlays/<seq:04d>/overlay-<n:04d>.mamaps downloaded segments+ * ```+ * Segments download through the existing `.part` + Range resume path+ * (`runDownloadsCore` with per-segment SHA-256), sequentially, so peak+ * transient disk is one segment — never old+new full worlds. The base is+ * never copied or patched; the version switch to `(base, seq)` is an atomic+ * handle-set swap in the Phase 3 reader work.+ *+ * Manifest JSON is parsed by hand (org.json ships on every device): the+ * schema is small and a new dependency for one file is not worth it.+ */+object MapOverlay {+ /** Where [MapTileCache.BASEMAP_ARCHIVE_FILE] is checked for updates. */+ const val MANIFEST_URL = "https://data.maproj.org/planet3.manifest.json"++ /** Pinned manifest filename (under [OVERLAY_ROOT]). */+ const val MANIFEST_FILE = "manifest.json"++ /** Overlay root dir name (under external files). */+ const val OVERLAY_ROOT = "overlays"++ /** Manifest format version this client understands. */+ const val MANIFEST_VERSION = 1++ /** One overlay segment reference from the manifest. */+ data class SegmentRef(+ val url: String,+ val len: Long,+ val sha256: String,+ val seq: Int,+ )++ /** One independently chunked sidecar section (large kinds; empty today). */+ data class SectionRef(+ val kind: Int,+ val url: String,+ val len: Long,+ val sha256: String,+ val chunkSize: Long,+ val chunkHashes: List<String>,+ )++ /** Parsed manifest: base pin + overlay sequence + what to fetch. */+ data class Manifest(+ val version: Int,+ val baseUrl: String,+ val baseBuildId: Long,+ val baseLen: Long,+ val overlaySeq: Long,+ val overlayBuildId: Long,+ val segments: List<SegmentRef>,+ val sections: List<SectionRef>,+ val minClient: Int,+ )++ /**+ * Parse [text] into a [Manifest], or null when it is not a manifest this+ * client can apply (wrong version, missing fields, min_client above us).+ * Never throws: a bad manifest is "no update", not a crash.+ */+ fun parse(text: String): Manifest? = runCatching {+ val root = Json.parseToJsonElement(text).jsonObject+ val version = root.getValue("version").jsonPrimitive.int+ if (version != MANIFEST_VERSION) return null+ val minClient = root["min_client"]?.jsonPrimitive?.int ?: 1+ if (minClient > MANIFEST_VERSION) return null+ val base = root.getValue("base").jsonObject+ val segments = root.getValue("segments").jsonArray.toSegments()+ val sections = root["sections"]?.jsonArray?.toSections().orEmpty()+ Manifest(+ version = version,+ baseUrl = base.getValue("url").jsonPrimitive.content,+ baseBuildId = parseBuildId(base.getValue("build_id").jsonPrimitive.content),+ baseLen = base.getValue("len").jsonPrimitive.long,+ overlaySeq = root.getValue("overlay_seq").jsonPrimitive.long,+ overlayBuildId = parseBuildId(root.getValue("overlay_build_id").jsonPrimitive.content),+ segments = segments,+ sections = sections,+ minClient = minClient,+ )+ }.getOrNull()++ private fun JsonArray.toSegments(): List<SegmentRef> {+ val out = ArrayList<SegmentRef>(size)+ for (element in this) {+ val s = element.jsonObject+ out.add(+ SegmentRef(+ url = s.getValue("url").jsonPrimitive.content,+ len = s.getValue("len").jsonPrimitive.long,+ sha256 = s.getValue("sha256").jsonPrimitive.content,+ seq = s.getValue("seq").jsonPrimitive.int,+ ),+ )+ }+ return out.sortedBy { it.seq }+ }++ private fun JsonArray.toSections(): List<SectionRef> {+ val out = ArrayList<SectionRef>(size)+ for (element in this) {+ val s = element.jsonObject+ val hashes = s.getValue("chunk_hashes").jsonArray+ out.add(+ SectionRef(+ kind = s.getValue("kind").jsonPrimitive.int,+ url = s.getValue("url").jsonPrimitive.content,+ len = s.getValue("len").jsonPrimitive.long,+ sha256 = s.getValue("sha256").jsonPrimitive.content,+ chunkSize = s.getValue("chunk_size").jsonPrimitive.long,+ chunkHashes = List(hashes.size) { hashes[it].jsonPrimitive.content },+ ),+ )+ }+ return out.sortedBy { it.kind }+ }++ /**+ * A `0x…` hex build id from the manifest, or 0 when it does not parse.+ * Build ids are opaque equality tokens here (match the base or refuse).+ */+ fun parseBuildId(raw: String): Long =+ raw.removePrefix("0x").removePrefix("0X").toLongOrNull(16) ?: 0L++ /** On-disk file for segment [seg] of overlay [overlaySeq] under [root]. */+ fun segmentFile(root: File, overlaySeq: Long, seg: SegmentRef): File =+ File(File(root, "$OVERLAY_ROOT/%04d".format(overlaySeq)), "overlay-%04d.mamaps".format(seg.seq))++ /** Whether every segment of [manifest] is present and length-plausible. */+ fun isApplied(root: File, manifest: Manifest): Boolean =+ manifest.segments.all { seg ->+ val f = segmentFile(root, manifest.overlaySeq, seg)+ f.isFile && f.length() == seg.len+ }++ /** Segments of [manifest] still missing or short on disk. */+ fun missing(root: File, manifest: Manifest): List<SegmentRef> =+ manifest.segments.filter { seg ->+ val f = segmentFile(root, manifest.overlaySeq, seg)+ !f.isFile || f.length() != seg.len+ }++ /**+ * Total bytes still to fetch for [manifest] (missing segments only).+ * What the Settings row shows as pending.+ */+ fun pendingBytes(root: File, manifest: Manifest): Long =+ missing(root, manifest).sumOf { it.len }++ /** The pinned manifest on disk, or null when no check ever applied. */+ fun pinned(root: File): Manifest? {+ val f = File(File(root, OVERLAY_ROOT), MANIFEST_FILE)+ if (!f.isFile) return null+ return runCatching { parse(f.readText()) }.getOrNull()+ }++ /** Pin [text] (already parsed) as the applied manifest. */+ fun pin(root: File, text: String) {+ val dir = File(root, OVERLAY_ROOT)+ dir.mkdirs()+ File(dir, MANIFEST_FILE).writeText(text)+ }+}
maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.ktnew file mode 100644index 0000000000..98c84b71e7--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapOverlayWorker.kt@@ -0,0 +1,201 @@+package com.vayunmathur.maps.util++import android.content.Context+import androidx.work.BackoffPolicy+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import androidx.work.workDataOf+import com.vayunmathur.library.downloadservice.ModelDownloadItem+import com.vayunmathur.library.downloadservice.downloadModels+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.net.URL+import java.util.concurrent.TimeUnit++/**+ * Checks for and fetches incremental map updates (Phase 2: download + store).+ *+ * One run: fetch `planet3.manifest.json` (kilobytes, any network), compare+ * its overlay sequence against the pinned manifest, and — when newer —+ * download the missing segments sequentially through the shared+ * [downloadModels] path (`.part` + Range resume, per-segment SHA-256, atomic+ * rename). Segments land under `overlays/<seq>/`; the base+ * `basemap.mamaps` is never touched, so peak transient disk is one segment.+ * On success the manifest text is pinned; the atomic reader swap to+ * `(base, seq)` is Phase 3 work — until then new segments sit inert on disk+ * and the map keeps reading the base.+ *+ * Two entry points: [checkAuto] (UNMETERED periodic check, gated on the+ * auto-update toggle) and [checkManual] (user-tapped, any connectivity).+ * Both KEEP an in-flight run rather than doubling it.+ */+class MapOverlayWorker(context: Context, params: WorkerParameters) :+ CoroutineWorker(context, params) {++ override suspend fun doWork(): Result {+ val manifestUrl = inputData.getString(KEY_MANIFEST_URL) ?: MapOverlay.MANIFEST_URL+ val ds = DataStoreUtils.getInstance(applicationContext)+ val root = applicationContext.getExternalFilesDir(null) ?: return Result.failure()+ // No base, no overlay: the startup gate owns the full download.+ if (!File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).exists()) {+ Log.status(TAG, "no base archive; skipping overlay check")+ return Result.success()+ }+ val text = fetchText(manifestUrl) ?: return Result.retry()+ val manifest = MapOverlay.parse(text)+ if (manifest == null) {+ Log.status(TAG, "manifest unparseable or too new; skipping")+ return Result.success()+ }+ ds.setString(KEY_LAST_MANIFEST, text.take(MANIFEST_TEXT_CAP))+ ds.setLong(KEY_LAST_CHECK, System.currentTimeMillis())+ val pinned = MapOverlay.pinned(root)+ if (pinned != null && pinned.overlaySeq >= manifest.overlaySeq) {+ Log.status(TAG, "overlay seq ${manifest.overlaySeq} already applied")+ return Result.success()+ }+ // Base mismatch refuses: an overlay for another build must never apply.+ if (!baseMatches(root, manifest)) {+ Log.status(TAG, "overlay seq ${manifest.overlaySeq} is for another base; skipping")+ return Result.success()+ }+ val missing = MapOverlay.missing(root, manifest)+ if (missing.isEmpty()) {+ MapOverlay.pin(root, text)+ ds.setLong(KEY_APPLIED_SEQ, manifest.overlaySeq)+ return Result.success()+ }+ ds.setLong(KEY_PENDING_BYTES, missing.sumOf { it.len })+ val items = missing.map { seg ->+ val file = MapOverlay.segmentFile(root, manifest.overlaySeq, seg)+ val rel = root.toURI().relativize(file.toURI()).path+ ModelDownloadItem(+ url = seg.url,+ fileName = rel,+ description = "Map update ${manifest.overlaySeq} part ${seg.seq + 1}/${manifest.segments.size}",+ sha256 = seg.sha256,+ )+ }+ // Sequential, one segment at a time: peak transient is one segment.+ var ok = true+ for (item in items) {+ if (!downloadModels(applicationContext, ds, listOf(item))) {+ ok = false+ break+ }+ }+ if (!ok) return Result.retry()+ if (!MapOverlay.isApplied(root, manifest)) {+ Log.status(TAG, "segments landed but failed verification")+ return Result.retry()+ }+ MapOverlay.pin(root, text)+ ds.setLong(KEY_APPLIED_SEQ, manifest.overlaySeq)+ ds.setLong(KEY_PENDING_BYTES, 0L)+ Log.status(TAG, "overlay seq ${manifest.overlaySeq} stored (${items.size} segments)")+ return Result.success()+ }++ /**+ * Whether the local base is the build [manifest] was made for. The base+ * header's `build_id` lives at bytes 16..24 (little-endian u64); the+ * manifest pins it as hex. A missing/unreadable header refuses.+ */+ private fun baseMatches(root: File, manifest: MapOverlay.Manifest): Boolean {+ if (manifest.baseLen > 0) {+ val len = File(root, MapTileCache.BASEMAP_ARCHIVE_FILE).length()+ if (len != manifest.baseLen) {+ Log.status(TAG, "base len $len != manifest ${manifest.baseLen}")+ return false+ }+ }+ val id = readBaseBuildId(File(root, MapTileCache.BASEMAP_ARCHIVE_FILE)) ?: return false+ if (id != manifest.baseBuildId) {+ Log.status(TAG, "base build ${id.toString(16)} != manifest ${manifest.baseBuildId.toString(16)}")+ return false+ }+ return true+ }++ companion object {+ private const val TAG = "MapOverlay"+ private const val KEY_MANIFEST_URL = "manifest_url"+ /** DataStore keys the Settings row reads (last check text is capped). */+ const val KEY_LAST_CHECK = "overlay_last_check"+ const val KEY_APPLIED_SEQ = "overlay_applied_seq"+ const val KEY_PENDING_BYTES = "overlay_pending_bytes"+ const val KEY_LAST_MANIFEST = "overlay_last_manifest"+ private const val MANIFEST_TEXT_CAP = 8 * 1024++ private const val MAX_RUN_ATTEMPTS = 6+ private const val BACKOFF_SECONDS = 30L++ /** Periodic auto check: UNMETERED only (multi-hundred-MB segments). */+ fun checkAuto(context: Context) =+ enqueue(context, MapOverlay.MANIFEST_URL, requireUnmetered = true)++ /** Manual check from Settings: any connectivity. */+ fun checkManual(context: Context) =+ enqueue(context, MapOverlay.MANIFEST_URL, requireUnmetered = false)++ private fun enqueue(context: Context, manifestUrl: String, requireUnmetered: Boolean) {+ val request = OneTimeWorkRequestBuilder<MapOverlayWorker>()+ .setInputData(workDataOf(KEY_MANIFEST_URL to manifestUrl))+ .setConstraints(+ Constraints.Builder()+ .setRequiredNetworkType(+ if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED,+ )+ .build(),+ )+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_SECONDS, TimeUnit.SECONDS)+ .build()+ WorkManager.getInstance(context).enqueueUniqueWork(+ if (requireUnmetered) UNIQUE_AUTO else UNIQUE_MANUAL,+ ExistingWorkPolicy.KEEP,+ request,+ )+ }++ private const val UNIQUE_AUTO = "map_overlay_auto"+ private const val UNIQUE_MANUAL = "map_overlay_manual"++ /** Attempt count guard lives in doWork's caller: WorkManager retries. */+ fun maxAttempts(): Int = MAX_RUN_ATTEMPTS+ }+}++/** GET [url] as text, or null on any failure (caller retries). */+private suspend fun fetchText(url: String): String? = runCatching {+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ (URL(url).openConnection() as java.net.HttpURLConnection).run {+ connectTimeout = 30_000+ readTimeout = 30_000+ requestMethod = "GET"+ try {+ connect()+ if (responseCode != java.net.HttpURLConnection.HTTP_OK) return@run null+ inputStream.bufferedReader().use { it.readText() }+ } finally {+ disconnect()+ }+ }+ }+}.getOrNull()++/** The base archive's header `build_id` (bytes 16..24 LE), or null. */+private fun readBaseBuildId(file: File): Long? = runCatching {+ if (!file.isFile || file.length() < 24) return null+ java.io.RandomAccessFile(file, "r").use { raf ->+ raf.seek(16)+ val buf = ByteArray(8)+ raf.readFully(buf)+ java.nio.ByteBuffer.wrap(buf).order(java.nio.ByteOrder.LITTLE_ENDIAN).long+ }+}.getOrNull()
maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.ktindex 50eb4cef15..ff5d7b4045 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapSettingsViewModel.kt@@ -57,6 +57,40 @@ class MapSettingsViewModel(application: Application) : AndroidViewModel(applicat fun setGlobeEnabled(enabled: Boolean) = launch { ds.setBoolean(MapPreferences.KEY_GLOBE, enabled) } + // --- Map updates ---------------------------------------------------------++ /**+ * Auto-update map data on unmetered networks. Drives the periodic+ * [MapOverlayWorker] check; the Settings row checks manually regardless.+ */+ val mapAutoUpdate: StateFlow<Boolean> = boolPref(+ MapPreferences.KEY_MAP_AUTO_UPDATE, MapPreferences.DEFAULT_MAP_AUTO_UPDATE,+ )++ /** Overlay sequence already stored on disk (0 = base only). */+ val overlayAppliedSeq: StateFlow<Long> =+ ds.longFlow(MapOverlayWorker.KEY_APPLIED_SEQ, 0L).stateIn(+ viewModelScope, SharingStarted.Eagerly,+ ds.getLong(MapOverlayWorker.KEY_APPLIED_SEQ) ?: 0L,+ )++ /** Bytes still to fetch for the pending overlay (0 = nothing pending). */+ val overlayPendingBytes: StateFlow<Long> =+ ds.longFlow(MapOverlayWorker.KEY_PENDING_BYTES, 0L).stateIn(+ viewModelScope, SharingStarted.Eagerly,+ ds.getLong(MapOverlayWorker.KEY_PENDING_BYTES) ?: 0L,+ )++ /** Last manifest check time (millis, 0 = never). */+ val overlayLastCheck: StateFlow<Long> =+ ds.longFlow(MapOverlayWorker.KEY_LAST_CHECK, 0L).stateIn(+ viewModelScope, SharingStarted.Eagerly,+ ds.getLong(MapOverlayWorker.KEY_LAST_CHECK) ?: 0L,+ )++ fun setMapAutoUpdate(enabled: Boolean) =+ launch { ds.setBoolean(MapPreferences.KEY_MAP_AUTO_UPDATE, enabled) }+ // --- Layers sheet ------------------------------------------------------ val trafficLayer: StateFlow<Boolean> = boolPref(
maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.ktindex 990833dca9..fb4f5cd45e 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt@@ -21,6 +21,10 @@ object MapTileCache { const val BASEMAP_ARCHIVE_URL = "https://data.maproj.org/planet3.mamaps" + /** Where the incremental-update manifest lives (see `util/MapOverlay`). */+ const val BASEMAP_MANIFEST_URL =+ "https://data.maproj.org/planet3.manifest.json"+ /** * The single source of truth for the streamed basemap PMTiles URL. *
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 76301f7407..b2a6d8b2d4 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -378,6 +378,20 @@ <string name="settings_google_services">Google services</string> <!-- Settings: Google services toggle description. --> <string name="settings_google_services_desc">Place details, reviews, Street View</string>+ <!-- Settings: section header for offline map data. Noun. -->+ <string name="settings_section_map_data">Offline map data</string>+ <!-- Settings: check-for-updates row title. Verb phrase. -->+ <string name="settings_map_update">Check for map updates</string>+ <!-- Settings: update row when bytes are pending. %1$d = MB. -->+ <string name="settings_map_update_pending"><xliff:g id="mb" example="340">%1$d</xliff:g> MB update downloading</string>+ <!-- Settings: update row when an overlay is applied. %1$d = sequence. -->+ <string name="settings_map_update_applied">Map data update <xliff:g id="seq" example="7">%1$d</xliff:g> installed</string>+ <!-- Settings: update row when the base is current. -->+ <string name="settings_map_update_current">Map data is up to date</string>+ <!-- Settings: auto-update toggle title. Noun phrase. -->+ <string name="settings_map_auto_update">Auto-update maps</string>+ <!-- Settings: auto-update toggle description. -->+ <string name="settings_map_auto_update_desc">Download updates on Wi-Fi only</string> <!-- Body switch: Earth option. Noun. --> <string name="body_earth">Earth</string> <!-- Body switch: Moon option. Noun. -->
maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.ktnew file mode 100644index 0000000000..1d341ed0ff--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/util/MapOverlayTest.kt@@ -0,0 +1,109 @@+package com.vayunmathur.maps.util++import java.io.File+import java.nio.file.Files+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins [MapOverlay]'s manifest parsing and on-disk queries.+ *+ * The oracle is the schema `tile_build/src/manifest.rs` renders: the JSON+ * below mirrors it field for field, so a drift between publisher and client+ * fails here rather than as a silent "no update" on device.+ */+class MapOverlayTest {++ private var temp: File? = null++ @AfterTest+ fun tearDown() {+ temp?.deleteRecursively()+ temp = null+ }++ private fun root(): File {+ val dir = Files.createTempDirectory("overlay").toFile()+ temp = dir+ return dir+ }++ private fun manifestJson(seq: Long = 7): String =+ """{"version":1,"base":{"url":"https://data.maproj.org/planet3.mamaps","build_id":"0x0000000000001234","len":78017648928},"overlay_seq":$seq,"overlay_build_id":"0x000000000000abcd","segments":[{"url":"https://data.maproj.org/overlays/0007/overlay-0000.mamaps","len":11,"sha256":"abc","seq":0}],"sections":[],"min_client":1}"""++ @Test+ fun parses_the_published_schema() {+ val m = MapOverlay.parse(manifestJson())!!+ assertEquals(1, m.version)+ assertEquals("https://data.maproj.org/planet3.mamaps", m.baseUrl)+ assertEquals(0x1234L, m.baseBuildId)+ assertEquals(78017648928L, m.baseLen)+ assertEquals(7L, m.overlaySeq)+ assertEquals(0xabcdL, m.overlayBuildId)+ assertEquals(1, m.segments.size)+ assertEquals(11L, m.segments[0].len)+ assertTrue(m.sections.isEmpty())+ }++ @Test+ fun refuses_a_newer_manifest_version() {+ assertNull(MapOverlay.parse(manifestJson().replace("\"version\":1", "\"version\":99")))+ }++ @Test+ fun refuses_a_min_client_above_us() {+ assertNull(MapOverlay.parse(manifestJson().replace("\"min_client\":1", "\"min_client\":99")))+ }++ @Test+ fun refuses_garbage_quietly() {+ assertNull(MapOverlay.parse("not json"))+ assertNull(MapOverlay.parse("{}"))+ }++ @Test+ fun missing_counts_only_absent_segments() {+ val dir = root()+ val m = MapOverlay.parse(manifestJson())!!+ assertEquals(1, MapOverlay.missing(dir, m).size)+ assertEquals(11L, MapOverlay.pendingBytes(dir, m))+ assertFalse(MapOverlay.isApplied(dir, m))++ val seg = MapOverlay.segmentFile(dir, m.overlaySeq, m.segments[0])+ seg.parentFile?.mkdirs()+ seg.writeBytes(ByteArray(11))+ assertTrue(MapOverlay.missing(dir, m).isEmpty())+ assertEquals(0L, MapOverlay.pendingBytes(dir, m))+ assertTrue(MapOverlay.isApplied(dir, m))+ }++ @Test+ fun short_files_do_not_count_as_applied() {+ val dir = root()+ val m = MapOverlay.parse(manifestJson())!!+ val seg = MapOverlay.segmentFile(dir, m.overlaySeq, m.segments[0])+ seg.parentFile?.mkdirs()+ seg.writeBytes(ByteArray(5))+ assertFalse(MapOverlay.isApplied(dir, m))+ assertEquals(11L, MapOverlay.pendingBytes(dir, m))+ }++ @Test+ fun pin_round_trips_the_manifest() {+ val dir = root()+ assertNull(MapOverlay.pinned(dir))+ val text = manifestJson()+ MapOverlay.pin(dir, text)+ assertEquals(7L, MapOverlay.pinned(dir)!!.overlaySeq)+ }++ @Test+ fun build_ids_parse_hex_with_prefix() {+ assertEquals(0x1234L, MapOverlay.parseBuildId("0x0000000000001234"))+ assertEquals(0L, MapOverlay.parseBuildId("garbage"))+ }+}