various fixes
- Commit
2abf04c6d27a610a153fcfb65f03b67bd6233452- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-06 19:50 UTC (3 months ago)
- Parents
953499d
Diff
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 50057d7c9c..b0748f0157 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -172,6 +172,13 @@ Summed old per-crate locks (before workspace) = 712 total (641 excluding voxels) | `com.google.zxing:core` | `3.5.4` | `messages` (QR), `library:ocr`, `pdf` | Old, community fork `zxing-cpp` preferred | `libs.versions.toml:83` | | `com.google.ai.edge.litertlm:litertlm-android` | `0.14.0` experimental | `openassistant` | Google AI Edge experimental, GPU backend `libLiteRtTopKOpenClSampler.so`, requires `kotlinx-coroutines 1.11.0` conflict win | `openassistant/build.gradle.kts`, `libs.versions.toml:30` | +### Vendored Assets (compiled in, no runtime fetch)++| Asset | Source | Licence | Notes | File |+|---|---|---|---|---|+| POI sprite sheet, entries 1-53 | `protomaps/basemaps-assets` `sprites/v4/light@2x` | BSD-3-Clause | Vendored unchanged from upstream; also mirrored at `data.vayunmathur.com/basemaps-assets/`. Compiled into `libmap_renderer.so`, never fetched at runtime | `library/map/src/main/rust/assets/sprites/sprites@2x.{png,json}` |+| POI sprite sheet, entries 54-57 (`fuel`, `hotel`, `bank`, `atm`) | `mapbox/maki` glyphs on a badge lifted from the Protomaps sheet | **CC0 1.0** (public domain, no attribution required) | Protomaps' style draws none of these four kinds, so no upstream sheet has ever carried an icon for them — but the `maps` app has offered Gas, Hotels and ATM chips all along. Regenerate with `analysis/spritepack/pack.py` | same as above |+ ### Low Risk / Platform (Google/JetBrains) — Not Critical Well-maintained: `androidx.*` (`core-ktx 1.19.0`, `lifecycle 2.11.0`, `room3 3.0.2`, `sqlite 2.7.0`, `work 2.11.2`, `datastore`, `camera`, `webkit`, `browser 1.9.0`, `biometric`, `glance`, `exifinterface`, `credentials`, `autofill`), `composeBom 2026.06.01`, `material3 1.5.0-alpha23`, `material 1.14.0`, `foundation 1.12.0-beta02`, `ink 1.1.0-alpha04`, `navigation3`, `media3-exoplayer 1.11.0-beta01`, `okhttp 4.12.0` + `okio 3.17.0`, `kotlin 2.4.0` + `coroutines 1.11.0` + `serialization-json 1.11.0` + `datetime 0.8.0`, `ksp 2.3.10`, `protobuf 4.36.0-RC1` / `protobuf-javalite 4.35.0`, `libphonenumber 9.0.34`, `fhir-model 1.0.0-beta02`, `health/connect-client 1.2.0-alpha04`, etc.
appstore/src/main/java/com/vayunmathur/appstore/data/RestrictedPackages.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/RestrictedPackages.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/RestrictedPackages.ktindex 42a4f9c21e..039680796b 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/RestrictedPackages.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/RestrictedPackages.kt@@ -1,7 +1,6 @@ package com.vayunmathur.appstore.data import android.content.Context-import android.content.pm.ApplicationInfo import androidx.core.content.edit /**@@ -12,9 +11,10 @@ import androidx.core.content.edit * source and shell are allowed to install <package>`, which is not something the user can act * on — so a pending update for it is a notification that can only ever be dismissed. *- * [KNOWN] is consulted on GrapheneOS only; on stock Android these are ordinary updatable apps.- * [recordIfRestricted] adds whatever else the installer finds out the hard way, so a- * restriction that isn't listed here costs one failed install rather than one per update check.+ * [KNOWN] is consulted on GrapheneOS-derived builds only; on stock Android these are ordinary+ * updatable apps. [recordIfRestricted] adds whatever else the installer finds out the hard way,+ * so a restriction that isn't listed here costs one failed install rather than one per update+ * check. */ object RestrictedPackages { @@ -24,11 +24,15 @@ object RestrictedPackages { private val KNOWN = setOf(ANDROID_AUTO) /**- * GrapheneOS's own app store, preinstalled on every build — and the first-party source the- * restricted installs are reserved for. Present as a system package only on GrapheneOS,- * which makes it a cheaper and steadier signal than any build fingerprint or property.+ * The system feature GrapheneOS declares, and which Modern Apps OS inherits from it.+ *+ * The old check looked for `app.grapheneos.apps` as a system package, which is GrapheneOS's+ * own store — Modern Apps OS ships this store instead and so was misread as stock Android,+ * losing both the restricted-package list and the Sandboxed Google Play section. The+ * feature is true on both and false on stock, which is the distinction that actually+ * matters here. */- private const val GRAPHENEOS_APPS = "app.grapheneos.apps"+ private const val GRAPHENEOS_FEATURE = "grapheneos.version" /** The distinguishing part of the OS's refusal, matched case-insensitively. */ private const val RESTRICTED_MESSAGE = "first party package source"@@ -58,8 +62,13 @@ object RestrictedPackages { private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) - private fun isGrapheneOS(context: Context): Boolean = runCatching {- val info = context.packageManager.getApplicationInfo(GRAPHENEOS_APPS, 0)- (info.flags and ApplicationInfo.FLAG_SYSTEM) != 0- }.getOrDefault(false)+ /**+ * Whether this is GrapheneOS or a build derived from it, such as Modern Apps OS.+ *+ * Also gates the Sandboxed Google Play section: those packages only work alongside the+ * gmscompat layer, which is part of the OS, so offering them on stock Android would offer+ * an install that cannot function.+ */+ fun isGrapheneOS(context: Context): Boolean =+ context.packageManager.hasSystemFeature(GRAPHENEOS_FEATURE) }
appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.ktindex 9b0868a0ec..9c2a6df4f4 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/SandboxedGooglePlay.kt@@ -1,18 +1,19 @@ package com.vayunmathur.appstore.data +import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepo+ /** * The GrapheneOS "Sandboxed Google Play" bundle: Google's own Play components, installed as * ordinary unprivileged user apps rather than as a privileged system blob. * * These three packages are **not** installable from Google Play, so the store never fetches * them through the anonymous-Play path. They come from GrapheneOS's app release server- * (apps.grapheneos.org), which re-hosts Google's official signed APKs alongside signed repo- * metadata. Installing them reuses the store's ordinary signed-APK download and- * user-confirmed [android.content.pm.PackageInstaller] flow — the same- * [com.vayunmathur.appstore.data.installer.InstallCoordinator] `installFromUrl` path every- * F-Droid / Modern Apps listing uses, and the same mechanism GrapheneOS's own Apps client- * uses for Sandboxed Google Play. The gmscompat shim that lets these run without the- * privileged access the real Play client expects lives in the OS, not here.+ * (apps.grapheneos.org), which re-hosts Google's official signed APKs alongside a signed+ * index — see [com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepository], which is what+ * supplies the download URLs, the expected signing certificates and the per-APK hashes.+ * Installing them reuses the store's ordinary verify-then-commit+ * [android.content.pm.PackageInstaller] flow. The gmscompat shim that lets these run without+ * the privileged access the real Play client expects lives in the OS, not here. * * Order matters at install. Google Services Framework and Play Services provide the * accounts, the GSF ID and the provider the store front-end talks to, so they go on before@@ -31,13 +32,7 @@ object SandboxedGooglePlay { /** Stable id for the curated home section, shared by the ViewModel and the home screen. */ const val SECTION_ID = "sandboxed-google-play" - /**- * GrapheneOS's app release server. The three packages, and the signed metadata that- * verifies them, are served from here — nothing is fetched from Google Play.- */- const val RELEASE_SERVER = "https://apps.grapheneos.org"-- /** Human-readable names, shown before richer metadata has been fetched. */+ /** Human-readable names, shown before the signed index has been fetched. */ val DISPLAY_NAMES: Map<String, String> = mapOf( GSF to "Google Services Framework", GMS to "Google Play Services",@@ -50,17 +45,14 @@ object SandboxedGooglePlay { */ val PACKAGES: List<String> = listOf(GSF, GMS, VENDING) - /** The GrapheneOS release-server download URL for [pkg]'s signed APK. */- fun apkUrlFor(pkg: String): String = "$RELEASE_SERVER/packages/$pkg.apk"- /** * Stand-in listings for the three packages. *- * The home section shows these immediately. They carry [AppSource.GRAPHENEOS] and the- * GrapheneOS release-server [UnifiedApp.apkUrl], so tapping install routes down the- * signed-APK download + [android.content.pm.PackageInstaller] path against- * apps.grapheneos.org — never the Play path. A catalogue sync that has cached richer- * rows (icon, size, signer, hash) replaces these in the ViewModel.+ * The home section shows these immediately, before the network is reached. They carry no+ * download: everything needed to install — version, file list, signer digests, per-APK+ * hashes — comes from the signed index, and a row built without it would be a download+ * nothing could be checked against. Until the sync lands, tapping install reports that+ * the source published nothing, which is exactly what has happened. */ fun placeholders(): List<UnifiedApp> = PACKAGES.map { pkg -> UnifiedApp(@@ -68,8 +60,7 @@ object SandboxedGooglePlay { source = AppSource.GRAPHENEOS, name = DISPLAY_NAMES[pkg] ?: pkg, author = "Google LLC",- apkUrl = apkUrlFor(pkg),- repoUrl = RELEASE_SERVER,+ repoUrl = GrapheneOSRepo.BASE_URL, ) } }
appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.ktindex fa9f399b4a..96625c902d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -26,6 +26,8 @@ import com.vayunmathur.appstore.MainActivity import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.installer.InstallCoordinator import com.vayunmathur.appstore.data.accrescent.AccrescentRepository+import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepository+import com.vayunmathur.appstore.data.grapheneos.toUnifiedApp import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.library.network.NetworkClient@@ -64,6 +66,7 @@ class UpdateCheckWorker( val installedRepo = InstalledAppsRepository(context) val play = PlayRepository(context) val accrescent = AccrescentRepository(context, db)+ val grapheneOS = GrapheneOSRepository(context) catalog.sync() installedRepo.refresh()@@ -74,7 +77,8 @@ class UpdateCheckWorker( // Only Play can answer for packages the offline catalogues have never heard of — except // the Sandboxed Google Play components, which Play also hosts but must never update- // here: only the builds GrapheneOS re-hosts are the ones this device can use.+ // here: only the builds GrapheneOS re-hosts are the ones this device can use. Their+ // updates come from GrapheneOS's own signed index instead, below. val index = catalog.packageIndex.value val unknown = installed .filter {@@ -106,9 +110,23 @@ class UpdateCheckWorker( details.copy(versionCode = update.versionCode, versionName = update.versionName) } + // GrapheneOS: refresh its signed index and offer a newer build of each Sandboxed+ // Google Play component that is installed. Skipped on stock Android, where these+ // packages cannot work at all for want of the OS's gmscompat layer.+ val fromGrapheneOS = if (RestrictedPackages.isGrapheneOS(context)) {+ grapheneOS.refresh(SandboxedGooglePlay.PACKAGES).getOrNull().orEmpty()+ .mapNotNull { entry ->+ val current = installed.firstOrNull { it.packageName == entry.packageName }+ ?: return@mapNotNull null+ entry.toUnifiedApp().takeIf { it.versionCode > current.versionCode }+ }+ } else {+ emptyList()+ }+ // The surviving row's source decides which download-and-verify path the update takes, // so it has to be the same precedence the rest of the store uses.- val updates = (fromCatalog + fromPlay + fromAccrescent)+ val updates = (fromCatalog + fromPlay + fromAccrescent + fromGrapheneOS) .sortedBy { it.source.priority } .distinctBy { it.packageName } @@ -118,7 +136,7 @@ class UpdateCheckWorker( if (autoInstall && updates.isNotEmpty()) { val eligible = updates.filter { canSilentlyUpdate(it.packageName) } if (eligible.isNotEmpty()) {- autoInstall(eligible, db, play, accrescent)+ autoInstall(eligible, db, play, accrescent, grapheneOS) installedRepo.refresh() } // Only nag about the updates we could not apply on our own.@@ -217,6 +235,7 @@ class UpdateCheckWorker( db: AppDatabase, play: PlayRepository, accrescent: AccrescentRepository,+ grapheneOS: GrapheneOSRepository, ) { runCatching { setForeground(installingForegroundInfo(apps.size)) } val installer = InstallCoordinator(@@ -224,6 +243,7 @@ class UpdateCheckWorker( db = db, play = play, accrescent = accrescent,+ grapheneOS = grapheneOS, ownSigningCertificates = { ApkCertificates.selfSigners(context) }, ) var installed = 0
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.ktindex 0bdd37e6d9..0424773c82 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt@@ -6,6 +6,7 @@ import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.appstore.data.security.Signify import kotlinx.coroutines.flow.first import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable@@ -62,7 +63,7 @@ class AccrescentRepoDataFetcher(private val context: Context) { } // Verify the signature over the exact bytes downloaded, before parsing them.- if (!AccrescentSignify.verify(jsonBytes, sig.body)) {+ if (!Signify.verify(jsonBytes, sig.body, AccrescentRepo.REPODATA_PUBKEY)) { return Result.failure(SecurityException("repodata signature did not verify")) }
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.ktindex 1d684a892f..5a066f21b9 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt@@ -7,8 +7,8 @@ package com.vayunmathur.appstore.data.accrescent * anywhere in the repo was this one signature check. * * Takes already-extracted raw bytes: signify's base64 and framing are parsed by- * [AccrescentSignify], which stays in Kotlin. Returns false for a bad signature- * and for any malformed input, so the caller's fail-closed contract holds+ * [com.vayunmathur.appstore.data.security.Signify], which stays in Kotlin. Returns false for+ * a bad signature and for any malformed input, so the caller's fail-closed contract holds * without this ever throwing. */ internal object SignifyNative {
appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.ktnew file mode 100644index 0000000000..0e94921dc9--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSIndex.kt@@ -0,0 +1,244 @@+package com.vayunmathur.appstore.data.grapheneos++import android.content.Context+import android.os.Build+import android.util.DisplayMetrics+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import org.json.JSONArray+import org.json.JSONObject++/** One downloadable file of a package: the base APK or one of its splits. */+data class GrapheneOSApk(+ val name: String,+ /** Lowercase-hex SHA-256 of the **uncompressed** APK; the server serves it gzipped. */+ val sha256: String,+ /** Uncompressed size, which is what the install session is sized against. */+ val size: Long,+ /** Compressed size, which is what actually crosses the network. */+ val gzSize: Long,+)++/** A package as this device should install it: one chosen variant, one chosen set of splits. */+data class GrapheneOSPackage(+ val packageName: String,+ val label: String,+ val description: String,+ val versionCode: Long,+ val versionName: String,+ /** Lowercase-hex SHA-256 digests of the certificates the APKs must be signed by. */+ val signers: List<String>,+ val iconUrl: String?,+ val apks: List<GrapheneOSApk>,+) {+ val totalSize: Long get() = apks.sumOf { it.size }+}++/**+ * The listing row for this package.+ *+ * No `apkUrl`: the download is a set of splits at index-derived URLs, not one file, so+ * `InstallCoordinator` reads the entry back out of the repository rather than being handed a+ * URL. `expectedSigners` and `apkSha256` are set for the detail page's benefit; the install+ * itself checks against every file's hash, not just the base APK's.+ */+fun GrapheneOSPackage.toUnifiedApp(): UnifiedApp = UnifiedApp(+ packageName = packageName,+ source = AppSource.GRAPHENEOS,+ name = label,+ description = description,+ summary = description.lineSequence().firstOrNull().orEmpty(),+ iconUrl = iconUrl,+ author = "Google LLC",+ versionName = versionName,+ versionCode = versionCode,+ sizeBytes = totalSize,+ containsSplit = apks.size > 1,+ repoUrl = GrapheneOSRepo.BASE_URL,+ expectedSigners = signers,+ apkSha256 = apks.firstOrNull { it.name == BASE_APK }?.sha256,+)++private const val BASE_APK = "base.apk"++/**+ * Reader for GrapheneOS's repository index.+ *+ * The index lists every published version of every package, for every SDK level, ABI, screen+ * density and language. Picking from it is the client's job, and getting it wrong means+ * either an install the device rejects or a download of hundreds of megabytes of splits it+ * will never use — so the selection rules here deliberately mirror GrapheneOS's own client+ * (`core/Repo.kt`): newest stable variant this SDK and ABI can run, then the base APK plus+ * only the ABI, density and language splits this device needs.+ *+ * Nothing here decides trust. The caller verifies the signature over the whole document+ * before parsing it, which is what makes the hashes and signer digests below worth reading.+ */+object GrapheneOSIndex {++ private const val STABLE = "stable"+ private const val CONFIG_SEPARATOR = "config."+ private const val APK_SUFFIX = ".apk"++ private val ABI_QUALIFIERS = mapOf(+ "armeabi-v7a" to "armeabi_v7a",+ "arm64-v8a" to "arm64_v8a",+ "x86" to "x86",+ "x86_64" to "x86_64",+ )++ private val DENSITY_QUALIFIERS = mapOf(+ "ldpi" to DisplayMetrics.DENSITY_LOW,+ "mdpi" to DisplayMetrics.DENSITY_MEDIUM,+ "tvdpi" to DisplayMetrics.DENSITY_TV,+ "hdpi" to DisplayMetrics.DENSITY_HIGH,+ "xhdpi" to DisplayMetrics.DENSITY_XHIGH,+ "xxhdpi" to DisplayMetrics.DENSITY_XXHIGH,+ "xxxhdpi" to DisplayMetrics.DENSITY_XXXHIGH,+ )++ /** Index timestamp, for the anti-rollback check. */+ fun timestamp(index: JSONObject): Long = index.optLong("time", 0L)++ /**+ * The subset of [wanted] this device can install, in [wanted]'s order.+ *+ * A package the index does not list, or lists with no variant this device can run, is+ * simply absent from the result rather than an error: the caller shows what it can offer.+ */+ fun packagesFor(+ context: Context,+ index: JSONObject,+ wanted: List<String>,+ ): List<GrapheneOSPackage> {+ val packages = index.optJSONObject("packages") ?: return emptyList()+ return wanted.mapNotNull { name ->+ packages.optJSONObject(name)?.let { parsePackage(context, name, it) }+ }+ }++ private fun parsePackage(+ context: Context,+ packageName: String,+ json: JSONObject,+ ): GrapheneOSPackage? {+ val variants = json.optJSONObject("variants") ?: return null+ val (versionCode, variant) = newestInstallableVariant(variants) ?: return null++ val apks = selectApks(context, variant)+ if (apks.isNullOrEmpty()) return null++ val signers = json.optJSONArray("signatures").toStringList().map { it.lowercase() }+ if (signers.isEmpty()) return null++ return GrapheneOSPackage(+ packageName = packageName,+ label = variant.optString("label", packageName),+ description = variant.opt("description") as? String+ ?: json.opt("description") as? String+ ?: "",+ versionCode = versionCode,+ versionName = variant.opt("versionName") as? String ?: versionCode.toString(),+ signers = signers,+ iconUrl = (json.opt("iconType") as? String)+ ?.let { GrapheneOSRepo.iconUrl(packageName, it) },+ apks = apks,+ )+ }++ /**+ * The newest stable variant this device can run, with its version code.+ *+ * Variants are keyed by version code and differ by SDK range and ABI, so several are+ * usually publishable at once and only some are installable here. An unrunnable variant+ * has to be skipped rather than clamped: installing a build outside its declared SDK+ * range is exactly what the range exists to prevent.+ */+ private fun newestInstallableVariant(variants: JSONObject): Pair<Long, JSONObject>? {+ var best: Pair<Long, JSONObject>? = null+ for (key in variants.keys()) {+ val versionCode = key.toLongOrNull() ?: continue+ val variant = variants.optJSONObject(key) ?: continue+ if (variant.optString("channel", STABLE) != STABLE) continue+ if (Build.VERSION.SDK_INT < variant.optInt("minSdk", 0)) continue+ if (Build.VERSION.SDK_INT > variant.optInt("maxSdk", Int.MAX_VALUE)) continue++ val abis = variant.optJSONArray("abis")?.toStringList()+ if (abis != null && DEVICE_ABI !in abis) continue++ if (best == null || versionCode > best.first) best = versionCode to variant+ }+ return best+ }++ /**+ * The files to download: the base APK plus the splits this device needs.+ *+ * Null when the four parallel arrays disagree on length, which would otherwise pair a+ * file name with another file's hash — a silent mis-verification rather than a failure.+ */+ private fun selectApks(context: Context, variant: JSONObject): List<GrapheneOSApk>? {+ val names = variant.optJSONArray("apks") ?: return null+ val hashes = variant.optJSONArray("apkHashes") ?: return null+ val sizes = variant.optJSONArray("apkSizes") ?: return null+ val gzSizes = variant.optJSONArray("apkGzSizes") ?: return null+ val count = names.length()+ if (hashes.length() != count || sizes.length() != count || gzSizes.length() != count) {+ return null+ }++ val languages = deviceLanguages(context)+ val kept = mutableListOf<GrapheneOSApk>()+ val byDensity = mutableMapOf<Int, MutableList<GrapheneOSApk>>()++ for (i in 0 until count) {+ val apk = GrapheneOSApk(+ name = names.optString(i),+ sha256 = hashes.optString(i).lowercase(),+ size = sizes.optLong(i),+ gzSize = gzSizes.optLong(i),+ )+ val qualifier = configQualifier(apk.name)+ val density = qualifier?.let { DENSITY_QUALIFIERS[it] }+ when {+ qualifier == null -> kept += apk+ density != null -> byDensity.getOrPut(density) { mutableListOf() }.add(apk)+ qualifier in ABI_QUALIFIERS.values ->+ if (qualifier == DEVICE_ABI_QUALIFIER) kept += apk+ else -> if (qualifier in languages) kept += apk+ }+ }++ // One density split, not all of them: the closest at or above this screen, falling+ // back to the largest published when the screen is denser than anything on offer.+ if (byDensity.isNotEmpty()) {+ val densities = byDensity.keys.sorted()+ val target = context.resources.displayMetrics.densityDpi+ val chosen = densities.firstOrNull { it >= target } ?: densities.last()+ kept += byDensity.getValue(chosen)+ }+ return kept+ }++ /** The part after the last `config.`, or null for a file that is not a config split. */+ private fun configQualifier(name: String): String? {+ val index = name.lastIndexOf(CONFIG_SEPARATOR)+ if (index < 0 || !name.endsWith(APK_SUFFIX)) return null+ return name.substring(index + CONFIG_SEPARATOR.length, name.length - APK_SUFFIX.length)+ }++ private fun deviceLanguages(context: Context): Set<String> {+ val locales = context.resources.configuration.locales+ return (0 until locales.size()).mapTo(mutableSetOf()) { locales.get(it).language }+ }++ private fun JSONArray?.toStringList(): List<String> {+ if (this == null) return emptyList()+ return (0 until length()).mapNotNull { optString(it).takeIf { s -> s.isNotEmpty() } }+ }++ /** Secondary ABIs are deliberately not considered; they run worse than the primary one. */+ private val DEVICE_ABI: String = Build.SUPPORTED_ABIS.firstOrNull().orEmpty()++ private val DEVICE_ABI_QUALIFIER: String? = ABI_QUALIFIERS[DEVICE_ABI]+}
appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepo.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepo.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepo.ktnew file mode 100644index 0000000000..ab822ee1b5--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepo.kt@@ -0,0 +1,39 @@+package com.vayunmathur.appstore.data.grapheneos++/**+ * Fixed trust anchors for the GrapheneOS Apps source, mirroring GrapheneOS's own client+ * (`Apps/app/build.gradle.kts` and `core/RepoRetriever.kt`).+ *+ * These are the only values this store takes on faith for GrapheneOS: the release-server+ * host and — the actual root of trust — the signify ed25519 public key the repository index+ * must verify against. Everything the index then states (versions, file names, per-APK+ * SHA-256, signing-certificate digests) is trusted only because the signature covered it.+ */+object GrapheneOSRepo {++ const val BASE_URL = "https://apps.grapheneos.org"++ /** signify-format ed25519 public key the index signature is verified against. */+ const val METADATA_PUBKEY = "RWQtZwEu1br1lMh911L3yPOs97cQb9LOks/ALBbqGl21ul695ocWR/ir"++ /** Index schema version. Bumping it is a breaking change GrapheneOS publishes separately. */+ private const val METADATA_VERSION = 1++ /** Signing-key generation. Rotating the key above means bumping this with it. */+ private const val KEY_VERSION = 0++ val METADATA_URL = "$BASE_URL/metadata.$METADATA_VERSION.$KEY_VERSION.sjson"++ /**+ * Anti-rollback floor: the store refuses any index older than this, even on first run+ * when nothing is stored yet. Matches GrapheneOS's own `MIN_TIMESTAMP`.+ */+ const val MIN_TIMESTAMP = 1_770_000_000L++ /** Where a package's APKs live. GrapheneOS serves them gzipped. */+ fun apkUrl(manifestPackageName: String, versionCode: Long, apkName: String): String =+ "$BASE_URL/packages/$manifestPackageName/$versionCode/$apkName.gz"++ fun iconUrl(manifestPackageName: String, iconType: String): String =+ "$BASE_URL/packages/$manifestPackageName/icon.$iconType"+}
appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.ktnew file mode 100644index 0000000000..4b24cd532c--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/grapheneos/GrapheneOSRepository.kt@@ -0,0 +1,133 @@+package com.vayunmathur.appstore.data.grapheneos++import android.content.Context+import android.util.Log+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import com.vayunmathur.appstore.data.security.Signify+import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import org.json.JSONObject+import java.security.GeneralSecurityException++private val Context.grapheneOSDataStore by preferencesDataStore(name = "grapheneos_repo")+private val INDEX_TIMESTAMP_KEY = longPreferencesKey("index_timestamp")++/**+ * The GrapheneOS Apps source: a signed index, and the packages this device can install from it.+ *+ * Trust comes entirely from one ed25519 signature over the index bytes ([Signify]) verified+ * against the pinned [GrapheneOSRepo.METADATA_PUBKEY], plus a monotonic timestamp that can+ * never go backwards. Every failure path leaves [packages] empty — fail closed — so a+ * tampered, unsigned or rolled-back index yields nothing installable rather than an install+ * with no signer or hash to check.+ *+ * That last part is the point of this class. The store used to build a download URL for the+ * Sandboxed Google Play packages by hand and carry no signer or hash at all, which the+ * verifier could only treat as "the source published nothing to check against" — while the+ * UI claimed the same guarantees as F-Droid. Those guarantees are now real, and an index+ * that fails to verify produces no download rather than an unchecked one.+ */+class GrapheneOSRepository(private val context: Context) {++ private val mutex = Mutex()++ @Volatile+ private var cached: List<GrapheneOSPackage> = emptyList()++ /** The last successfully verified listing, empty until [refresh] succeeds once. */+ val packages: List<GrapheneOSPackage> get() = cached++ fun packageFor(packageName: String): GrapheneOSPackage? =+ cached.firstOrNull { it.packageName == packageName }++ /**+ * Fetch, verify and parse the index for [wanted].+ *+ * A failure keeps whatever was verified last rather than emptying the list: the previous+ * answer was signed and is still true, and dropping it would take the section off the+ * screen every time the network is down.+ */+ suspend fun refresh(wanted: List<String>): Result<List<GrapheneOSPackage>> = mutex.withLock {+ try {+ val (status, _, bytes) =+ NetworkClient.performRequestBytesFull(GrapheneOSRepo.METADATA_URL)+ if (status !in 200..299) {+ return@withLock Result.failure(+ IllegalStateException("index fetch failed: HTTP $status")+ )+ }++ val (json, signature) = split(bytes)+ ?: return@withLock Result.failure(+ IllegalStateException("index is too short to carry a signature")+ )++ // Verify over the exact bytes downloaded, before parsing them.+ if (!Signify.verify(json, signature, GrapheneOSRepo.METADATA_PUBKEY)) {+ return@withLock Result.failure(+ SecurityException("index signature did not verify")+ )+ }++ val index = JSONObject(json.toString(Charsets.UTF_8))++ // Anti-rollback: never accept an index older than the newest one already seen,+ // and never older than the pinned floor even on first run.+ val floor = maxOf(readStoredTimestamp(), GrapheneOSRepo.MIN_TIMESTAMP)+ val timestamp = GrapheneOSIndex.timestamp(index)+ if (timestamp < floor) {+ return@withLock Result.failure(+ GeneralSecurityException("index timestamp $timestamp is older than $floor")+ )+ }+ persistTimestamp(timestamp)++ val parsed = GrapheneOSIndex.packagesFor(context, index, wanted)+ cached = parsed+ Result.success(parsed)+ } catch (e: Exception) {+ Log.w(TAG, "index fetch/verify failed", e)+ Result.failure(e)+ }+ }++ /**+ * Split the signed document into the bytes that were signed and the signature over them.+ *+ * The format is the JSON, a newline, 100 base64 characters and a final newline — see+ * GrapheneOS's `core/RepoRetriever.kt`. The signature is a fixed-width trailer rather+ * than a separate file, so it is sliced off by length.+ */+ private fun split(bytes: ByteArray): Pair<ByteArray, String>? {+ if (bytes.size <= TRAILER_BYTES) return null+ val json = bytes.copyOfRange(0, bytes.size - TRAILER_BYTES)+ val signature = bytes+ .copyOfRange(bytes.size - TRAILER_BYTES + 1, bytes.size - 1)+ .toString(Charsets.UTF_8)+ return json to signature+ }++ private suspend fun readStoredTimestamp(): Long = try {+ context.grapheneOSDataStore.data.first()[INDEX_TIMESTAMP_KEY] ?: 0L+ } catch (_: Exception) {+ 0L+ }++ private suspend fun persistTimestamp(timestamp: Long) {+ try {+ context.grapheneOSDataStore.edit { it[INDEX_TIMESTAMP_KEY] = timestamp }+ } catch (_: Exception) {+ }+ }++ private companion object {+ const val TAG = "GrapheneOSRepository"++ /** Newline + 100 base64 signature characters + newline. */+ const val TRAILER_BYTES = 102+ }+}
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex c6450dfe83..86de74dd9c 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -8,6 +8,8 @@ import com.vayunmathur.appstore.data.PinnedStampEntity import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.accrescent.AccrescentRepository import com.vayunmathur.appstore.data.accrescent.IncompatibleDeviceException+import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepo+import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepository import com.vayunmathur.appstore.data.play.CertUtil import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.security.InstallRequirement@@ -20,8 +22,11 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.withContext import java.io.File+import java.io.FilterInputStream+import java.io.IOException import java.net.HttpURLConnection import java.net.URL+import java.util.zip.GZIPInputStream import javax.net.ssl.HttpsURLConnection /**@@ -54,6 +59,7 @@ class InstallCoordinator( private val db: AppDatabase, private val play: PlayRepository, private val accrescent: AccrescentRepository,+ private val grapheneOS: GrapheneOSRepository, private val ownSigningCertificates: () -> Set<String>, ) { private val sessionInstaller = SessionInstaller(context)@@ -85,6 +91,7 @@ class InstallCoordinator( when (app.source) { AppSource.PLAYSTORE -> installFromPlay(app) AppSource.ACCRESCENT -> installFromAccrescent(app)+ AppSource.GRAPHENEOS -> installFromGrapheneOS(app) else -> installFromUrl(app) }.also { outcome -> if (outcome.started) {@@ -109,7 +116,7 @@ class InstallCoordinator( if (_stages.value[packageName] is InstallStage.Failed) clear(packageName) } - // --- Direct APK: Modern Apps, F-Droid and GrapheneOS ---------------------------+ // --- Direct APK: Modern Apps and F-Droid --------------------------------------- private suspend fun installFromUrl(app: UnifiedApp): SessionInstaller.Outcome = withContext(Dispatchers.IO) {@@ -128,15 +135,6 @@ class InstallCoordinator( ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(), signerOrigin = "this store", )- // GrapheneOS re-hosts Google's official signed APKs; the signer and hash- // come from its signed release metadata when a sync has cached them.- AppSource.GRAPHENEOS -> InstallRequirement(- expectedPackage = app.packageName,- requiredSigners = app.expectedSigners.toSet(),- expectedSha256 = app.apkSha256- ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),- signerOrigin = "GrapheneOS's signed app list",- ) else -> InstallRequirement( expectedPackage = app.packageName, requiredSigners = app.expectedSigners.toSet(),@@ -155,7 +153,13 @@ class InstallCoordinator( sessionInstaller.installSplits(app.packageName, listOf(file), requirement, file.length()) } - private fun download(url: String, target: File, expectedSize: Long, onProgress: (Float) -> Unit) {+ private fun download(+ url: String,+ target: File,+ expectedSize: Long,+ gzipped: Boolean = false,+ onProgress: (Float) -> Unit,+ ) { val rawConnection = URL(url).openConnection() val sslSocketFactory = NetworkClient.defaultSslSocketFactory if (sslSocketFactory != null && rawConnection is HttpsURLConnection) {@@ -167,17 +171,33 @@ class InstallCoordinator( instanceFollowRedirects = true } try {+ // Without this a 404 reaches the caller as a FileNotFoundException whose whole+ // message is the URL, which the UI then shows the user as the reason the install+ // failed. Read the status first and say what the server actually said.+ val code = conn.responseCode+ if (code !in 200..299) {+ throw IOException("the server returned HTTP $code for ${target.name}")+ }++ // Progress counts bytes off the network, so it stays honest for a gzipped body+ // where the file on disk ends up several times larger than the transfer. val total = conn.contentLengthLong.takeIf { it > 0 } ?: expectedSize- conn.inputStream.use { input ->- target.outputStream().use { out ->- val buf = ByteArray(64 * 1024)- var downloaded = 0L- var read: Int- while (input.read(buf).also { read = it } != -1) {- out.write(buf, 0, read)- downloaded += read- if (total > 0) onProgress((downloaded.toFloat() / total).coerceIn(0f, 1f))+ var downloaded = 0L+ val counting = object : FilterInputStream(conn.inputStream) {+ override fun read(b: ByteArray, off: Int, len: Int): Int =+ super.read(b, off, len).also { read ->+ if (read > 0) {+ downloaded += read+ if (total > 0) {+ onProgress((downloaded.toFloat() / total).coerceIn(0f, 1f))+ }+ } }+ }+ val input = if (gzipped) GZIPInputStream(counting) else counting+ input.use { source ->+ target.outputStream().use { out ->+ source.copyTo(out, 64 * 1024) } } } finally {@@ -185,6 +205,68 @@ class InstallCoordinator( } } + // --- GrapheneOS ------------------------------------------------------------------++ /**+ * Install one of GrapheneOS's packages from its signed index.+ *+ * Everything the install is checked against — the file list, each file's SHA-256, and the+ * certificates the APKs must be signed by — comes from the index this store verified the+ * signature of, so a package the index does not vouch for is refused before anything is+ * downloaded rather than installed unchecked.+ *+ * The files are served gzipped and the published hashes are of the uncompressed APKs, so+ * they are decompressed on the way to disk and hashed there, under their index file names+ * so the hash map lines up.+ */+ private suspend fun installFromGrapheneOS(app: UnifiedApp): SessionInstaller.Outcome =+ withContext(Dispatchers.IO) {+ val entry = grapheneOS.packageFor(app.packageName)+ ?: return@withContext SessionInstaller.Outcome(+ false,+ VerificationResult.Rejected(+ "GrapheneOS's signed app list does not vouch for this app"+ ),+ )++ val dir = File(context.cacheDir, "grapheneos/${app.packageName}").apply {+ deleteRecursively()+ mkdirs()+ }++ val totalCompressed = entry.apks.sumOf { it.gzSize }.takeIf { it > 0 } ?: -1L+ var doneCompressed = 0L+ val files = entry.apks.map { apk ->+ val file = File(dir, apk.name)+ val start = doneCompressed+ download(+ url = GrapheneOSRepo.apkUrl(app.packageName, entry.versionCode, apk.name),+ target = file,+ expectedSize = apk.gzSize,+ gzipped = true,+ ) { fileFraction ->+ if (totalCompressed > 0) {+ val overall = (start + fileFraction * apk.gzSize) / totalCompressed+ stage(app.packageName, InstallStage.Downloading(overall.coerceIn(0f, 1f)))+ }+ }+ doneCompressed += apk.gzSize+ file+ }++ val requirement = InstallRequirement(+ expectedPackage = app.packageName,+ requiredSigners = entry.signers.toSet(),+ expectedSha256 = entry.apks.associate { it.name to it.sha256 },+ signerOrigin = "GrapheneOS's signed app list",+ )++ stage(app.packageName, InstallStage.Verifying)+ sessionInstaller.installSplits(+ app.packageName, files, requirement, files.sumOf { it.length() }+ )+ }+ // --- Accrescent ---------------------------------------------------------------- /**
appstore/src/main/java/com/vayunmathur/appstore/data/security/Signify.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/Signify.ktsimilarity index 55%rename from appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.ktrename to appstore/src/main/java/com/vayunmathur/appstore/data/security/Signify.ktindex 2d97e9b719..17fb57e1f4 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/Signify.kt@@ -1,26 +1,29 @@-package com.vayunmathur.appstore.data.accrescent+package com.vayunmathur.appstore.data.security import android.util.Base64+import com.vayunmathur.appstore.data.accrescent.SignifyNative /**- * ed25519 verification of an OpenBSD-signify signature, replicating Accrescent's- * `util/RepoDataVerifier.verifySignature`.+ * ed25519 verification of an OpenBSD-signify signature.+ *+ * Two of this store's sources sign their index with signify — Accrescent's `repodata.N.json`+ * and GrapheneOS's `metadata.N.N.sjson` — so the framing is parsed once here rather than+ * twice. * * signify wire format (what this understands):- * - The **public key** ([AccrescentRepo.REPODATA_PUBKEY]) is a raw base64 blob of- * `2-byte algo id || 8-byte key id || 32-byte ed25519 public key`; the key is bytes- * `[10, 42)`.- * - A **`.sig` file** is two lines: an `untrusted comment:` line and a base64 blob of- * `2-byte algo id || 8-byte key id || 64-byte ed25519 signature`; the signature is bytes- * `[10, 74)`.- * - The signature is over the **raw bytes of the signed file** (here, `repodata.N.json`).+ * - A **public key** is a raw base64 blob of `2-byte algo id || 8-byte key id || 32-byte+ * ed25519 public key`; the key is bytes `[10, 42)`.+ * - A **signature** is a base64 blob of `2-byte algo id || 8-byte key id || 64-byte ed25519+ * signature`; the signature is bytes `[10, 74)`. A `.sig` *file* precedes it with an+ * `untrusted comment:` line; a signature embedded in a signed document does not.+ * - The signature is over the **raw bytes of the signed file**. *- * This is the whole trust anchor for the Accrescent source, so it fails closed: any parsing- * or verification problem returns `false` rather than throwing or assuming success.+ * This is the whole trust anchor for both sources, so it fails closed: any parsing or+ * verification problem returns `false` rather than throwing or assuming success. * * The framing above is parsed here; the raw ed25519 check itself is [SignifyNative]. */-object AccrescentSignify {+object Signify { private const val PUBKEY_HEADER = 10 private const val PUBKEY_END = 42@@ -28,23 +31,23 @@ object AccrescentSignify { private const val SIG_END = 74 /**- * @param message the exact bytes that were signed (the repodata JSON as downloaded).- * @param sigFileContent the full text of the `.sig` file.+ * @param message the exact bytes that were signed.+ * @param signature the base64 signature blob, optionally preceded by a `.sig` comment line. * @param base64PublicKey the signify public key, as a raw base64 string (no comment line).- * @return true only if [sigFileContent] is a valid ed25519 signature over [message] by+ * @return true only if [signature] is a valid ed25519 signature over [message] by * [base64PublicKey]. */ fun verify( message: ByteArray,- sigFileContent: String,- base64PublicKey: String = AccrescentRepo.REPODATA_PUBKEY,+ signature: String,+ base64PublicKey: String, ): Boolean { return try { val pubKeyBytes = decodeRange(base64PublicKey, PUBKEY_HEADER, PUBKEY_END) ?: return false // A .sig file is a comment line followed by the base64 blob. Take the last // non-blank, non-comment line so a stray trailing newline can't select "".- val sigBase64 = sigFileContent+ val sigBase64 = signature .lineSequence() .map { it.trim() } .lastOrNull { it.isNotEmpty() && !it.startsWith("untrusted comment:") }
appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.ktindex ad8a3f42c3..7db2388522 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt@@ -175,9 +175,9 @@ enum class TrustProfile { // The whole F-Droid catalogue is listed; whether a given version was reproduced // is shown per-app as a badge (see UnifiedApp.reproducible). AppSource.FDROID -> FDROID- // GrapheneOS serves a hard-pinned, JAR-signed index with a publisher key and a- // per-APK hash this app checks the download against — the same trust story as- // F-Droid, so it shares that profile.+ // GrapheneOS serves a hard-pinned, signify-signed index with a publisher key and a+ // per-APK hash this app checks every downloaded file against — the same trust+ // story as F-Droid, so it shares that profile. AppSource.GRAPHENEOS -> FDROID AppSource.PLAYSTORE -> PLAY // Accrescent apps are signed by their developers, not by Accrescent; trust is the
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex 12defcbdad..3ec5106f0b 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -15,11 +15,14 @@ import com.vayunmathur.appstore.data.CatalogRepository import com.vayunmathur.appstore.data.InstalledAppsRepository import com.vayunmathur.appstore.data.InstalledInfo import com.vayunmathur.appstore.data.PlayStoreLinks+import com.vayunmathur.appstore.data.RestrictedPackages import com.vayunmathur.appstore.data.SandboxedGooglePlay import com.vayunmathur.appstore.data.SettingsRepository import com.vayunmathur.appstore.data.SyncStep import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.accrescent.AccrescentRepository+import com.vayunmathur.appstore.data.grapheneos.GrapheneOSRepository+import com.vayunmathur.appstore.data.grapheneos.toUnifiedApp import com.vayunmathur.appstore.data.installer.InstallCoordinator import com.vayunmathur.appstore.data.installer.InstallStage import com.vayunmathur.appstore.data.play.PlayAuthState@@ -54,9 +57,11 @@ class AppStoreViewModel( private val catalog = CatalogRepository(context, db, viewModelScope) private val play = PlayRepository(context) private val accrescent = AccrescentRepository(context, db)+ private val grapheneOS = GrapheneOSRepository(context) private val installedRepo = InstalledAppsRepository(context) private val settings = SettingsRepository(context, viewModelScope)- private val installer = InstallCoordinator(context, db, play, accrescent) { ownSigningCertificates }+ private val installer =+ InstallCoordinator(context, db, play, accrescent, grapheneOS) { ownSigningCertificates } /** Off-by-default: the periodic check may also download and install updates unattended. */ val autoInstallUpdates: StateFlow<Boolean> = settings.autoInstallUpdates@@ -91,12 +96,18 @@ class AppStoreViewModel( /** * The Sandboxed Google Play bundle rows. Seeded with stand-ins so the section is on- * screen immediately; [loadHome] swaps in richer catalogue rows when a sync has cached- * them. These install from GrapheneOS's release server, never Play.+ * screen immediately; [loadHome] replaces them with rows built from GrapheneOS's signed+ * index. These install from GrapheneOS's release server, never Play. * Kept in [SandboxedGooglePlay.PACKAGES] order so the ordered install reads straight off it.+ *+ * Empty on stock Android. These packages only work alongside the gmscompat layer, which+ * is part of the OS, so on a device without it the section would offer three installs+ * that cannot function. */- private val _sandboxedGooglePlay =- MutableStateFlow(SandboxedGooglePlay.placeholders())+ private val _sandboxedGooglePlay = MutableStateFlow(+ if (RestrictedPackages.isGrapheneOS(context)) SandboxedGooglePlay.placeholders()+ else emptyList()+ ) private val _categories = MutableStateFlow<List<String>>(emptyList()) private val _selectedCategory = MutableStateFlow<String?>(null) private val _categoryApps = MutableStateFlow<List<UnifiedApp>>(emptyList())@@ -113,6 +124,7 @@ class AppStoreViewModel( private val _catalogUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList()) private val _playUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList()) private val _accrescentUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())+ private val _grapheneOSUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList()) private val _libraryFilter = MutableStateFlow(SourceFilter.ALL) @@ -144,10 +156,11 @@ class AppStoreViewModel( _catalogUpdates, _playUpdates, _accrescentUpdates,+ _grapheneOSUpdates, installedRepo.apps,- ) { catalogUpdates, playUpdates, accrescentUpdates, installed ->+ ) { catalogUpdates, playUpdates, accrescentUpdates, grapheneOSUpdates, installed -> val installedVersions = installed.associate { it.packageName to it.versionCode }- (catalogUpdates + playUpdates + accrescentUpdates)+ (catalogUpdates + playUpdates + accrescentUpdates + grapheneOSUpdates) // The surviving row's source decides which download-and-verify path the update // takes, so it has to be the same precedence search and the library use. .sortedBy { it.source.priority }@@ -405,12 +418,16 @@ class AppStoreViewModel( _recentlyUpdated.value = catalog.recentlyUpdated(RECENT_LIMIT) // The Sandboxed Google Play components come from GrapheneOS's release server, not- // Play. Enrich the stand-ins with richer catalogue rows (icon, size, signer, hash)- // when a sync has cached them; keep the stand-ins, and the section, when it hasn't.- val cached = catalog.byPackages(SandboxedGooglePlay.PACKAGES).associateBy { it.packageName }- if (cached.isNotEmpty()) {- _sandboxedGooglePlay.value =- _sandboxedGooglePlay.value.map { cached[it.packageName] ?: it }+ // Play. Refreshing its signed index is what turns the stand-ins into installable+ // rows: the version, file list, signer digests and per-APK hashes all come from+ // there. A failed refresh leaves the stand-ins, and the section, exactly as they were.+ if (_sandboxedGooglePlay.value.isNotEmpty()) {+ grapheneOS.refresh(SandboxedGooglePlay.PACKAGES).getOrNull()?.let { packages ->+ val byPackage = packages.associateBy { it.packageName }+ _sandboxedGooglePlay.value = _sandboxedGooglePlay.value.map { row ->+ byPackage[row.packageName]?.toUnifiedApp() ?: row+ }+ } } val clusters = play.homeClusters()@@ -621,11 +638,9 @@ class AppStoreViewModel( // Play lists the Sandboxed Google Play components too, so a search hit for one can // arrive carrying AppSource.PLAYSTORE. Describe it from GrapheneOS regardless: that // is the row an install would actually use, and the Play build is the wrong- // artifact for the device even though Play would happily deliver it. Prefer the- // cached row — the stand-in carries no version, size, signer or hash, and on a cold- // start nothing has enriched it yet.+ // artifact for the device even though Play would happily deliver it. sandboxedGooglePlayRow(app.packageName)?.let { sandboxed ->- _selectedApp.value = catalog.byPackage(app.packageName) ?: sandboxed+ _selectedApp.value = sandboxed return@launch } // The catalogue row wins whenever there is one, even if the user tapped a Play@@ -795,8 +810,8 @@ class AppStoreViewModel( // Only ask Play about packages neither offline source lists — for the rest the // catalogue already answered, and Play would just re-answer it over the network. // The Sandboxed Google Play components are held back too: Play hosts newer builds- // of all three, but only GrapheneOS's are the ones this device can use, so no- // update is better than the wrong one until its release metadata is synced.+ // of all three, but only GrapheneOS's are the ones this device can use, so their+ // updates come from its signed index below instead. val index = catalog.packageIndex.value val installed = installedRepo.updatable.value val playCandidates = installed@@ -823,6 +838,14 @@ class AppStoreViewModel( .filter { it.packageName in accrescentIds } .mapNotNull { inst -> accrescentUpdate(inst.packageName, inst.versionCode) } + // GrapheneOS: its signed index is the only place a Sandboxed Google Play update+ // can come from, which is why the three are held back from the Play list above.+ _grapheneOSUpdates.value = grapheneOS.packages.mapNotNull { entry ->+ val current = installed.firstOrNull { it.packageName == entry.packageName }+ ?: return@mapNotNull null+ entry.toUnifiedApp().takeIf { it.versionCode > current.versionCode }+ }+ _lastUpdateCheck.value = System.currentTimeMillis() _statusMessage.value = "" _isCheckingUpdates.value = false
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.ktindex a6fdccaa41..7c8d90270f 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/InitialDownloader.kt@@ -239,8 +239,9 @@ internal suspend fun runDownloadsCore( context: Context, ds: DataStoreUtils, specs: List<DownloadSpec>,+ targetDir: File? = null, ): Boolean = withContext(Dispatchers.IO) {- val dir = context.getExternalFilesDir(null)+ val dir = targetDir ?: context.getExternalFilesDir(null) var allDownloaded = true for (spec in specs) { // Sever any legacy DownloadManager claim on an already-present file before
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.ktindex 51fb30725a..54f0e68702 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelDownloadWorker.kt@@ -11,6 +11,7 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.vayunmathur.library.util.DataStoreUtils+import java.io.File import java.util.concurrent.TimeUnit /**@@ -34,9 +35,10 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) : val specs = readSpecs(inputData) if (specs.isEmpty()) return Result.failure() + val targetDir = inputData.getString(KEY_TARGET_DIR)?.let(::File) val ds = DataStoreUtils.getInstance(applicationContext) return when {- runDownloadsCore(applicationContext, ds, specs) -> Result.success()+ runDownloadsCore(applicationContext, ds, specs, targetDir) -> Result.success() // Keep retrying transient problems (flaky network, mirror hiccup) but eventually stop so // the screen can offer a retry rather than backing off forever. runAttemptCount + 1 >= MAX_RUN_ATTEMPTS -> Result.failure()@@ -49,6 +51,8 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) : private const val KEY_FILE_NAMES = "fileNames" private const val KEY_DESCRIPTIONS = "descriptions" private const val KEY_HASHES = "hashes"+ private const val KEY_TARGET_DIR = "targetDir"+ private const val KEY_UNMETERED = "unmetered" /** Absent SHA-256, encoded as an empty string because [Data] holds no nulls. */ private const val NO_HASH = ""@@ -73,23 +77,58 @@ class ModelDownloadWorker(context: Context, params: WorkerParameters) : internal fun retry(context: Context, specs: List<DownloadSpec>) = enqueue(context, specs, ExistingWorkPolicy.REPLACE) + /**+ * Enqueues a download that writes outside the app's external files dir, and optionally+ * only over an unmetered network.+ *+ * Used by networklocation, whose multi-gigabyte offline databases go to device-protected+ * storage so the always-on provider can read them before first unlock, and which must not+ * pull gigabytes over cellular.+ */+ fun enqueueTo(+ context: Context,+ models: List<ModelDownloadItem>,+ targetDir: File,+ requireUnmetered: Boolean = false,+ replaceExisting: Boolean = false,+ ) = enqueue(+ context = context,+ specs = models.map {+ DownloadSpec(+ fileName = it.fileName,+ description = it.description,+ url = it.url,+ sha256 = it.sha256,+ )+ },+ policy = if (replaceExisting) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.KEEP,+ targetDir = targetDir,+ requireUnmetered = requireUnmetered,+ )+ private fun enqueue( context: Context, specs: List<DownloadSpec>, policy: ExistingWorkPolicy,+ targetDir: File? = null,+ requireUnmetered: Boolean = false, ) { val data = Data.Builder() .putStringArray(KEY_URLS, specs.map { it.url }.toTypedArray()) .putStringArray(KEY_FILE_NAMES, specs.map { it.fileName }.toTypedArray()) .putStringArray(KEY_DESCRIPTIONS, specs.map { it.description }.toTypedArray()) .putStringArray(KEY_HASHES, specs.map { it.sha256 ?: NO_HASH }.toTypedArray())+ .apply { targetDir?.let { putString(KEY_TARGET_DIR, it.absolutePath) } }+ .putBoolean(KEY_UNMETERED, requireUnmetered) .build() val request = OneTimeWorkRequestBuilder<ModelDownloadWorker>() .setInputData(data) .setConstraints( Constraints.Builder()- .setRequiredNetworkType(NetworkType.CONNECTED)+ .setRequiredNetworkType(+ if (requireUnmetered) NetworkType.UNMETERED else NetworkType.CONNECTED+ ) .build() ) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_SECONDS, TimeUnit.SECONDS)
library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.ktindex ffec8b8f03..a9c1349283 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/LayerOptions.kt@@ -28,12 +28,29 @@ data class LayerOptions( /** * Points of interest: an icon plus a wrapped label per feature, at z17 and deeper. *- * Matches the reference basemap's `pois` layer — the same 36 kinds, the same sprite- * sheet, the same six-way colour split by kind, and the same left/right anchor flip at- * the screen edge. Density is governed by the archive, which drops each kind below its+ * Matches the reference basemap's `pois` layer — the same sprite sheet, the same six-way+ * colour split by kind, and the same left/right anchor flip at the screen edge. Forty+ * kinds: the reference's thirty-six plus `fuel`, `hotel`, `bank` and `atm`, which it+ * draws none of. Density is governed by the archive, which drops each kind below its * own minimum zoom, so this stays empty at world zoom whatever the flag says. */ val poi: Boolean = false,+ /**+ * Narrow [poi] to these archive kind names (`cafe`, `fuel`, `hotel`, …). Empty draws+ * every kind the style has, which is the default.+ *+ * This is what a category-chip row filters with. It is a *sub-layer* filter — the six+ * `poi-*` layers hold forty kinds between them and a chip selects a handful — so it+ * cannot be expressed by turning layers off. Basemap layers are never narrowed by it:+ * selecting "Coffee" hides other POIs, not the roads.+ *+ * A name the archive schema does not know is ignored rather than treated as an error.+ *+ * Costs what [poi] costs: the filter is applied at tessellation time, so changing it+ * re-tessellates the resident set. Order does not matter and duplicates are fine —+ * equality is by content, so a freshly-built set each recomposition is a no-op.+ */+ val poiKinds: Set<String> = emptySet(), /** * Rail transit lines, coloured per route. *
library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.ktindex 0e86f9dc3e..f7acd261c5 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapGestures.kt@@ -25,12 +25,29 @@ import kotlin.math.abs import kotlin.math.sign /**- * A tap on the map: the geographic position under the finger plus the screen- * point (Dp from the viewport top-left) that produced it. The screen point is- * what [MapFeaturePicker]-style hit-testing needs; the geo alone cannot+ * A tap on the map: the geographic position under the finger, the screen+ * point (Dp from the viewport top-left) that produced it, and the POI it+ * landed on if it landed on one. The screen point is what+ * [MapFeaturePicker]-style hit-testing needs; the geo alone cannot * recover it once the camera moves.+ *+ * [poi] rides on the same click rather than arriving through a callback of its own so a+ * host sees one tap as one event. With two callbacks the host would have to guess whether+ * the other had already claimed the tap, and a POI tap would both open the POI and fall+ * through to whatever the host does with empty map. */-data class MapClick(val position: GeoPoint, val screen: DpOffset)+data class MapClick(+ val position: GeoPoint,+ val screen: DpOffset,+ /**+ * The topmost drawn POI under the finger, or null.+ *+ * Only ever set when [LayerOptions.poi] is on, and only for labels the collision pass+ * actually placed last frame — a POI hidden behind another is not reported, because it+ * is not on screen to be tapped.+ */+ val poi: PlacedLabel? = null,+) /** * Viewport measurement and every pan/zoom/tap gesture the map supports. *
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex 11883a2733..06495c742e 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -5,11 +5,11 @@ import android.view.Surface /** * The JNI surface of the Vulkan renderer in `library/map/src/main/rust`. *- * Deliberately five methods and nothing per-feature: Kotlin creates and destroys the- * renderer for a [Surface], resizes it, reports connectivity, and hands it **one- * camera snapshot per frame**. Tile selection, fetching, decode, tessellation and- * drawing all happen on the native side, so the boundary is crossed a handful of times- * a frame rather than thousands.+ * Deliberately narrow and nothing per-feature: Kotlin creates and destroys the renderer+ * for a [Surface], resizes it, reports connectivity and theme, sets the handful of pieces+ * of state the renderer draws from, and hands it **one camera snapshot per frame**. Tile+ * selection, fetching, decode, tessellation and drawing all happen on the native side, so+ * the boundary is crossed a handful of times a frame rather than thousands. * * [handle] values are opaque pointers owned by the native side. Every method tolerates * `0`, which is what [create] returns on failure — so a device without a working Vulkan@@ -93,8 +93,11 @@ internal object MapNative { * * A call that changes nothing does nothing, so this is safe to drive from a * `LaunchedEffect` that may re-run for unrelated reasons.+ *+ * [kinds] is a comma-separated list of archive kind names narrowing POI to those kinds;+ * empty draws them all. A name the schema does not know is ignored. */- external fun setLayers(handle: Long, poi: Boolean, transit: Boolean)+ external fun setLayers(handle: Long, poi: Boolean, transit: Boolean, kinds: String) /** * Tell the renderer whether the device is online. When offline it serves stale cached@@ -102,15 +105,44 @@ internal object MapNative { */ external fun setOnline(handle: Long, online: Boolean) + /**+ * Show the user-location puck at [lon]/[lat], drawn by the renderer inside the same+ * frame as the basemap.+ *+ * Free in the same sense as [setPalette]: the quad is already on the GPU and+ * everything that varies about the puck reaches it as a push constant, so nothing is+ * re-tessellated or re-uploaded. That is why a fix is pushed in out of band rather+ * than being an argument on [render] — a fix arrives at about 1 Hz while [render]+ * runs at 60.+ *+ * [lon] and [lat] are `Float` for the same reason the camera's are (see [render]).+ * [bearing] is degrees clockwise from north and is only read when [hasBearing] is+ * true; without it the dot draws and the bearing cone does not.+ */+ external fun setUserPuck(+ handle: Long,+ lon: Float,+ lat: Float,+ bearing: Float,+ hasBearing: Boolean,+ )++ /** Take the puck away: no fix, or a host that stopped asking for one. */+ external fun clearUserPuck(handle: Long)+ /** * Pick placed labels (task 17): the last frame's placed symbol labels * whose screen boxes intersect the query box, in placement order. * * All four box edges are Dp from the viewport top-left. Returns one * `String` per hit, fields joined by `\u0001`: `layerId \u0001 name \u0001- * kind \u0001 lon \u0001 lat`. A `\u0001`-joined string (not objects)- * keeps the boundary allocation-free on the native side and parse-trivial- * on the Kotlin side. Empty array when nothing was placed or nothing hits.+ * kind \u0001 lon \u0001 lat \u0001 featureId`. A `\u0001`-joined string+ * (not objects) keeps the boundary allocation-free on the native side and+ * parse-trivial on the Kotlin side. Empty array when nothing was placed or+ * nothing hits.+ *+ * `kind` is the feature's own kind, not its layer's first one. `featureId` is the+ * archive's stable id, or `0` for a feature that has none. */ external fun pickLabels( handle: Long,
library/map/src/main/java/com/vayunmathur/library/map/Projection.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt b/library/map/src/main/java/com/vayunmathur/library/map/Projection.ktindex de376c4ac9..0344d9ac7e 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt@@ -14,8 +14,24 @@ import androidx.compose.ui.unit.dp data class PlacedLabel( val layerId: String, val name: String,+ /**+ * The feature's **own** archive kind (`cafe`, `hotel`, `station`, …), not its layer's.+ *+ * A symbol layer filters on several kinds — `poi-food` draws four — so before this was+ * read from the feature it reported the layer's first whitelist entry, and every food POI+ * came back as `restaurant`.+ */ val kind: String, val position: GeoPoint,+ /**+ * The archive's stable id for the feature, or `0` when it has none.+ *+ * Only `places` and `poi` features carry one — they are the only pure points, and the+ * tiler merges everything else. The low two bits say which OSM id space it came from+ * (1 node, 2 way, 3 relation) because those three sequences overlap; the id itself is+ * the remaining bits.+ */+ val featureId: Long = 0L, ) /**
library/map/src/main/java/com/vayunmathur/library/map/UserPuck.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/UserPuck.kt b/library/map/src/main/java/com/vayunmathur/library/map/UserPuck.ktnew file mode 100644index 0000000000..1aefe5f311--- /dev/null+++ b/library/map/src/main/java/com/vayunmathur/library/map/UserPuck.kt@@ -0,0 +1,28 @@+package com.vayunmathur.library.map++/**+ * The user's own location, drawn by the renderer rather than by the host.+ *+ * Pass one to [VectorMap] and the puck appears; pass null and nothing is drawn. The host+ * needs no location code and no location permission of its own — `photos` and+ * `fooddelivery` hold none at all, which is exactly the case this serves: whoever already+ * has a fix hands the point in, and the library draws it.+ *+ * It is drawn **inside the renderer's frame**, from the same camera value as the basemap+ * under it, which is the whole reason it is not a [MapMarker]. Compose overlays are+ * produced by a second, unsynchronised pass over the same camera, so during a pan they+ * land on glass a frame or two behind the tiles and visibly drag (see [MapMarker]'s own+ * note). The puck is the one overlay with no hit-testing, so it could move without the+ * pin-picking machinery moving with it.+ *+ * The tradeoff that comes with that: it is now under *all* Compose content, so a pin the+ * host draws on the user's position will cover it. That is how Google Maps behaves.+ *+ * @param bearing degrees clockwise from north, or null when there is no heading yet.+ * Null draws the dot without its bearing cone, which is a different thing from a+ * heading of zero — passing `0f` for "unknown" points the cone spuriously north.+ */+data class UserPuck(+ val position: GeoPoint,+ val bearing: Float? = null,+)
library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.ktindex 254707a37b..9cbdd4d9bd 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VectorMap.kt@@ -9,7 +9,9 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size@@ -20,6 +22,7 @@ import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.DpRect import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.math.roundToInt@@ -52,6 +55,9 @@ import kotlin.math.roundToInt * are `maps`' own contrast-checked `BasemapPalette`, so the apps agree with each other. * Switching is free: only a push constant changes. * @param imageOverlay a georeferenced translucent image drawn over the basemap.+ * @param userPuck the user's own location, drawn inside the renderer's frame so it stays+ * glued to the ground while the map moves. Defaults to drawing nothing; see [UserPuck]+ * for why this is not a [MapMarker]. * @param onFrame called after each presented frame. * * Kept for `library/map/src/androidTest/.../BasemapScreenshotTest.kt`, which counts frames@@ -73,12 +79,18 @@ fun VectorMap( zoomRange: ClosedFloatingPointRange<Float> = 0f..20f, options: MapOptions = MapOptions(), imageOverlay: ImageOverlay? = null,+ userPuck: UserPuck? = null, onMapClick: (GeoPoint) -> Unit = {}, /** * Tap with the screen point attached (see [MapClick]): what * `MapFeaturePicker`-style hit-testing needs. Null (default) means * taps report geo only, exactly as before — existing call sites, * including mapcompare, are unaffected.+ *+ * When [LayerOptions.poi] is on, [MapClick.poi] carries the topmost drawn POI under+ * the finger, so a host can open a place sheet for it and skip whatever it does with a+ * tap on empty map. The tap point is inflated by a touch slop first — a 19 Dp icon is+ * smaller than a fingertip. */ onMapClickWithScreen: ((MapClick) -> Unit)? = null, onFrame: () -> Unit = {},@@ -88,6 +100,36 @@ fun VectorMap( ) { val density = LocalDensity.current.density + // Read through `rememberUpdatedState` so the lambda handed to `mapGestures` keeps a+ // stable identity: its `pointerInput` is keyed on the camera and gesture options, not on+ // the callbacks, so a fresh lambda per recomposition would sit unused behind a detector+ // that never restarted.+ val latestScreenClick by rememberUpdatedState(onMapClickWithScreen)+ val poiEnabled = options.layerOptions.poi+ val latestPoiEnabled by rememberUpdatedState(poiEnabled)+ val screenClick = remember(cameraState) {+ { click: MapClick ->+ val handler = latestScreenClick+ if (handler != null) {+ // Queried only when POI is drawn: with the layer off there is nothing placed+ // to hit, and the query would be a pick over the place labels for nothing.+ val poi = if (latestPoiEnabled) {+ val point = click.screen+ val box = DpRect(+ left = point.x - POI_TOUCH_SLOP,+ top = point.y - POI_TOUCH_SLOP,+ right = point.x + POI_TOUCH_SLOP,+ bottom = point.y + POI_TOUCH_SLOP,+ )+ cameraState.projection?.queryRenderedLabels(box, POI_LAYER_IDS)?.firstOrNull()+ } else {+ null+ }+ handler(click.copy(poi = poi))+ }+ }+ }+ // Remembered and @Stable so the content lambda gets the same receiver across // recompositions. A fresh receiver every time would make large content subtrees — // `maps`' MapLayers is one — permanently unskippable.@@ -105,7 +147,7 @@ fun VectorMap( .onSizeChanged { cameraState.setViewport(Size(it.width / density, it.height / density)) }- .mapGestures(cameraState, options.gestureOptions, zoomRange, density, onMapClick, onMapClickWithScreen),+ .mapGestures(cameraState, options.gestureOptions, zoomRange, density, onMapClick, screenClick), ) { VulkanMapSurface( cameraState = cameraState,@@ -113,6 +155,7 @@ fun VectorMap( muted = style == MapStyle.Muted, layerOptions = options.layerOptions, archivePath = archivePath,+ userPuck = userPuck, modifier = Modifier.fillMaxSize(), onFrame = onFrame, fallback = fallback,@@ -165,6 +208,29 @@ private fun GeoreferencedOverlay(overlay: ImageOverlay, cameraState: CameraState } } +/**+ * How far around a tap to look for a POI.+ *+ * A POI icon is 19 Dp and a fingertip is nearer 40, so an exact-point test would make icons+ * feel unhittable. Half the Material minimum touch target, applied as a radius, gives a+ * 24 Dp box centred on the finger.+ */+private val POI_TOUCH_SLOP = 12.dp++/**+ * The style's six POI symbol layers, which is what [MapClick.poi] reports hits from. Place+ * labels (`places-*`) are deliberately excluded: a country or city label is not a point of+ * interest, and a host that wants those can query for them directly.+ */+private val POI_LAYER_IDS = setOf(+ "poi-outdoor",+ "poi-transport",+ "poi-civic",+ "poi-shop",+ "poi-food",+ "poi-culture",+)+ /** * Shown before any tile has loaded. Matches the renderer's own backdrop, so the surface * appearing does not flash a different colour.
library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.ktindex 0cc447b334..ae94f1629e 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/VulkanMapSurface.kt@@ -54,6 +54,7 @@ internal fun VulkanMapSurface( muted: Boolean, layerOptions: LayerOptions = LayerOptions(), archivePath: String? = null,+ userPuck: UserPuck? = null, modifier: Modifier = Modifier, onFrame: () -> Unit = {}, fallback: @Composable (MapRenderState.Unavailable) -> Unit = {},@@ -107,6 +108,10 @@ internal fun VulkanMapSurface( // a call that changes nothing, which is what makes driving it from an effect safe. LaunchedEffect(layerOptions, host) { host.setLayers(layerOptions) } + // A setter rather than an argument on the frame loop: a fix arrives at about 1 Hz and+ // `render` runs at 60, so the puck is state the renderer holds between frames.+ LaunchedEffect(userPuck, host) { host.setUserPuck(userPuck) }+ // Live connectivity, replacing a single sample taken in onSurfaceTextureAvailable. // Collected here rather than inside the host so every MapNative call stays on the // composition dispatcher, like setPalette and setLayers.@@ -198,6 +203,13 @@ private class MapSurfaceHost( */ private var online = true + /**+ * Remembered for the same reason as [layers]: a fix taken before the surface existed+ * has to reach the renderer before its first frame, or the puck is missing until the+ * next one arrives a second later.+ */+ private var userPuck: UserPuck? = null+ /** * Where cached byte ranges live. External files rather than the cache dir: this is * large and expensive to rebuild, so it should not be the first thing the platform@@ -228,7 +240,8 @@ private class MapSurfaceHost( MapNative.setOnline(handle, online) // Before the first frame, so the very first resident set is tessellated with // the layers the host asked for instead of being built and then invalidated.- MapNative.setLayers(handle, layers.poi, layers.transit)+ MapNative.setLayers(handle, layers.poi, layers.transit, layers.poiKinds.joinToString(","))+ applyUserPuck() renderState = MapRenderState.Rendering syncFrameLoop() }@@ -325,7 +338,7 @@ private class MapSurfaceHost( MapNative.pickLabels(h, box.left.value, box.top.value, box.right.value, box.bottom.value) .asSequence() .map { row -> row.split('') }- .filter { parts -> parts.size == 5 && (layerIds.isEmpty() || parts[0] in layerIds) }+ .filter { parts -> parts.size == 6 && (layerIds.isEmpty() || parts[0] in layerIds) } .map { parts -> PlacedLabel( layerId = parts[0],@@ -335,6 +348,9 @@ private class MapSurfaceHost( longitude = parts[3].toDoubleOrNull() ?: 0.0, latitude = parts[4].toDoubleOrNull() ?: 0.0, ),+ // Unsigned on the native side; ids never come close to the sign bit+ // (an OSM id shifted left two is ~36 bits), so a Long is roomy.+ featureId = parts[5].toLongOrNull() ?: 0L, ) } .toList()@@ -351,7 +367,9 @@ private class MapSurfaceHost( fun setLayers(options: LayerOptions) { this.layers = options- if (handle != 0L) MapNative.setLayers(handle, options.poi, options.transit)+ if (handle != 0L) {+ MapNative.setLayers(handle, options.poi, options.transit, options.poiKinds.joinToString(","))+ } } fun setOnline(online: Boolean) {@@ -359,6 +377,27 @@ private class MapSurfaceHost( if (handle != 0L) MapNative.setOnline(handle, online) } + fun setUserPuck(puck: UserPuck?) {+ this.userPuck = puck+ applyUserPuck()+ }++ private fun applyUserPuck() {+ if (handle == 0L) return+ val puck = userPuck+ if (puck == null) {+ MapNative.clearUserPuck(handle)+ } else {+ MapNative.setUserPuck(+ handle,+ puck.position.longitude.toFloat(),+ puck.position.latitude.toFloat(),+ puck.bearing ?: 0f,+ puck.bearing != null,+ )+ }+ }+ private companion object { const val TAG = "VulkanMapSurface" const val CACHE_DIR_NAME = "vectortilecache"
library/map/src/main/rust/assets/sprites/[email protected]
diff --git a/library/map/src/main/rust/assets/sprites/[email protected] b/library/map/src/main/rust/assets/sprites/[email protected]index 4e98508218..749206d689 100644--- a/library/map/src/main/rust/assets/sprites/[email protected]+++ b/library/map/src/main/rust/assets/sprites/[email protected]@@ -1 +1 @@-{"NL:S-road-1char":{"height":42,"pixelRatio":2,"width":42,"x":0,"y":72},"NL:S-road-2char":{"height":42,"pixelRatio":2,"width":44,"x":76,"y":42},"NL:S-road-3char":{"height":42,"pixelRatio":2,"width":50,"x":404,"y":36},"NL:S-road-4char":{"height":42,"pixelRatio":2,"width":58,"x":346,"y":0},"NL:S-road-5char":{"height":42,"pixelRatio":2,"width":64,"x":158,"y":0},"US:I-1char":{"height":42,"pixelRatio":2,"width":40,"x":168,"y":42},"US:I-2char":{"height":42,"pixelRatio":2,"width":46,"x":454,"y":36},"US:I-3char":{"height":42,"pixelRatio":2,"width":60,"x":286,"y":0},"US:I-4char":{"height":42,"pixelRatio":2,"width":64,"x":222,"y":0},"US:I-5char":{"height":42,"pixelRatio":2,"width":68,"x":90,"y":0},"aerodrome":{"height":38,"pixelRatio":2,"width":38,"x":120,"y":78},"animal":{"height":38,"pixelRatio":2,"width":38,"x":42,"y":84},"arrow":{"height":38,"pixelRatio":2,"width":38,"x":0,"y":114},"artwork":{"height":38,"pixelRatio":2,"width":38,"x":80,"y":84},"attraction":{"height":38,"pixelRatio":2,"width":38,"x":208,"y":42},"bar":{"height":38,"pixelRatio":2,"width":38,"x":246,"y":42},"beach":{"height":38,"pixelRatio":2,"width":38,"x":284,"y":42},"beauty":{"height":38,"pixelRatio":2,"width":38,"x":322,"y":42},"bench":{"height":38,"pixelRatio":2,"width":38,"x":360,"y":42},"books":{"height":38,"pixelRatio":2,"width":38,"x":398,"y":78},"building":{"height":34,"pixelRatio":2,"width":34,"x":386,"y":154},"bus_stop":{"height":38,"pixelRatio":2,"width":38,"x":436,"y":78},"cafe":{"height":38,"pixelRatio":2,"width":38,"x":474,"y":78},"capital":{"height":20,"pixelRatio":2,"width":20,"x":420,"y":154},"clothes":{"height":38,"pixelRatio":2,"width":38,"x":208,"y":80},"convenience":{"height":38,"pixelRatio":2,"width":38,"x":158,"y":84},"drinking_water":{"height":38,"pixelRatio":2,"width":38,"x":118,"y":116},"electronics":{"height":38,"pixelRatio":2,"width":38,"x":38,"y":122},"fast_food":{"height":38,"pixelRatio":2,"width":38,"x":0,"y":152},"ferry_terminal":{"height":38,"pixelRatio":2,"width":38,"x":76,"y":122},"forest":{"height":38,"pixelRatio":2,"width":38,"x":246,"y":80},"garden":{"height":38,"pixelRatio":2,"width":38,"x":284,"y":80},"generic_shield-1char":{"height":36,"pixelRatio":2,"width":38,"x":470,"y":0},"generic_shield-2char":{"height":36,"pixelRatio":2,"width":48,"x":120,"y":42},"generic_shield-3char":{"height":36,"pixelRatio":2,"width":66,"x":404,"y":0},"generic_shield-4char":{"height":36,"pixelRatio":2,"width":76,"x":0,"y":36},"generic_shield-5char":{"height":36,"pixelRatio":2,"width":90,"x":0,"y":0},"library":{"height":38,"pixelRatio":2,"width":38,"x":322,"y":80},"marina":{"height":38,"pixelRatio":2,"width":38,"x":360,"y":80},"museum":{"height":38,"pixelRatio":2,"width":38,"x":398,"y":116},"park":{"height":38,"pixelRatio":2,"width":38,"x":436,"y":116},"peak":{"height":38,"pixelRatio":2,"width":38,"x":474,"y":116},"post_office":{"height":38,"pixelRatio":2,"width":38,"x":196,"y":118},"restaurant":{"height":38,"pixelRatio":2,"width":38,"x":156,"y":122},"school":{"height":38,"pixelRatio":2,"width":38,"x":114,"y":154},"stadium":{"height":38,"pixelRatio":2,"width":38,"x":38,"y":160},"supermarket":{"height":38,"pixelRatio":2,"width":38,"x":0,"y":190},"theatre":{"height":38,"pixelRatio":2,"width":38,"x":76,"y":160},"toilets":{"height":38,"pixelRatio":2,"width":38,"x":234,"y":118},"townspot":{"height":20,"pixelRatio":2,"width":20,"x":440,"y":154},"train_station":{"height":38,"pixelRatio":2,"width":38,"x":272,"y":118},"university":{"height":38,"pixelRatio":2,"width":38,"x":310,"y":118},"zoo":{"height":38,"pixelRatio":2,"width":38,"x":348,"y":118}}\ No newline at end of file+{"NL:S-road-1char":{"height":42,"pixelRatio":2,"width":42,"x":0,"y":72},"NL:S-road-2char":{"height":42,"pixelRatio":2,"width":44,"x":76,"y":42},"NL:S-road-3char":{"height":42,"pixelRatio":2,"width":50,"x":404,"y":36},"NL:S-road-4char":{"height":42,"pixelRatio":2,"width":58,"x":346,"y":0},"NL:S-road-5char":{"height":42,"pixelRatio":2,"width":64,"x":158,"y":0},"US:I-1char":{"height":42,"pixelRatio":2,"width":40,"x":168,"y":42},"US:I-2char":{"height":42,"pixelRatio":2,"width":46,"x":454,"y":36},"US:I-3char":{"height":42,"pixelRatio":2,"width":60,"x":286,"y":0},"US:I-4char":{"height":42,"pixelRatio":2,"width":64,"x":222,"y":0},"US:I-5char":{"height":42,"pixelRatio":2,"width":68,"x":90,"y":0},"aerodrome":{"height":38,"pixelRatio":2,"width":38,"x":120,"y":78},"animal":{"height":38,"pixelRatio":2,"width":38,"x":42,"y":84},"arrow":{"height":38,"pixelRatio":2,"width":38,"x":0,"y":114},"artwork":{"height":38,"pixelRatio":2,"width":38,"x":80,"y":84},"attraction":{"height":38,"pixelRatio":2,"width":38,"x":208,"y":42},"bar":{"height":38,"pixelRatio":2,"width":38,"x":246,"y":42},"beach":{"height":38,"pixelRatio":2,"width":38,"x":284,"y":42},"beauty":{"height":38,"pixelRatio":2,"width":38,"x":322,"y":42},"bench":{"height":38,"pixelRatio":2,"width":38,"x":360,"y":42},"books":{"height":38,"pixelRatio":2,"width":38,"x":398,"y":78},"building":{"height":34,"pixelRatio":2,"width":34,"x":386,"y":154},"bus_stop":{"height":38,"pixelRatio":2,"width":38,"x":436,"y":78},"cafe":{"height":38,"pixelRatio":2,"width":38,"x":474,"y":78},"capital":{"height":20,"pixelRatio":2,"width":20,"x":420,"y":154},"clothes":{"height":38,"pixelRatio":2,"width":38,"x":208,"y":80},"convenience":{"height":38,"pixelRatio":2,"width":38,"x":158,"y":84},"drinking_water":{"height":38,"pixelRatio":2,"width":38,"x":118,"y":116},"electronics":{"height":38,"pixelRatio":2,"width":38,"x":38,"y":122},"fast_food":{"height":38,"pixelRatio":2,"width":38,"x":0,"y":152},"ferry_terminal":{"height":38,"pixelRatio":2,"width":38,"x":76,"y":122},"forest":{"height":38,"pixelRatio":2,"width":38,"x":246,"y":80},"garden":{"height":38,"pixelRatio":2,"width":38,"x":284,"y":80},"generic_shield-1char":{"height":36,"pixelRatio":2,"width":38,"x":470,"y":0},"generic_shield-2char":{"height":36,"pixelRatio":2,"width":48,"x":120,"y":42},"generic_shield-3char":{"height":36,"pixelRatio":2,"width":66,"x":404,"y":0},"generic_shield-4char":{"height":36,"pixelRatio":2,"width":76,"x":0,"y":36},"generic_shield-5char":{"height":36,"pixelRatio":2,"width":90,"x":0,"y":0},"library":{"height":38,"pixelRatio":2,"width":38,"x":322,"y":80},"marina":{"height":38,"pixelRatio":2,"width":38,"x":360,"y":80},"museum":{"height":38,"pixelRatio":2,"width":38,"x":398,"y":116},"park":{"height":38,"pixelRatio":2,"width":38,"x":436,"y":116},"peak":{"height":38,"pixelRatio":2,"width":38,"x":474,"y":116},"post_office":{"height":38,"pixelRatio":2,"width":38,"x":196,"y":118},"restaurant":{"height":38,"pixelRatio":2,"width":38,"x":156,"y":122},"school":{"height":38,"pixelRatio":2,"width":38,"x":114,"y":154},"stadium":{"height":38,"pixelRatio":2,"width":38,"x":38,"y":160},"supermarket":{"height":38,"pixelRatio":2,"width":38,"x":0,"y":190},"theatre":{"height":38,"pixelRatio":2,"width":38,"x":76,"y":160},"toilets":{"height":38,"pixelRatio":2,"width":38,"x":234,"y":118},"townspot":{"height":20,"pixelRatio":2,"width":20,"x":440,"y":154},"train_station":{"height":38,"pixelRatio":2,"width":38,"x":272,"y":118},"university":{"height":38,"pixelRatio":2,"width":38,"x":310,"y":118},"zoo":{"height":38,"pixelRatio":2,"width":38,"x":348,"y":118},"fuel":{"x":0,"y":228,"width":38,"height":38,"pixelRatio":2},"hotel":{"x":38,"y":228,"width":38,"height":38,"pixelRatio":2},"bank":{"x":76,"y":228,"width":38,"height":38,"pixelRatio":2},"atm":{"x":76,"y":228,"width":38,"height":38,"pixelRatio":2}}\ No newline at end of file
library/map/src/main/rust/assets/sprites/[email protected]
diff --git a/library/map/src/main/rust/assets/sprites/[email protected] b/library/map/src/main/rust/assets/sprites/[email protected]index a6765ac7c2..ff02a0e459 100644Binary files a/library/map/src/main/rust/assets/sprites/[email protected] and b/library/map/src/main/rust/assets/sprites/[email protected] differ
library/map/src/main/rust/examples/places_probe.rs
diff --git a/library/map/src/main/rust/examples/places_probe.rs b/library/map/src/main/rust/examples/places_probe.rsindex 396817ccd0..f8c0ebc6d8 100644--- a/library/map/src/main/rust/examples/places_probe.rs+++ b/library/map/src/main/rust/examples/places_probe.rs@@ -290,6 +290,7 @@ fn main() { coords: vec![(2048, 2048)], }], names: vec!["Testland".to_string()],+ ids: Vec::new(), }; let mesh = geometry::build(&body, layers, 6, 32, 40, false); println!(
library/map/src/main/rust/shaders/puck.frag
diff --git a/library/map/src/main/rust/shaders/puck.frag b/library/map/src/main/rust/shaders/puck.fragnew file mode 100644index 0000000000..61b80e1d22--- /dev/null+++ b/library/map/src/main/rust/shaders/puck.frag@@ -0,0 +1,84 @@+#version 450+// User puck: the bearing cone, the white rim and the blue dot, all from a distance and+// an angle rather than from geometry.+//+// Tessellating this would need a circle, an annulus sector with round caps, and+// per-vertex alpha the `fill` vertex format cannot carry. Solving it per fragment+// instead gives exact circles at any density, the real radial falloff across the cone's+// stroke, and antialiased edges that do not depend on MSAA.+layout(location = 0) in vec2 inLocal;+layout(location = 0) out vec4 outColor;+layout(push_constant) uniform Push {+ mat4 tileToClip;+ // The dot and the cone. The rim's colour is a constant, below.+ vec4 color;+ // Radii in device px: x the rim, y the dot, z the cone's centreline, w half the+ // cone's stroke width.+ vec4 line;+ // x: bearing in radians clockwise from north. y: 1 when there is a bearing at all,+ // 0 when the fix carries no heading and the cone must not draw. z: the quad's radius+ // in device px, which turns a local -1..1 coordinate into pixels.+ vec4 misc;+} push;++// The rim is white in both palettes. It exists to separate the dot from whatever is+// under it, and a rim that followed the basemap would stop doing that on one of them.+const vec3 RIM = vec3(1.0);+// Half the cone's 60 degree sweep.+const float CONE_HALF_SWEEP = radians(30.0);+const float PI = radians(180.0);++// Source-over, on premultiplied colour.+vec4 over(vec4 src, vec4 dst) {+ return src + dst * (1.0 - src.a);+}++// 1 inside, 0 outside, with one pixel of falloff across the edge.+float disc(float distancePx, float radiusPx) {+ return clamp(radiusPx + 0.5 - distancePx, 0.0, 1.0);+}++void main() {+ float quadPx = push.misc.z;+ vec2 p = inLocal * quadPx;+ float r = length(p);++ vec4 acc = vec4(0.0);++ if (push.misc.y > 0.5) {+ float conePx = push.line.z;+ float halfStrokePx = push.line.w;+ // Clockwise from north, matching a compass bearing: clip y points down, so "up"+ // is -y.+ float offset = atan(p.x, -p.y) - push.misc.x;+ // The shortest way round, so a cone pointing just west of north is two degrees+ // from it rather than 358.+ offset = mod(offset + PI, 2.0 * PI) - PI;+ // Distance to the arc's centreline: straight across it inside the sweep, and to+ // the nearer end point outside it, which is what gives the round caps.+ float toCentreline;+ if (abs(offset) <= CONE_HALF_SWEEP) {+ toCentreline = abs(r - conePx);+ } else {+ float capAngle = push.misc.x + sign(offset) * CONE_HALF_SWEEP;+ toCentreline = distance(p, conePx * vec2(sin(capAngle), -cos(capAngle)));+ }+ // The gradient is radial across the whole puck rather than across the stroke, so+ // the arc is fully opaque at its inner edge and only ~71% at its outer one.+ // Fading to zero across the stroke instead looks visibly flat.+ float fade = 1.0 - clamp((r - 0.8 * quadPx) / (0.2 * quadPx), 0.0, 1.0);+ float cone = disc(toCentreline, halfStrokePx) * fade;+ acc = over(vec4(push.color.rgb * cone, cone), acc);+ }++ // Rim then dot, both over the cone, so the dot is never eaten by the cone's inner+ // edge.+ float rim = disc(r, push.line.x);+ acc = over(vec4(RIM * rim, rim), acc);+ float core = disc(r, push.line.y);+ acc = over(vec4(push.color.rgb * core, core), acc);++ if (acc.a <= 0.0) discard;+ // Back to straight alpha: the pipeline blends src-alpha over one-minus-src-alpha.+ outColor = vec4(acc.rgb / acc.a, acc.a * push.color.a);+}
library/map/src/main/rust/shaders/puck.vert
diff --git a/library/map/src/main/rust/shaders/puck.vert b/library/map/src/main/rust/shaders/puck.vertnew file mode 100644index 0000000000..a717f116db--- /dev/null+++ b/library/map/src/main/rust/shaders/puck.vert@@ -0,0 +1,20 @@+#version 450+// User puck: one screen-anchored quad, drawn analytically by `puck.frag`.+//+// The vertex data is a fixed unit square in -1..1, uploaded once at startup. Where the+// puck sits and how big it is both live in the matrix, which for an overlay maps -1..1+// to a quad of a fixed Dp radius centred on a lon/lat rather than to a tile+// (`Camera::screen_quad_to_clip`). So a pan, a zoom and a new fix are all a push+// constant, and no buffer is touched after startup.+layout(location = 0) in vec2 inLocal;+layout(location = 0) out vec2 outLocal;+layout(push_constant) uniform Push {+ mat4 tileToClip;+ vec4 color;+ vec4 line;+ vec4 misc;+} push;+void main() {+ outLocal = inLocal;+ gl_Position = push.tileToClip * vec4(inLocal, 0.0, 1.0);+}
library/map/src/main/rust/src/bridge.rs
diff --git a/library/map/src/main/rust/src/bridge.rs b/library/map/src/main/rust/src/bridge.rsindex f4df0aa589..9d8d2dc90c 100644--- a/library/map/src/main/rust/src/bridge.rs+++ b/library/map/src/main/rust/src/bridge.rs@@ -23,7 +23,7 @@ use crate::tile::source::{ basemap_origin, CachingRangeReader, JniRangeFetcher, BASEMAP_ARCHIVE_URL, }; use crate::vulkan::context::{ANativeWindow_acquire, ANativeWindow_fromSurface};-use crate::vulkan::renderer::Renderer;+use crate::vulkan::renderer::{Renderer, UserPuck}; use jni::objects::{JClass, JObject, JString}; use jni::sys::{jboolean, jfloat, jint, jlong}; use jni::JNIEnv;@@ -328,9 +328,9 @@ fn spawn_worker( let key = tile.key(); // Read per tile, not once per worker: a toggle change has to reach the- // very next tile built, and both halves come from one atomic load so the+ // very next tile built, and all three parts come from one snapshot so the // stamp can never describe different flags than the mesh was built with.- let (enabled, generation) = toggles.get();+ let (enabled, kinds, generation) = toggles.get(); let result = match archive.tile(tile.z, tile.x, tile.y) { Ok(Some(body)) => TileResult::Ready(geometry::build_toggled( &body,@@ -340,6 +340,7 @@ fn spawn_worker( tile.y, rings_validated, enabled,+ &kinds, generation, )), Ok(None) => TileResult::Absent,@@ -400,10 +401,10 @@ fn spawn_file_worker( }; let Ok(tile) = next else { return }; let key = tile.key();- let (enabled, generation) = toggles.get();+ let (enabled, kinds, generation) = toggles.get(); let result = match archive.tile(tile.z, tile.x, tile.y) { Ok(Some(body)) => TileResult::Ready(geometry::build_toggled(- &body, layers, tile.z, tile.x, tile.y, rings_validated, enabled,+ &body, layers, tile.z, tile.x, tile.y, rings_validated, enabled, &kinds, generation, )), Ok(None) => TileResult::Absent,@@ -527,7 +528,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>( // toggle change re-requests the resident set through this same loop rather than // needing a path of its own. The stale mesh keeps drawing until its replacement // arrives.- let (_, generation) = map.toggles.get();+ let (_, _, generation) = map.toggles.get(); let keep: Vec<u64> = select::resident_set(&camera, min_zoom, max_zoom).iter().map(|t| t.key()).collect(); for tile in select::visible(&camera, min_zoom, max_zoom) {@@ -613,7 +614,48 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setPalette<'l> } } -/// Turn the optional layers on or off.+/// Show the user-location puck at `lon`/`lat`, drawn inside the renderer's own frame.+///+/// Free in the same sense as+/// [`setPalette`](Java_com_vayunmathur_library_map_MapNative_setPalette): pure state,+/// nothing re-tessellated and nothing re-uploaded. The quad is already on the GPU and+/// everything that varies about the puck is a push constant.+///+/// `bearing` is degrees clockwise from north and is only read when `has_bearing` is set;+/// without it the dot draws and the cone does not, which is what a fix with no heading+/// should look like rather than one pointing north.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setUserPuck<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ lon: jfloat,+ lat: jfloat,+ bearing: jfloat,+ has_bearing: jboolean,+) {+ if let Some(map) = handle_mut(handle) {+ map.renderer.set_user_puck(Some(UserPuck {+ lon: lon as f64,+ lat: lat as f64,+ bearing: (has_bearing != 0).then_some(bearing),+ }));+ }+}++/// Take the puck away: no fix, or a host that stopped asking for one.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_clearUserPuck<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if let Some(map) = handle_mut(handle) {+ map.renderer.set_user_puck(None);+ }+}++/// Turn the optional layers on or off, and narrow POI to a set of kinds. /// /// Not free, unlike [`setPalette`](Java_com_vayunmathur_library_map_MapNative_setPalette): /// POI and transit are gated at tessellation time so that leaving them off costs nothing,@@ -622,20 +664,37 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setPalette<'l> /// them through the existing worker pool, reading the archive it already has. Nothing is /// refetched, nothing is evicted, and the old meshes keep drawing until the new ones land. ///+/// `kinds` is a comma-separated list of archive kind names — the app's category chips. Empty+/// means every kind the style draws. A name the schema has no id for is skipped rather than+/// refused: the chip list is app data and a typo there should narrow the map oddly, not blank it.+/// /// A call that changes nothing bumps nothing, because the host is expected to call this /// from a Compose effect that may re-run for unrelated reasons. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_setLayers<'l>(- _env: JNIEnv<'l>,+ mut env: JNIEnv<'l>, _class: JClass<'l>, handle: jlong, poi: jboolean, transit: jboolean,+ kinds: JString<'l>, ) {+ let names: String = env.get_string(&kinds).map(Into::into).unwrap_or_default();+ let filter = style::KindFilter::new(+ names+ .split(',')+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .filter_map(style::kind_id)+ .collect(),+ ); if let Some(map) = handle_mut(handle) { let wanted = LayerToggles { poi: poi != 0, transit: transit != 0 };- if map.toggles.set(wanted) {- log_info(&format!("layers changed: poi={} transit={}", wanted.poi, wanted.transit));+ if map.toggles.set(wanted, filter) {+ log_info(&format!(+ "layers changed: poi={} transit={} kinds=[{names}]",+ wanted.poi, wanted.transit,+ )); } } }@@ -668,10 +727,14 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_destroy<'l>( } /// Task-17 pick: placed labels intersecting the query box (Dp from the-/// viewport top-left). Returns `\u{1}`-joined `layerId/name/kind/lon/lat`-/// strings in placement order; empty when nothing hits. Dp→device-px via the+/// viewport top-left). Returns `\u{1}`-joined `layerId/name/kind/lon/lat/featureId`+/// strings in placement order (topmost first); empty when nothing hits. Dp→device-px via the /// last frame's density, remembered on the map handle (same density the /// boxes were built with — boxes are device px, the query arrives in Dp).+///+/// `kind` is the feature's own kind, not its layer's first one, so a `poi-food` hit says+/// `cafe` rather than `restaurant`. `featureId` is the archive's stable id, or `0` for a+/// feature that has none. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_pickLabels<'l>( mut env: JNIEnv<'l>,@@ -702,7 +765,10 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_pickLabels<'l> }; for (i, h) in hits.iter().enumerate() { let layer_id = layers.get(h.layer_index).map(|l| l.id.as_str()).unwrap_or("");- let s = format!("{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}", layer_id, h.name, h.kind, h.lon, h.lat);+ let s = format!(+ "{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}",+ layer_id, h.name, h.kind, h.lon, h.lat, h.feature_id,+ ); let Ok(js) = env.new_string(s) else { continue }; let _ = env.set_object_array_element(&out, i as i32, js); }
library/map/src/main/rust/src/camera.rs
diff --git a/library/map/src/main/rust/src/camera.rs b/library/map/src/main/rust/src/camera.rsindex 58c91f9f6c..a8614be637 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -119,6 +119,36 @@ impl Camera { tx as f32, ty as f32, 0.0, 1.0, ] }++ /// Column-major 4x4 taking a quad's local −1..1 coordinates to Vulkan clip space,+ /// for a quad of `radius_dp` centred on `lon`/`lat`.+ ///+ /// The screen-anchored sibling of [`tile_to_clip`](Self::tile_to_clip). Same+ /// derivation, but the extent is a fixed number of Dp instead of a tile span, so the+ /// quad keeps its screen size as the camera zooms while staying glued to its ground+ /// position. That is what an overlay wants and what a tile address cannot express:+ /// the alternative is to find the tile containing the point and borrow its matrix,+ /// which works for a POI icon because a POI *is* tile data, and is a fiction for+ /// anything that is not.+ ///+ /// The y-sign note on [`tile_to_clip`](Self::tile_to_clip) applies here too: Vulkan+ /// clip y and Mercator y both point down, so there is no flip.+ pub fn screen_quad_to_clip(&self, lon: f64, lat: f64, radius_dp: f64) -> [f32; 16] {+ let center = project(lon, lat, self.zoom);+ let origin = self.viewport_origin();++ let sx = 2.0 * radius_dp / self.width_dp as f64;+ let sy = 2.0 * radius_dp / self.height_dp as f64;+ let tx = 2.0 * (center.x - origin.x) / self.width_dp as f64 - 1.0;+ let ty = 2.0 * (center.y - origin.y) / self.height_dp as f64 - 1.0;++ [+ sx as f32, 0.0, 0.0, 0.0, //+ 0.0, sy as f32, 0.0, 0.0, //+ 0.0, 0.0, 1.0, 0.0, //+ tx as f32, ty as f32, 0.0, 1.0,+ ]+ } } #[cfg(test)]@@ -277,6 +307,50 @@ mod tests { assert!(p.y >= -1.0 && p.y <= size + 1.0, "y at lat {lat} is {}, off the map", p.y); } }++ #[test]+ fn a_screen_quad_on_the_camera_centre_lands_on_the_clip_origin() {+ // The puck's whole point is being glued to a ground position, and the camera+ // centre is the one position whose clip coordinate is known without arithmetic.+ let camera = Camera { center_lon: -122.4194, center_lat: 37.7749, ..camera(14.0) };+ let m = camera.screen_quad_to_clip(-122.4194, 37.7749, 28.0);+ let (x, y) = transform(&m, 0.0, 0.0);+ assert!(x.abs() < 1e-5, "x {x}");+ assert!(y.abs() < 1e-5, "y {y}");+ }++ #[test]+ fn a_screen_quad_keeps_its_dp_size_across_zooms_and_grows_with_the_viewport() {+ // A tile quad doubles on screen every zoom; this one must not, or the puck would+ // swell into a blue disc the size of a city block at z18.+ let close = Camera { center_lon: 0.0, center_lat: 0.0, ..camera(18.0) };+ let far = Camera { center_lon: 0.0, center_lat: 0.0, ..camera(4.0) };+ let (near_x, _) = transform(&close.screen_quad_to_clip(0.0, 0.0, 28.0), 1.0, 0.0);+ let (wide_x, _) = transform(&far.screen_quad_to_clip(0.0, 0.0, 28.0), 1.0, 0.0);+ assert!((near_x - wide_x).abs() < 1e-6, "{near_x} vs {wide_x}");+ // 28 Dp of a 512 Dp viewport is 28/256 of the half-width of clip space.+ assert!((near_x - 28.0 / 256.0).abs() < 1e-5, "{near_x}");+ }++ #[test]+ fn a_screen_quad_is_the_same_size_at_every_density() {+ // The radius is Dp, like `tile_span_dp`. Density enters only where a Dp becomes a+ // device pixel, which for the puck is the shader's radii — not this matrix.+ let one = Camera { density: 1.0, ..camera(14.0) };+ let three = Camera { density: 3.0, ..camera(14.0) };+ assert_eq!(one.screen_quad_to_clip(0.0, 0.0, 28.0), three.screen_quad_to_clip(0.0, 0.0, 28.0));+ }++ #[test]+ fn a_screen_quad_far_off_screen_falls_outside_the_clip_cube() {+ // A fix taken in another country must not smear a puck across the edge of the+ // viewport: the whole quad has to clip out.+ let camera = Camera { center_lon: -122.4194, center_lat: 37.7749, ..camera(14.0) };+ let m = camera.screen_quad_to_clip(2.3522, 48.8566, 28.0);+ let (left, _) = transform(&m, -1.0, 0.0);+ let (right, _) = transform(&m, 1.0, 0.0);+ assert!(left > 1.0 && right > 1.0, "Paris at {left}..{right} should be off to the right");+ } } // device-verifier: mtime bump to force cargo recompile (no semantic change)
library/map/src/main/rust/src/style/mod.rs
diff --git a/library/map/src/main/rust/src/style/mod.rs b/library/map/src/main/rust/src/style/mod.rsindex 14f5f5ffad..d41bff2c78 100644--- a/library/map/src/main/rust/src/style/mod.rs+++ b/library/map/src/main/rust/src/style/mod.rs@@ -95,8 +95,61 @@ impl LayerToggles { } } -/// The toggles plus a generation counter, in one atomic word, shared with the tile-/// workers.+/// Which POI kinds the map is narrowed to, or empty for "every kind the style draws".+///+/// The app's category chips (Food, Gas, Hotels, …) select a handful of kinds out of the six+/// `poi-*` layers' thirty-nine. That is a *sub-layer* filter, so it cannot be expressed by+/// turning layers off, and it cannot ride in [`SharedToggles`]' packed word either — there are+/// more kinds than a `u32` has bits.+///+/// Interned ids rather than names, sorted, so the per-feature test is a binary search over a+/// `u16` slice — the same shape [`Layer::matches_id`] already uses for the layer's own whitelist.+/// An `Arc` because a worker holds it for the length of a tile build while the host may replace it.+#[derive(Clone, Debug, Default)]+pub struct KindFilter(std::sync::Arc<[u16]>);++impl PartialEq for KindFilter {+ fn eq(&self, other: &KindFilter) -> bool {+ // By value, not by pointer: the host rebuilds this list on every recomposition, so a+ // pointer comparison would report a change on every frame and re-tessellate forever.+ self.0[..] == other.0[..]+ }+}++impl Eq for KindFilter {}++impl KindFilter {+ /// Every kind. The default, and what an empty chip selection means.+ pub fn all() -> KindFilter {+ KindFilter(std::sync::Arc::from(Vec::new()))+ }++ /// A filter over interned kind ids. Sorted and deduplicated here so callers need not be.+ pub fn new(mut kinds: Vec<u16>) -> KindFilter {+ kinds.sort_unstable();+ kinds.dedup();+ KindFilter(std::sync::Arc::from(kinds))+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ /// Does this filter admit `kind` on `layer`?+ ///+ /// Only POI layers are filtered. The chips narrow which *points of interest* are shown; a+ /// road or a country label is not one, and hiding the basemap because the user tapped+ /// "Coffee" would be absurd.+ pub fn admits(&self, layer: &Layer, kind: u16) -> bool {+ if self.0.is_empty() || layer.toggle != Some(Toggle::Poi) {+ return true;+ }+ self.0.binary_search(&kind).is_ok()+ }+}++/// The toggles, the POI kind filter and a generation counter, read as one snapshot and shared+/// with the tile workers. /// /// Gating happens at **tessellation** time rather than at draw time, because that is /// where the cost is: with POI off, no label is shaped and no placement candidate is@@ -107,44 +160,55 @@ impl LayerToggles { /// evicted — the same "re-decorate without reloading" shape as a palette switch, one step /// heavier. ///-/// One word rather than three atomics so a worker's read is a consistent snapshot: a-/// mesh tagged with one generation but built from another's flags would either never be-/// refreshed or be refreshed forever.+/// One snapshot rather than a field each so a worker's read is consistent: a mesh tagged with+/// one generation but built from another's flags would either never be refreshed or be refreshed+/// forever. This was a single `AtomicU32` while the state was two bits and a counter; the kind+/// filter does not fit in a word, so it is a lock — taken once per tile build, not per feature. #[derive(Debug)]-pub struct SharedToggles(std::sync::atomic::AtomicU32);+pub struct SharedToggles(std::sync::RwLock<Snapshot>);++#[derive(Clone, Debug)]+struct Snapshot {+ toggles: LayerToggles,+ kinds: KindFilter,+ generation: u32,+} impl SharedToggles { /// Generations start at 1, so a mesh from a default-initialised 0 is always stale. pub fn new(toggles: LayerToggles) -> SharedToggles {- SharedToggles(std::sync::atomic::AtomicU32::new(Self::pack(toggles, 1)))+ SharedToggles(std::sync::RwLock::new(Snapshot {+ toggles,+ kinds: KindFilter::all(),+ generation: 1,+ })) } - fn pack(toggles: LayerToggles, generation: u32) -> u32 {- (generation << 2) | (u32::from(toggles.poi) << 1) | u32::from(toggles.transit)+ /// The current toggles, kind filter and the generation they belong to.+ pub fn get(&self) -> (LayerToggles, KindFilter, u32) {+ // A poisoned lock means another thread panicked mid-set. The state behind it is three+ // plain values with no invariant between them beyond the generation, so reading it is+ // sound; refusing to draw the map because a worker died is worse than drawing it.+ let snapshot = self.0.read().unwrap_or_else(|e| e.into_inner());+ (snapshot.toggles, snapshot.kinds.clone(), snapshot.generation) } - /// The current toggles and the generation they belong to.- pub fn get(&self) -> (LayerToggles, u32) {- let word = self.0.load(std::sync::atomic::Ordering::Acquire);- (- LayerToggles { poi: word & 0b10 != 0, transit: word & 0b01 != 0 },- word >> 2,- )- }-- /// Set the toggles, bumping the generation. Returns `true` when anything changed.+ /// Set the toggles and the kind filter, bumping the generation. Returns `true` when+ /// anything changed.+ ///+ /// Both at once rather than one setter each: the host sets them from a single Compose+ /// effect, and two bumps would re-tessellate the whole resident set twice for one change. /// /// A no-op set must not bump: the host may call this on every recomposition, and a /// bump there would re-tessellate the whole resident set for nothing.- pub fn set(&self, toggles: LayerToggles) -> bool {- let (current, generation) = self.get();- if current == toggles {+ pub fn set(&self, toggles: LayerToggles, kinds: KindFilter) -> bool {+ let mut snapshot = self.0.write().unwrap_or_else(|e| e.into_inner());+ if snapshot.toggles == toggles && snapshot.kinds == kinds { return false; }- self.0.store(- Self::pack(toggles, generation.wrapping_add(1).max(1)),- std::sync::atomic::Ordering::Release,- );+ snapshot.toggles = toggles;+ snapshot.kinds = kinds;+ snapshot.generation = snapshot.generation.wrapping_add(1).max(1); true } }@@ -524,7 +588,7 @@ impl Layer { } /// A `kind` name's interned id, or `None` when the schema has no counterpart.-fn kind_id(name: &str) -> Option<u16> {+pub fn kind_id(name: &str) -> Option<u16> { dict::KINDS.iter().position(|k| *k == name).map(|i| i as u16 + 1) } @@ -568,6 +632,53 @@ pub fn layers() -> &'static [Layer] { mod tests { use super::*; + /// The chips narrow POI and nothing else. A filter that hid roads and country labels+ /// because the user tapped "Coffee" would be a blank map, not a filtered one.+ #[test]+ fn a_kind_filter_narrows_poi_layers_only() {+ let poi = layers().iter().find(|l| l.id == "poi-food").expect("poi-food");+ let road = layers().iter().find(|l| l.toggle.is_none()).expect("a basemap layer");+ let cafe = kind_id("cafe").expect("cafe");+ let bar = kind_id("bar").expect("bar");++ let all = KindFilter::all();+ assert!(all.is_empty());+ assert!(all.admits(poi, cafe), "an empty filter admits everything");+ assert!(all.admits(poi, bar));++ let coffee = KindFilter::new(vec![cafe]);+ assert!(coffee.admits(poi, cafe));+ assert!(!coffee.admits(poi, bar), "a POI kind outside the filter is dropped");+ assert!(coffee.admits(road, bar), "a basemap layer is never narrowed");+ }++ /// Equality is by value. The host rebuilds the chip list on every recomposition, so a+ /// pointer comparison would report a change every frame and re-tessellate the resident set+ /// forever — which is exactly what the no-op rule exists to prevent.+ #[test]+ fn setting_the_same_filter_twice_does_not_bump_the_generation() {+ let cafe = kind_id("cafe").expect("cafe");+ let bar = kind_id("bar").expect("bar");+ let shared = SharedToggles::new(LayerToggles::default());+ let (_, _, first) = shared.get();++ let on = LayerToggles { poi: true, transit: false };+ assert!(shared.set(on, KindFilter::new(vec![cafe, bar])));+ let (toggles, kinds, second) = shared.get();+ assert!(toggles.poi);+ assert_ne!(second, first, "a real change bumps");++ // A freshly built, separately allocated filter holding the same kinds in the other+ // order — `new` sorts, so it must compare equal and bump nothing.+ assert!(!shared.set(on, KindFilter::new(vec![bar, cafe])));+ let (_, again, third) = shared.get();+ assert_eq!(third, second, "an identical set must not bump");+ assert_eq!(again, kinds);++ assert!(shared.set(on, KindFilter::all()), "clearing the chips is a change");+ assert_ne!(shared.get().2, third);+ }+ /// Perceived luminance, for asserting a palette is actually light or dark. fn luminance(argb: u32) -> f32 { let r = ((argb >> 16) & 0xFF) as f32 / 255.0;
library/map/src/main/rust/src/style/paint.rs
diff --git a/library/map/src/main/rust/src/style/paint.rs b/library/map/src/main/rust/src/style/paint.rsindex 2a64f9a4f7..d9183a97b2 100644--- a/library/map/src/main/rust/src/style/paint.rs+++ b/library/map/src/main/rust/src/style/paint.rs@@ -617,8 +617,17 @@ mod tests { drawn.sort_unstable(); drawn.dedup(); assert_eq!(before, drawn.len(), "a kind is claimed by two POI layers");+ // Four kinds are ours, not the reference's. The `maps` app has always offered Gas,+ // Hotels and ATM chips and the reference basemap draws none of those three, so the+ // chips could only ever have filtered a set that did not contain their subject. Stated+ // as an explicit extension rather than folded into the count, so this test still fails+ // if a kind is added to a POI layer by accident.+ const LOCAL: &[&str] = &["atm", "bank", "fuel", "hotel"];+ let (local, reference): (Vec<String>, Vec<String>) =+ drawn.into_iter().partition(|kind| LOCAL.contains(&kind.as_str()));+ assert_eq!(local, LOCAL, "the local POI extension is exactly these four kinds"); admitted.sort_unstable();- assert_eq!(drawn, admitted, "the POI layers do not cover the reference filter");+ assert_eq!(reference, admitted, "the POI layers do not cover the reference filter"); } #[test]
library/map/src/main/rust/src/tile/geometry.rs
diff --git a/library/map/src/main/rust/src/tile/geometry.rs b/library/map/src/main/rust/src/tile/geometry.rsindex f6a36d04bf..17a3cae3fd 100644--- a/library/map/src/main/rust/src/tile/geometry.rs+++ b/library/map/src/main/rust/src/tile/geometry.rs@@ -10,7 +10,7 @@ //! geometry-command walk. Nothing downstream of here changed — fills are still 2 floats a vertex, //! strokes 7, and the shaders never saw any of it. -use crate::style::{Layer, LayerKind, LayerToggles};+use crate::style::{KindFilter, Layer, LayerKind, LayerToggles}; use crate::tess::{fill, stroke}; use crate::tile::symbol; use crate::tile::select::ANCESTOR_DEPTH;@@ -75,6 +75,17 @@ pub struct ShapedLabel { /// carries. `None` for every place label, and for the one POI kind (`townhall`) the /// sheet has no picture of. pub sprite: Option<crate::tile::sprite::Sprite>,+ /// The feature's **own** interned `kind`, not its layer's whitelist.+ ///+ /// A symbol layer filters on several kinds — `poi-food` draws `restaurant`, `fast_food`,+ /// `cafe` and `bar` — so the layer cannot say which one a given label is. A pick that+ /// reports the layer's first kind reports `restaurant` for every food POI, which is what+ /// this field exists to stop.+ pub kind: u16,+ /// The archive's stable id for this feature, or+ /// [`ID_NONE`](tilecodec::mamaps::body::ID_NONE) when its layer carries no id table (every+ /// layer but `places` and `poi`) or the generator could not attribute it to an OSM element.+ pub feature_id: u64, } /// Every layer's geometry for one tile, ready to upload.@@ -119,7 +130,17 @@ pub fn build( y: u32, rings_validated: bool, ) -> TileMesh {- build_toggled(tile, layers, z, x, y, rings_validated, LayerToggles::default(), 0)+ build_toggled(+ tile,+ layers,+ z,+ x,+ y,+ rings_validated,+ LayerToggles::default(),+ &KindFilter::all(),+ 0,+ ) } /// [`build`] with the optional layers the host has turned on.@@ -128,8 +149,8 @@ pub fn build( /// tests use, so adding an optional layer does not touch a dozen call sites that have no /// opinion about POI. ///-/// `generation` is stamped onto the result unchanged; the caller reads it and the toggles-/// from the same [`crate::style::SharedToggles`] snapshot so the two cannot disagree.+/// `generation` is stamped onto the result unchanged; the caller reads it, the toggles and+/// `kinds` from the same [`crate::style::SharedToggles`] snapshot so the three cannot disagree. #[allow(clippy::too_many_arguments)] pub fn build_toggled( tile: &Body,@@ -139,6 +160,7 @@ pub fn build_toggled( y: u32, rings_validated: bool, toggles: LayerToggles,+ kinds: &KindFilter, generation: u32, ) -> TileMesh { let mut meshes = Vec::with_capacity(layers.len());@@ -167,7 +189,7 @@ pub fn build_toggled( #[allow(clippy::type_complexity)] let mut coloured: Vec<((u32, u8, u8, u8), Vec<f32>, Vec<u32>)> = Vec::new(); - for feature in &source.features {+ for (feature_index, feature) in source.features.iter().enumerate() { // Kind, then the road flag/detail filters: one call, so a surface layer never // draws the ramps, bridges, tunnels and service streets its `kind` alone would // admit. This used to be a `String` allocation and a property-map lookup per@@ -175,6 +197,12 @@ pub fn build_toggled( if !layer.matches_feature(feature) { continue; }+ // The app's category chips, when it has narrowed the map to a few POI kinds. A+ // second sorted-slice test beside the layer's own, and an empty filter admits+ // everything, so the common case is one branch.+ if !kinds.admits(layer, feature.kind) {+ continue;+ } let parts = source.parts_of(feature); match layer.kind { LayerKind::Fill => {@@ -237,9 +265,15 @@ pub fn build_toggled( if name.is_empty() { continue; }- if let Some(label) =- symbol::shape_label(layer, tile, feature, name, extent, index)- {+ if let Some(label) = symbol::shape_label(+ layer,+ tile,+ feature,+ name,+ extent,+ index,+ feature_index,+ ) { labels.push(label); } }@@ -596,7 +630,7 @@ mod tests { ); let on = LayerToggles { poi: false, transit: true };- let mesh = build_toggled(&body, only, 14, 0, 0, false, on, 7);+ let mesh = build_toggled(&body, only, 14, 0, 0, false, on, &KindFilter::all(), 7); assert_eq!(mesh.generation, 7, "the mesh records the generation it was built at"); let colours: Vec<Option<u32>> = mesh.meshes.iter().map(|m| m.color_override).collect(); assert_eq!(@@ -649,7 +683,7 @@ mod tests { let at = all.iter().position(|l| l.id == "transit-rail").expect("the transit layer"); let Some(only) = all.get(at..=at) else { panic!("a one-layer slice") }; let on = LayerTog
Diff truncated.