Modern Apps git

← Modern-Apps.git

various fixes

Commit
f044dc40323519941e2cf9d2f114ed6ee2f1014b
Author
vayun-mathur <[email protected]>
When
2026-09-16 22:08 UTC (2 months ago)
Parents
2aedfc8

Diff

.github/workflows/android.yml
diff --git a/.github/workflows/android.yml b/.github/workflows/android.ymlindex 3cc69b4a64..add1eebfb2 100644--- a/.github/workflows/android.yml+++ b/.github/workflows/android.yml@@ -51,11 +51,11 @@ jobs:       - name: Configure Gradle for CI runner         run: |           # GitHub-hosted Linux runners are ~16GB RAM / ~4 vCPU. The project's-          # local gradle.properties sizes the daemon at -Xmx46g for a full local-          # build of every module at once, which cannot start on a runner.-          # GRADLE_USER_HOME (~/.gradle)/gradle.properties overrides the project-          # gradle.properties, so cap heap + workers to runner-appropriate values-          # here rather than changing the local dev defaults.+          # local gradle.properties defaults to a small daemon heap sized for+          # scoped builds (./install all auto-escalates locally); cap heap ++          # workers to runner-appropriate values via GRADLE_USER_HOME+          # (~/.gradle)/gradle.properties, which overrides the project+          # gradle.properties, here rather than changing the local dev defaults.           mkdir -p ~/.gradle           {             echo 'org.gradle.jvmargs=-Xmx6144m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8'
.github/workflows/pr-compile-check.yml
diff --git a/.github/workflows/pr-compile-check.yml b/.github/workflows/pr-compile-check.ymlindex 2ca19a8170..7695cd33ff 100644--- a/.github/workflows/pr-compile-check.yml+++ b/.github/workflows/pr-compile-check.yml@@ -30,10 +30,11 @@ jobs:       - name: Configure Gradle for CI runner         run: |           # GitHub-hosted Linux runners are ~16GB RAM / ~4 vCPU. The project's-          # local gradle.properties sizes the daemon at -Xmx46g, which cannot-          # start on a runner. GRADLE_USER_HOME (~/.gradle)/gradle.properties-          # overrides the project gradle.properties, so cap heap + workers to-          # runner-appropriate values here (leaves the local dev defaults alone).+          # local gradle.properties defaults to a small daemon heap (./install+          # all auto-escalates locally); GRADLE_USER_HOME (~/.gradle)/+          # gradle.properties overrides the project gradle.properties, so cap+          # heap + workers to runner-appropriate values here (leaves the local+          # dev defaults alone).           mkdir -p ~/.gradle           {             echo 'org.gradle.jvmargs=-Xmx6144m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8'
.vscode/settings.json
diff --git a/.vscode/settings.json b/.vscode/settings.jsonnew file mode 100644index 0000000000..64ad6374ce--- /dev/null+++ b/.vscode/settings.json@@ -0,0 +1,36 @@+{+  // Token-burn guard: keep repo-wide search out of generated / vendored / binary noise.+  // See .llms/repo-map.md "Never scan". Scoped single-file reads still work —+  // this only affects unscoped search.+  "search.exclude": {+    "**/build": true,+    "**/target": true,+    "**/.gradle": true,+    "**/.kotlin": true,+    "**/.cxx": true,+    "**/.externalNativeBuild": true,+    "**/metadata_data/photos": true,+    "**/schemas": true,+    "**/third_party": true,+    "**/firmware": true,+    "**/node_modules": true,+    "**/dist": true,+    "**/tmp": true,+    "**/*.onnx": true,+    "**/*.log": true,+    "**/*.bin": true,+    "**/*.pmtiles": true,+    "**/personal": true,+    "**/analysis": true+  },+  "files.watcherExclude": {+    "**/build/**": true,+    "**/target/**": true,+    "**/.gradle/**": true,+    "**/.kotlin/**": true,+    "**/metadata_data/photos/**": true,+    "**/third_party/**": true,+    "**/firmware/**": true,+    "**/node_modules/**": true+  }+}
CONTRIBUTING.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4df08e562e..b1bc5c498f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -31,8 +31,11 @@ mechanically, and how to run those checks yourself.  Point `local.properties` at your SDK. Apps build **arm64-only** by default. -**Gradle memory.** `gradle.properties` sets `-Xmx46g`, sized for building every module at once-on a large workstation. Do not lower it in the repo — override it for your machine in+**Gradle memory.** `gradle.properties` defaults to a small daemon heap (`-Xmx8g`,+`-Xms512m`, 2 workers) sized for scoped `:module:` builds — the thing agents and+day-to-day dev actually run. `./install all` auto-escalates to the big heap for+the full ~100-module build, so don't raise the default. If your machine needs+different values, override them for your machine in `~/.gradle/gradle.properties` (which takes precedence), the way CI does:  ```properties
_tmp_npm.json
diff --git a/_tmp_npm.json b/_tmp_npm.jsonnew file mode 100644index 0000000000..0c2c7b061e--- /dev/null+++ b/_tmp_npm.json@@ -0,0 +1 @@+{"bugs":{"url":"https://github.com/software-mansion/react-native-executorch/issues"},"dist":{"shasum":"74438e226da231b7886cc89327861ecc4eb5ebec","tarball":"https://registry.npmjs.org/react-native-executorch/-/react-native-executorch-0.10.2.tgz","fileCount":1021,"integrity":"sha512-0OF/WkNnKpYipClIG3Ev2FBj3e/C1T4LCFjvmp8/cfpeMUxAVzRVkEddR/mxovesXu6AC0xyfMumOhxIXCbJUQ==","signatures":[{"sig":"MEYCIQCBKDx+JVWlu8lmbfFKKS0XBRhUuHl2yG1zp2UWdWuDTAIhAKXM14gysf4b34SkRsOxWyivQ5jDzRYBqCCEu5PMBg+z","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/[email protected]","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":7351364},"main":"./lib/module/index.js","name":"react-native-executorch","_from":"file:react-native-executorch-0.10.2.tgz","types":"./lib/typescript/src/index.d.ts","author":{"url":"https://github.com/software-mansion","name":"Software Mansion","email":"[email protected]"},"module":"./lib/module/index.js","source":"./src/index.ts","exports":{".":{"types":"./lib/typescript/src/index.d.ts","source":"./src/index.ts","default":"./lib/module/index.js"},"./cv":{"types":"./lib/typescript/src/extensions/cv/index.d.ts","source":"./src/extensions/cv/index.ts","default":"./lib/module/extensions/cv/index.js"},"./llm":{"types":"./lib/typescript/src/extensions/llm/index.d.ts","source":"./src/extensions/llm/index.ts","default":"./lib/module/extensions/llm/index.js"},"./nlp":{"types":"./lib/typescript/src/extensions/nlp/index.d.ts","source":"./src/extensions/nlp/index.ts","default":"./lib/module/extensions/nlp/index.js"},"./math":{"types":"./lib/typescript/src/extensions/math.d.ts","source":"./src/extensions/math.ts","default":"./lib/module/extensions/math.js"},"./legacy":{"types":"./lib/typescript/legacy/src/index.d.ts","source":"./legacy/src/index.ts","default":"./lib/module/legacy/src/index.js"},"./schema":{"types":"./lib/typescript/src/core/schema.d.ts","source":"./src/core/schema.ts","default":"./lib/module/core/schema.js"},"./speech":{"types":"./lib/typescript/src/extensions/speech/index.d.ts","source":"./src/extensions/speech/index.ts","default":"./lib/module/extensions/speech/index.js"},"./package.json":"./package.json"},"license":"MIT","scripts":{"lint":"eslint \"**/*.{js,ts,tsx}\"","test":"jest","clean":"del-cli lib","prepack":"cp ../../README.md ./README.md","prepare":"bob build && tsc -p legacy/tsconfig.json","lint:cpp":"./scripts/clang-tidy.sh","postpack":"rm ./README.md","typecheck":"tsc --noEmit","postinstall":"node scripts/download-libs.js"},"_npmUser":{"name":"GitHub Actions","email":"[email protected]","trustedPublisher":{"id":"github","oidcConfigId":"oidc:073df60a-4a1a-479c-9a5a-c38b010039ae"}},"homepage":"https://docs.swmansion.com/react-native-executorch","keywords":["text-to-speech","ocr","computer-vision","segmentation","object-detection","speech-to-text","vlm","image-embeddings","on-device-ai","text-embeddings","llm","ai","react-native","ios","android","executorch"],"_resolved":"/home/runner/work/react-native-executorch/react-native-executorch/react-native-executorch-0.10.2.tgz","_integrity":"sha512-0OF/WkNnKpYipClIG3Ev2FBj3e/C1T4LCFjvmp8/cfpeMUxAVzRVkEddR/mxovesXu6AC0xyfMumOhxIXCbJUQ==","repository":{"url":"git+https://github.com/software-mansion/react-native-executorch.git","type":"git","directory":"packages/react-native-executorch"},"_npmVersion":"11.19.0","description":"An easy way to run AI models in React Native with ExecuTorch","directories":{},"maintainers":[{"name":"swm-bot","email":"[email protected]"},{"name":"msluszniak","email":"[email protected]"}],"_nodeVersion":"24.20.0","dependencies":{"zod":"^4.3.6","jsonrepair":"^3.12.0","jsonschema":"^1.5.0","@huggingface/jinja":"^0.5.9","react-native-device-info":"^15.0.2"},"codegenConfig":{"name":"RnExecutorchSpec","type":"modules","android":{"javaPackageName":"com.swmansion.rnexecutorch"},"jsSrcsDir":"src"},"publishConfig":{"registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","react":"19.2.0","del-cli":"^6.0.0","typescript":"~5.9.2","@babel/core":"^7.25.1","@types/jest":"^29.5.14","@types/react":"^19.1.12","react-native":"0.83.6","test-renderer":"^1.2.0","react-native-worklets":"0.10.3","react-native-blob-util":"^0.24.0","react-native-builder-bob":"^0.40.18","@react-native/babel-preset":"0.83.6","@react-native/metro-config":"^0.86.0","@testing-library/react-native":"^14.0.1"},"peerDependencies":{"react":"*","react-native":"*","react-native-worklets":">=0.10.0 <0.13.0","react-native-blob-util":"^0.24.0","@kesha-antonov/react-native-background-downloader":">=4.4.0"},"nativeLibsVersion":"0.10.0","peerDependenciesMeta":{"@kesha-antonov/react-native-background-downloader":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/react-native-executorch_0.10.2_1789155911476_0.3245343785573731","host":"s3://npm-registry-packages-npm-production"},"react-native-builder-bob":{"output":"lib","source":"src","targets":[["module",{"esm":true}],["typescript",{"project":"tsconfig.build.json"}]]},"create-react-native-library":{"type":"turbo-module","tools":[],"version":"0.57.2","languages":"kotlin-objc"},"// === LEGACY SUPPORT: files ===":"!legacy/cpp/**/tests excludes legacy C++ test fixtures and assets from the published tarball (remove when legacy API is dropped)","// === LEGACY SUPPORT: exports ===":"./legacy subpath export is the legacy entrypoint (remove when legacy API is dropped)","// === LEGACY SUPPORT: dependencies ===":"jsonrepair, jsonschema, react-native-device-info, and zod are only needed for legacy API","// === LEGACY SUPPORT: prepare script ===":"tsc -p legacy/tsconfig.json builds legacy type definitions","// === LEGACY SUPPORT: peerDependencies ===":"@kesha-antonov/react-native-background-downloader is only needed for legacy API (remove when legacy is dropped)","_id":"[email protected]","version":"0.10.2"}\ No newline at end of file
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex d0dec5823a..827dcd7501 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -203,6 +203,11 @@ fun Project.rustNativeLib(             environment("AR", "$ndkBin/llvm-ar$exeExt")             environment("SYSROOT", ndkSysroot)             environment(linkerVar, clang)+            // Android 15 requires 16 KB page alignment on arm64 (Play blocks+            // 4 KB .so files). Target-scoped so host build-script links on+            // MSVC are unaffected. See analysis/plan-16kb-page-size.md.+            val rustflagsVar = "CARGO_TARGET_${triple.uppercase().replace('-', '_')}_RUSTFLAGS"+            environment(rustflagsVar, "-C link-arg=-Wl,-z,max-page-size=16384")             // Force the system clang for host-side C on Unix; on Windows let cc locate MinGW gcc.             if (!isWindows) environment("HOST_CC", "/usr/bin/clang")             // Pre-generated bindings (armv8-only): weather's om-file-format-sys no longer uses bindgen
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex 7bc0d9f4eb..aed0520e70 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -15,10 +15,11 @@ android {         applicationId = "com.vayunmathur.camera"     }     androidResources {-        // selfie_segmentation.onnx is read straight out of the APK by SelfieSegmenter, so-        // leave it uncompressed: quantised weights barely deflate, and a compressed asset-        // would have to be inflated into a heap buffer before ORT could open it.-        noCompress += "onnx"+        // The ExecuTorch Vulkan model is staged the same way: ExecutorchSessions+        // copies it out of the APK before Module.load, so it must not be deflated.+        // Quantised weights barely deflate, and a compressed asset would have to+        // be inflated into a heap buffer first.+        noCompress += "pte"     } } 
camera/src/main/assets/README.md
diff --git a/camera/src/main/assets/README.md b/camera/src/main/assets/README.mdindex d2586175c6..a3566055c4 100644--- a/camera/src/main/assets/README.md+++ b/camera/src/main/assets/README.md@@ -16,6 +16,16 @@ Run at 256×256 RGB, rescale 1/255 and **no** mean/std (`do_normalize: false` upstream), output a single 256×256 alpha channel through a sigmoid. Consumed by `SelfieSegmenter` from `BokehAnalyzer` and `PortraitBokeh.StillBokehRenderer`. +## `selfie_segmentation_vulkan_fp16.pte`++ExecuTorch export of the same MediaPipe family for the Vulkan delegate (fp16, ~275 KB):+`forward` takes `[1,3,256,256]` NCHW float32 — the planar buffer `stretchPlanar` already+produces, so there is no CHW→NHWC interleave — and returns `[1,1,256,256]`.+From https://huggingface.co/software-mansion/react-native-executorch-selfie-segmentation+(Apache-2.0; staged under `analysis/et-selfie/`, gitignored). This is the only selfie+runtime: a missing file, an unlinked Vulkan delegate, or a failed run fails closed+(no mask), with no `.tflite` fallback.+ This replaces `erdnet.{param,bin}`, which was added in `72dde80df` with no upstream URL, license or conversion recipe. It was Caffe-derived from nihui's ncnn demo family, had no obtainable ONNX, and so could not be attributed or rebuilt — see
camera/src/main/assets/selfie_segmentation.onnx
diff --git a/camera/src/main/assets/selfie_segmentation.onnx b/camera/src/main/assets/selfie_segmentation.onnxdeleted file mode 100644index f926ab523d..0000000000Binary files a/camera/src/main/assets/selfie_segmentation.onnx and /dev/null differ
camera/src/main/assets/selfie_segmentation_vulkan_fp16.pte
diff --git a/camera/src/main/assets/selfie_segmentation_vulkan_fp16.pte b/camera/src/main/assets/selfie_segmentation_vulkan_fp16.ptenew file mode 100644index 0000000000..3388e451b3Binary files /dev/null and b/camera/src/main/assets/selfie_segmentation_vulkan_fp16.pte differ
emergency/src/main/AndroidManifest.xml
diff --git a/emergency/src/main/AndroidManifest.xml b/emergency/src/main/AndroidManifest.xmlindex 06c3c9724d..ac318713c5 100644--- a/emergency/src/main/AndroidManifest.xml+++ b/emergency/src/main/AndroidManifest.xml@@ -7,10 +7,13 @@       com.vayunmathur.emergency because a Gradle-built app cannot be platform-signed.        Component contract mirrored 1:1 (see C:\Users\Vayun\.llms\plans\maos_emergency_app.plan.md):-      view/edit/medical activities answering the same platform actions, the Settings-      suggestion alias, the ia.emergency injection alias, the search indexables provider,-      the FileProvider for avatar photos, and the gesture provider speaking the-      settingslib EmergencyNumberUtils call() protocol against our own authorities.+      view/edit activities answering the same platform actions (EDIT_EMERGENCY_INFO plus+      the legacy EDIT_MEDICAL_INFO filter on the same editor), the Settings+      suggestion alias, the ia.emergency injection alias, the SystemUI SOS entry alias+      (LAUNCH_EMERGENCY, MANAGE_SENSOR_PRIVACY-guarded like stock), the search+      indexables provider, the FileProvider for avatar photos, and the gesture provider+      speaking the settingslib EmergencyNumberUtils call() protocol against our own+      authorities.        Privileged-only declarations (MANAGE_USERS, WRITE_SECURE_SETTINGS, CALL_PRIVILEGED,       READ_PRIVILEGED_PHONE_STATE) follow the parentalcontrols/screentime precedent: declared@@ -61,6 +64,7 @@     -->     <uses-permission android:name="android.permission.health.READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES" />     <uses-permission android:name="android.permission.health.READ_MEDICAL_DATA_MEDICATIONS" />+    <uses-permission android:name="android.permission.health.READ_MEDICAL_DATA_CONDITIONS" />      <!-- Not requested, deliberately: no INTERNET. Medical info, contacts and the SOS          countdown are all local; the call itself goes through the telephony stack. -->@@ -100,7 +104,10 @@          <!--           Edit entry: contacts + medical info. Answers android.settings.EDIT_EMERGENCY_INFO-          like GrapheneOS's EditInfoActivity.+          like GrapheneOS's EditInfoActivity, and also android.emergency.EDIT_MEDICAL_INFO+          like its EditMedicalInfoActivity: stock splits those across two activities, but+          our editor already covers both, so both filters land here and the legacy action+          keeps resolving.         -->         <activity             android:name=".ui.EditInfoActivity"@@ -114,6 +121,10 @@                 <action android:name="android.settings.EDIT_EMERGENCY_INFO" />                 <category android:name="android.intent.category.DEFAULT" />             </intent-filter>+            <intent-filter>+                <action android:name="android.emergency.EDIT_MEDICAL_INFO" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>         </activity>          <!--@@ -179,20 +190,46 @@         </activity-alias>          <!---          The SOS countdown screen, reached from the power-button gesture via SystemUI.-          Not exported: only the platform gesture path (or our own notification action)-          starts it explicitly. Ignores back press; finishing without cancel hands the-          countdown to the foreground service.+          The SOS countdown screen, reached from the power-button gesture via SystemUI+          (see the SosEntryPoint alias below). Not exported: only the platform gesture+          path (or our own notification action) starts it explicitly. turnScreenOn wakes+          the device when the gesture fires with the screen off; noHistory keeps back+          from returning to the countdown; finishing without cancel hands the countdown+          to the foreground service. All three mirror stock's EmergencyActionActivity.         -->         <activity             android:name=".ui.SosActivity"             android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:directBootAware="true"             android:excludeFromRecents="true"             android:exported="false"             android:launchMode="singleInstance"+            android:noHistory="true"             android:showWhenLocked="true"+            android:turnScreenOn="true"             android:theme="@style/Theme.General" /> +        <!--+          SystemUI entry point for the power-button SOS gesture. Mirrors stock's+          EmergencyAction alias: exported, MANAGE_SENSOR_PRIVACY-guarded, answering+          com.android.systemui.action.LAUNCH_EMERGENCY. SystemUI resolves this action+          with MATCH_SYSTEM_ONLY and prefers config_preferredEmergencySosPackage, which+          MAOS leaves empty, so the first (only) match wins - no SystemUI patch needed.+          The target stays non-exported exactly like stock's EmergencyActionActivity.+        -->+        <activity-alias+            android:name=".ui.SosEntryPoint"+            android:directBootAware="true"+            android:exported="true"+            android:label="@string/sos_title"+            android:permission="android.permission.MANAGE_SENSOR_PRIVACY"+            android:targetActivity=".ui.SosActivity">+            <intent-filter>+                <action android:name="com.android.systemui.action.LAUNCH_EMERGENCY" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+        </activity-alias>+         <!--           SOS countdown service: notification + exact alarm + vibration + warning sound.           Not exported: started explicitly by the SOS screen and the receiver.@@ -202,6 +239,7 @@         -->         <service             android:name=".service.SosCountdownService"+            android:directBootAware="true"             android:exported="false"             android:foregroundServiceType="specialUse">             <property@@ -251,10 +289,16 @@           Gesture state for Settings: number override, gesture/sound toggles, UI-showing           heartbeat. Mirrors GrapheneOS's EmergencyGestureContentProvider call() protocol;           CALL_PRIVILEGED guards it the same way. Query/insert/update/delete throw.+          Both authorities serve the same class/state: ours for the MAOS build (whose+          SettingsLib is rewired to it) and the stock com.android.emergency.gesture for+          unpatched Settings, whose ContentResolver.call() throws IllegalArgumentException+          on an unknown authority and crashes Settings on resume. Safe while stock+          EmergencyInfo is absent (MAOS removes it); a co-installed stock app would+          conflict at install time instead of silently shadowing.         -->         <provider             android:name=".platform.GestureProvider"-            android:authorities="com.vayunmathur.emergency.gesture"+            android:authorities="com.vayunmathur.emergency.gesture;com.android.emergency.gesture"             android:exported="true"             android:permission="android.permission.CALL_PRIVILEGED" /> 
emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.ktindex 458d89e870..e214eb15a4 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt@@ -36,7 +36,7 @@ data class EmergencyContact(     val photo: Bitmap? = null, ) -/** Preference keys. Order matches the fields shown in the view/edit screens. */+/** Preference keys. Order matches the fields shown in the view screen. */ object EmergencyKeys {     const val NAME = "name"     const val ADDRESS = "address"@@ -44,8 +44,7 @@ object EmergencyKeys {     const val ORGAN_DONOR = "organ_donor"     const val CONTACTS = "emergency_contacts" -    val EDIT_ORDER = listOf(ADDRESS, BLOOD_TYPE, ORGAN_DONOR)-    val VIEW_ORDER = EDIT_ORDER+    val VIEW_ORDER = listOf(ADDRESS, BLOOD_TYPE, ORGAN_DONOR) }  /** `|` separator from `EmergencyContactsPreference`; quoted for split. */
emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.ktindex a823a060eb..c7687fa351 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt@@ -48,22 +48,33 @@ class EmergencyRepository private constructor(private val app: Context) {         mutable.value = resolved     } -    suspend fun saveInfo(-        name: String,-        address: String,-        bloodType: String,-        organDonor: String,-    ) = withContext(Dispatchers.IO) {+    /**+     * Snapshots the picked owner identity. Writes only the identity keys so a+     * medical keystroke-save elsewhere can never clobber a just-picked name.+     */+    suspend fun saveOwnerIdentity(name: String, address: String) = withContext(Dispatchers.IO) {         prefs.edit {             putString(EmergencyKeys.NAME, name)             putString(EmergencyKeys.ADDRESS, address)-            putString(EmergencyKeys.BLOOD_TYPE, bloodType)-            putString(EmergencyKeys.ORGAN_DONOR, organDonor)         }         load()         updateSuggestionState()     } +    /**+     * Persists the manually-entered medical fields. Writes only those keys so it+     * can never clobber the picked owner identity.+     */+    suspend fun saveMedicalInfo(bloodType: String, organDonor: String) =+        withContext(Dispatchers.IO) {+            prefs.edit {+                putString(EmergencyKeys.BLOOD_TYPE, bloodType)+                putString(EmergencyKeys.ORGAN_DONOR, organDonor)+            }+            load()+            updateSuggestionState()+        }+     /** Adds a contact URI after validating it still resolves; returns false when rejected. */     suspend fun addContact(phoneUri: Uri): Boolean = withContext(Dispatchers.IO) {         val reader = ContactReader(app)
emergency/src/main/java/com/vayunmathur/emergency/data/ImportedMedical.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/data/ImportedMedical.kt b/emergency/src/main/java/com/vayunmathur/emergency/data/ImportedMedical.ktindex 2de2766d07..43dc434816 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/data/ImportedMedical.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/ImportedMedical.kt@@ -18,5 +18,10 @@ data class ImportedMedication(     val displayName: String, ) +/** A single active condition read from Health Connect. Read-only, like [ImportedAllergy]. */+data class ImportedCondition(+    val displayName: String,+)+ /** How dangerous a reaction is, mirroring FHIR `AllergyIntolerance.criticality`. */ enum class AllergyCriticality { High, Low, Unknown }
emergency/src/main/java/com/vayunmathur/emergency/domain/FhirMedicalParse.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/domain/FhirMedicalParse.kt b/emergency/src/main/java/com/vayunmathur/emergency/domain/FhirMedicalParse.ktindex 4dd43121de..6de314840a 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/domain/FhirMedicalParse.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/domain/FhirMedicalParse.kt@@ -2,6 +2,7 @@ package com.vayunmathur.emergency.domain  import com.vayunmathur.emergency.data.AllergyCriticality import com.vayunmathur.emergency.data.ImportedAllergy+import com.vayunmathur.emergency.data.ImportedCondition import com.vayunmathur.emergency.data.ImportedMedication import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray@@ -84,6 +85,23 @@ object FhirMedicalParse {             }         } +    /**+     * One active condition, or null when the resource is not a condition, has no usable+     * name, or is resolved/inactive.+     *+     * Mirrors the health app's status gate (resolved/inactive drop out, everything else+     * stays): an emergency card should show what the patient has now, not history.+     */+    fun parseCondition(data: String): ImportedCondition? {+        val root = parse(data) ?: return null+        if (root.str("resourceType") != "Condition") return null+        if (!isActive(root["clinicalStatus"] as? JsonObject)) return null++        val code = root["code"] as? JsonObject+        val displayName = displayFrom(code) ?: return null+        return ImportedCondition(displayName = displayName)+    }+     // --- helpers -------------------------------------------------------------      private fun parse(data: String): JsonObject? =
emergency/src/main/java/com/vayunmathur/emergency/domain/OwnerPostalFormat.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/domain/OwnerPostalFormat.kt b/emergency/src/main/java/com/vayunmathur/emergency/domain/OwnerPostalFormat.ktnew file mode 100644index 0000000000..ec9196e08b--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/domain/OwnerPostalFormat.kt@@ -0,0 +1,19 @@+package com.vayunmathur.emergency.domain++/**+ * Formats a postal address from its components when the provider has no+ * preformatted address (`FORMATTED_ADDRESS` blank).+ *+ * Mirrors the fallback in the contacts app's `getDetailsInternal`: joins the+ * non-blank components with `", "`. Pure logic (no Android dependency) so it+ * can carry a plain unit test.+ */+fun formatPostalFallback(+    street: String?,+    city: String?,+    region: String?,+    postcode: String?,+    country: String?,+): String = listOfNotNull(street, city, region, postcode, country)+    .filter { it.isNotBlank() }+    .joinToString(", ")
emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.ktindex ac88ae4076..a8fd17150e 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt@@ -4,6 +4,7 @@ import android.net.Uri import com.vayunmathur.emergency.data.EmergencyContact import com.vayunmathur.emergency.data.EmergencyInfo import com.vayunmathur.emergency.data.ImportedAllergy+import com.vayunmathur.emergency.data.ImportedCondition import com.vayunmathur.emergency.data.ImportedMedication  /**@@ -26,6 +27,7 @@ data class HealthConnectMedicalState(     val granted: Boolean = false,     val allergies: List<ImportedAllergy> = emptyList(),     val medications: List<ImportedMedication> = emptyList(),+    val conditions: List<ImportedCondition> = emptyList(), )  /** Everything the view/edit screens draw. */@@ -39,16 +41,40 @@ data class EmergencyUiState(     val addFailed: Boolean = false,     /** Allergies and current medications from Health Connect, when available and granted. */     val health: HealthConnectMedicalState = HealthConnectMedicalState(),+    /** Pending owner pick with several addresses; null except while choosing. */+    val ownerCandidates: OwnerPickCandidates? = null,+    /** Last owner-pick failure, for a one-shot message; false when none. */+    val ownerPickFailed: Boolean = false,+)++/**+ * A picked owner whose contact has several postal addresses: the name is fixed+ * and the user must choose which address to snapshot.+ */+data class OwnerPickCandidates(+    val name: String,+    val addresses: List<String>, )  interface EmergencyActions {-    /** Persists the manually-entered identity fields (allergies/medications come from HC). */-    fun saveInfo(-        name: String,-        address: String,-        bloodType: String,-        organDonor: String,-    ) {}+    /** Persists the manually-entered medical fields (identity comes from a pick). */+    fun saveMedicalInfo(bloodType: String, organDonor: String) {}++    /**+     * Snapshots the picked owner contact's identity; opens the address chooser+     * when several addresses are available, saves directly otherwise. Sets+     * [EmergencyUiState.ownerPickFailed] when the contact cannot be read.+     */+    fun pickOwner(contactUri: Uri) {}++    /** Saves the picked name with the chosen address and closes the chooser. */+    fun confirmOwnerAddress(address: String) {}++    /** Closes the address chooser without saving. */+    fun dismissOwnerPick() {}++    /** Clears the one-shot owner-pick failure flag after it has been shown. */+    fun clearOwnerPickFailed() {}      /** Adds the picked contact URI; sets [EmergencyUiState.addFailed] when rejected. */     fun addContact(phoneUri: Uri) {}@@ -114,4 +140,8 @@ fun sampleHealthConnect(): HealthConnectMedicalState = HealthConnectMedicalState         ImportedMedication("Salbutamol 100mcg inhaler"),         ImportedMedication("Lisinopril 10mg"),     ),+    conditions = listOf(+        ImportedCondition("Asthma"),+        ImportedCondition("Hypertension"),+    ), )
emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyViewModel.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyViewModel.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyViewModel.ktindex 2bfeccea1b..6d85818983 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyViewModel.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyViewModel.kt@@ -23,6 +23,8 @@ class EmergencyViewModel(app: Application) : AndroidViewModel(app), EmergencyAct     private val hasContactsAccess = MutableStateFlow(false)     private val addFailed = MutableStateFlow(false)     private val health = MutableStateFlow(HealthConnectMedicalState())+    private val ownerCandidates = MutableStateFlow<OwnerPickCandidates?>(null)+    private val ownerPickFailed = MutableStateFlow(false)      val state: StateFlow<EmergencyUiState> = combine(         repository.info,@@ -30,6 +32,8 @@ class EmergencyViewModel(app: Application) : AndroidViewModel(app), EmergencyAct         hasContactsAccess,         addFailed,         health,+        ownerCandidates,+        ownerPickFailed,     ) { flows ->         @Suppress("UNCHECKED_CAST")         val info = flows[0] as com.vayunmathur.emergency.data.EmergencyInfo@@ -39,6 +43,8 @@ class EmergencyViewModel(app: Application) : AndroidViewModel(app), EmergencyAct             hasContactsAccess = flows[2] as Boolean,             addFailed = flows[3] as Boolean,             health = flows[4] as HealthConnectMedicalState,+            ownerCandidates = flows[5] as OwnerPickCandidates?,+            ownerPickFailed = flows[6] as Boolean,         )     }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), EmergencyUiState()) @@ -72,21 +78,51 @@ class EmergencyViewModel(app: Application) : AndroidViewModel(app), EmergencyAct                 granted = true,                 allergies = healthConnect.readAllergies(),                 medications = healthConnect.readCurrentMedications(),+                conditions = healthConnect.readConditions(),             )         }     } -    override fun saveInfo(-        name: String,-        address: String,-        bloodType: String,-        organDonor: String,-    ) {+    override fun saveMedicalInfo(bloodType: String, organDonor: String) {         viewModelScope.launch {-            repository.saveInfo(name, address, bloodType, organDonor)+            repository.saveMedicalInfo(bloodType, organDonor)         }     } +    override fun pickOwner(contactUri: Uri) {+        viewModelScope.launch(Dispatchers.IO) {+            val identity = OwnerIdentityReader(getApplication()).read(contactUri)+            if (identity == null || identity.name.isBlank()) {+                ownerPickFailed.value = true+                return@launch+            }+            when {+                identity.addresses.isEmpty() ->+                    repository.saveOwnerIdentity(identity.name, "")+                identity.addresses.size == 1 ->+                    repository.saveOwnerIdentity(identity.name, identity.addresses[0])+                else -> ownerCandidates.value =+                    OwnerPickCandidates(identity.name, identity.addresses)+            }+        }+    }++    override fun confirmOwnerAddress(address: String) {+        val candidates = ownerCandidates.value ?: return+        ownerCandidates.value = null+        viewModelScope.launch {+            repository.saveOwnerIdentity(candidates.name, address)+        }+    }++    override fun dismissOwnerPick() {+        ownerCandidates.value = null+    }++    override fun clearOwnerPickFailed() {+        ownerPickFailed.value = false+    }+     override fun addContact(phoneUri: Uri) {         viewModelScope.launch(Dispatchers.IO) {             addFailed.value = !repository.addContact(phoneUri)
emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.ktindex e8ac61fbed..3613136f35 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt@@ -47,6 +47,14 @@ class GestureProvider : ContentProvider() {                 prefs().edit()                     .putString(EXTRA_CALL_NUMBER, extras?.getString(EXTRA_CALL_NUMBER))                     .apply()+                // Stock notifies observers of the gesture authority URI here; Settings+                // registers a content observer on it, so without this the override row+                // never refreshes after a set. Both authorities served in the manifest,+                // so both get the notification.+                runCatching {+                    requireContext().contentResolver.notifyChange(STOCK_GESTURE_URI, null)+                    requireContext().contentResolver.notifyChange(GESTURE_URI, null)+                }             }             METHOD_SET_GESTURE -> {                 if (!writeSecure(SecureKeys.GESTURE_ENABLED, extras, EXTRA_VALUE)) {@@ -173,6 +181,18 @@ class GestureProvider : ContentProvider() {     companion object {         private const val OVERRIDE_PREFS = "local_emergency_number_override_shared_pref" +        /** Our gesture authority, for the notifyChange stock sends on override sets. */+        private val GESTURE_URI: Uri = Uri.Builder()+            .scheme("content")+            .authority("com.vayunmathur.emergency.gesture")+            .build()++        /** Stock gesture authority served by the same provider (see manifest). */+        private val STOCK_GESTURE_URI: Uri = Uri.Builder()+            .scheme("content")+            .authority("com.android.emergency.gesture")+            .build()+         /**          * `Settings.Secure` gesture keys as literals: they are `@hide`/system-API in the          * framework (`Settings.Secure.EMERGENCY_GESTURE_*`), so a Gradle app cannot reference
emergency/src/main/java/com/vayunmathur/emergency/platform/HealthConnectMedical.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/HealthConnectMedical.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/HealthConnectMedical.ktindex 02631cc5aa..969b37013c 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/platform/HealthConnectMedical.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/HealthConnectMedical.kt@@ -11,6 +11,7 @@ import androidx.health.connect.client.records.MedicalResource import androidx.health.connect.client.request.ReadMedicalResourcesInitialRequest import androidx.health.connect.client.request.ReadMedicalResourcesPageRequest import com.vayunmathur.emergency.data.ImportedAllergy+import com.vayunmathur.emergency.data.ImportedCondition import com.vayunmathur.emergency.data.ImportedMedication import com.vayunmathur.emergency.domain.FhirMedicalParse @@ -80,6 +81,12 @@ class HealthConnectMedical(context: Context) {             .mapNotNull { FhirMedicalParse.parseCurrentMedication(it) }             .distinctBy { it.displayName } +    /** Active conditions; empty when unavailable, denied, or none recorded. */+    suspend fun readConditions(): List<ImportedCondition> =+        readCategory(MedicalResource.MEDICAL_RESOURCE_TYPE_CONDITIONS)+            .mapNotNull { FhirMedicalParse.parseCondition(it) }+            .distinctBy { it.displayName }+     /** Every FHIR resource of [medicalResourceType] as raw JSON, paging until exhausted. */     private suspend fun readCategory(medicalResourceType: Int): List<String> {         if (!isAvailable()) return emptyList()@@ -110,6 +117,7 @@ class HealthConnectMedical(context: Context) {         val PERMISSIONS = setOf(             HealthPermission.PERMISSION_READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES,             HealthPermission.PERMISSION_READ_MEDICAL_DATA_MEDICATIONS,+            HealthPermission.PERMISSION_READ_MEDICAL_DATA_CONDITIONS,         )          private const val PAGE_SIZE = 500
emergency/src/main/java/com/vayunmathur/emergency/platform/OwnerIdentityReader.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/OwnerIdentityReader.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/OwnerIdentityReader.ktnew file mode 100644index 0000000000..36bba04537--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/OwnerIdentityReader.kt@@ -0,0 +1,143 @@+package com.vayunmathur.emergency.platform++import android.content.ContentUris+import android.content.Context+import android.net.Uri+import android.provider.ContactsContract+import android.util.Log+import com.vayunmathur.emergency.domain.formatPostalFallback++private const val TAG = "OwnerIdentityReader"++private typealias CDKPostal = ContactsContract.CommonDataKinds.StructuredPostal++/** The owner's picked identity: display name plus any postal addresses. */+data class OwnerIdentity(+    val name: String,+    val addresses: List<String> = emptyList(),+)++/**+ * Reads the owner's identity from a whole-contact pick result.+ *+ * Our contacts app answers a contact pick with a per-raw-contact URI+ * (`RawContacts.CONTENT_URI/<rawId>`, see `ContactItemPick`); aggregate contact+ * and lookup URIs are resolved defensively to the same shape. The name comes+ * from `DISPLAY_NAME_PRIMARY` and addresses from the contact's `StructuredPostal`+ * rows (`FORMATTED_ADDRESS`, falling back to the joined components exactly like+ * the contacts app's `getDetailsInternal`). Needs `READ_CONTACTS`; without it+ * every read returns null and the UI must prompt.+ */+class OwnerIdentityReader(private val context: Context) {++    /** Reads the identity, or null when the URI does not resolve or access is denied. */+    fun read(contactUri: Uri): OwnerIdentity? {+        val rawId = rawContactId(contactUri) ?: return null+        val name = readDisplayName(rawId) ?: return null+        if (name.isBlank()) return null+        return OwnerIdentity(name, readAddresses(rawId))+    }++    private fun rawContactId(contactUri: Uri): Long? {+        val segments = contactUri.pathSegments+        // Raw-contact URI from our picker: content://.../raw_contacts/<rawId>.+        if (segments.size >= 2 && segments[0] == ContactsContract.RawContacts.CONTENT_URI.lastPathSegment) {+            return contactUri.lastPathSegment?.toLongOrNull()+        }+        // Aggregate contact URI: content://.../contacts/<id> or .../contacts/lookup/<key>/<id>.+        val contactId = aggregateContactId(contactUri) ?: return null+        return firstRawContactId(contactId)+    }++    private fun aggregateContactId(contactUri: Uri): Long? {+        if (contactUri.path?.contains("/lookup/") == true) {+            return runCatching {+                ContactsContract.Contacts.lookupContact(context.contentResolver, contactUri)+                    ?.let { ContentUris.parseId(it) }+            }.getOrNull()+        }+        return contactUri.lastPathSegment?.toLongOrNull()+    }++    private fun firstRawContactId(contactId: Long): Long? {+        val cursor = runCatching {+            context.contentResolver.query(+                ContactsContract.RawContacts.CONTENT_URI,+                arrayOf(ContactsContract.RawContacts._ID),+                "${ContactsContract.RawContacts.CONTACT_ID} = ? AND " ++                    "${ContactsContract.RawContacts.DELETED} = 0",+                arrayOf(contactId.toString()),+                "${ContactsContract.RawContacts.STARRED} DESC, ${ContactsContract.RawContacts._ID} ASC",+            )+        }.getOrElse {+            Log.w(TAG, "unable to resolve raw contact for $contactId", it)+            return null+        } ?: return null+        cursor.use {+            if (!it.moveToFirst()) return null+            return it.getLong(0)+        }+    }++    private fun readDisplayName(rawId: Long): String? {+        val uri = ContentUris.withAppendedId(+            ContactsContract.RawContacts.CONTENT_URI, rawId,+        )+        val cursor = runCatching {+            context.contentResolver.query(+                uri,+                arrayOf(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY),+                null, null, null,+            )+        }.getOrElse {+            Log.w(TAG, "unable to read display name for raw contact $rawId", it)+            return null+        } ?: return null+        cursor.use {+            if (!it.moveToNext()) return null+            return it.getString(0).orEmpty()+        }+    }++    private fun readAddresses(rawId: Long): List<String> {+        val cursor = runCatching {+            context.contentResolver.query(+                ContactsContract.Data.CONTENT_URI,+                arrayOf(+                    CDKPostal.FORMATTED_ADDRESS,+                    CDKPostal.STREET,+                    CDKPostal.CITY,+                    CDKPostal.REGION,+                    CDKPostal.POSTCODE,+                    CDKPostal.COUNTRY,+                ),+                "${ContactsContract.Data.RAW_CONTACT_ID} = ? AND " ++                    "${ContactsContract.Data.MIMETYPE} = ?",+                arrayOf(rawId.toString(), CDKPostal.CONTENT_ITEM_TYPE),+                null,+            )+        }.getOrElse {+            Log.w(TAG, "unable to read addresses for raw contact $rawId", it)+            return emptyList()+        } ?: return emptyList()+        cursor.use {+            val addresses = mutableListOf<String>()+            while (it.moveToNext()) {+                val formatted = it.getString(0)+                val address = if (!formatted.isNullOrBlank()) {+                    formatted+                } else {+                    formatPostalFallback(+                        street = it.getString(1),+                        city = it.getString(2),+                        region = it.getString(3),+                        postcode = it.getString(4),+                        country = it.getString(5),+                    )+                }+                if (address.isNotBlank()) addresses += address+            }+            return addresses.distinct()+        }+    }+}
emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.ktindex 9c572658e3..0270a6e319 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt@@ -8,8 +8,8 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge-import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable@@ -38,13 +38,16 @@ import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior  /**- * Edits the owner's identity details and emergency contacts.+ * Edits the owner's medical details and emergency contacts.  *  * Answers `android.settings.EDIT_EMERGENCY_INFO` like GrapheneOS's EditInfoActivity.- * Contacts are picked with `ACTION_PICK` against `Phone.CONTENT_URI` so the stored value is- * the per-number URI GrapheneOS persists (not the aggregate contact URI). Adding requires- * `READ_CONTACTS`, requested here. Allergies and medications are never typed here - they are- * read from Health Connect, which this screen only offers to connect.+ * The owner's identity (name, and address when available) is picked from a contact+ * card with `ACTION_PICK` against `Contacts.CONTENT_URI` and snapshotted into+ * storage — never typed here. Emergency contacts are picked separately with+ * `ACTION_PICK` against `Phone.CONTENT_URI` so the stored value is the per-number+ * URI GrapheneOS persists (not the aggregate contact URI). Picking requires+ * `READ_CONTACTS`, requested here. Allergies and medications are never typed here -+ * they are read from Health Connect, which this screen only offers to connect.  */ class EditInfoActivity : ComponentActivity() { @@ -75,6 +78,11 @@ private fun EditInfoPage(viewModel: EmergencyViewModel) {     ) { result ->         result.data?.data?.let { viewModel.addContact(it) }     }+    val pickOwner = rememberLauncherForActivityResult(+        ActivityResultContracts.StartActivityForResult(),+    ) { result ->+        result.data?.data?.let { viewModel.pickOwner(it) }+    }     val requestContacts = rememberLauncherForActivityResult(         ActivityResultContracts.RequestPermission(),     ) { granted ->@@ -86,41 +94,55 @@ private fun EditInfoPage(viewModel: EmergencyViewModel) {         PermissionController.createRequestPermissionResultContract(),     ) { viewModel.refreshHealthConnect() } +    val gatePick = { open: () -> Unit ->+        if (state.hasContactsAccess) {+            open()+        } else {+            requestContacts.launch(Manifest.permission.READ_CONTACTS)+        }+    }     EditInfoScreen(         state = state,         actions = viewModel,         onPickContact = {-            if (state.hasContactsAccess) {+            gatePick {                 pickContact.launch(                     Intent(                         Intent.ACTION_PICK,                         ContactsContract.CommonDataKinds.Phone.CONTENT_URI,                     ),                 )-            } else {-                requestContacts.launch(Manifest.permission.READ_CONTACTS)+            }+        },+        onPickOwner = {+            gatePick {+                pickOwner.launch(+                    Intent(+                        Intent.ACTION_PICK,+                        ContactsContract.Contacts.CONTENT_URI,+                    ),+                )             }         },         onConnectHealth = { requestHealth.launch(HealthConnectMedical.PERMISSIONS) },     ) } -/** The editor: identity fields, a Health Connect connect prompt, and contacts add/remove. */+/** The editor: picked identity, medical fields, a Health Connect prompt, contacts add/remove. */ @Composable fun EditInfoScreen(     state: EmergencyUiState,     actions: EmergencyActions,     onPickContact: () -> Unit,+    onPickOwner: () -> Unit = {},     onConnectHealth: () -> Unit = {}, ) {     // Local copies so typing does not wait for a repository round-trip; saved on each keystroke     // (SharedPreferences writes are cheap) so leaving mid-edit loses nothing.-    var name by remember(state.info.name) { mutableStateOf(state.info.name) }-    var address by remember(state.info.address) { mutableStateOf(state.info.address) }     var bloodType by remember(state.info.bloodType) { mutableStateOf(state.info.bloodType) }     var organDonor by remember(state.info.organDonor) { mutableStateOf(state.info.organDonor) }     val save = {-        actions.saveInfo(name, address, bloodType, organDonor)+        actions.saveMedicalInfo(bloodType, organDonor)     }      LazyListScaffold(@@ -129,18 +151,32 @@ fun EditInfoScreen(         scrollBehavior = appBarScrollBehavior(),     ) {         item {-            EditField(-                label = stringResource(R.string.field_name),-                value = name,-                onChange = { name = it; save() },-            )-        }-        item {-            EditField(-                label = stringResource(R.string.field_address),-                value = address,-                onChange = { address = it; save() },-            )+            SettingsSection(title = stringResource(R.string.section_owner_identity)) {+                val name = state.info.name+                if (name.isBlank()) {+                    SettingsRow(+                        title = stringResource(R.string.owner_identity_empty),+                        onClick = onPickOwner,+                    )+                } else {+                    val address = state.info.address+                    SettingsRow(+                        title = name,+                        supportingText = address.ifBlank { null },+                        onClick = onPickOwner,+                    )+                }+                SettingsRow(+                    title = stringResource(R.string.choose_owner_contact),+                    onClick = onPickOwner,+                )+                if (state.ownerPickFailed) {+                    SettingsRow(+                        title = stringResource(R.string.fail_pick_owner),+                        onClick = actions::clearOwnerPickFailed,+                    )+                }+            }         }         item {             EditField(@@ -215,9 +251,19 @@ fun EditInfoScreen(             }         }     }++    val candidates = state.ownerCandidates+    if (candidates != null) {+        OwnerAddressDialog(+            name = candidates.name,+            addresses = candidates.addresses,+            onConfirm = actions::confirmOwnerAddress,+            onDismiss = actions::dismissOwnerPick,+        )+    } } -/** One identity field: a titled section holding a single text field. */+/** One medical field: a titled section holding a single text field. */ @Composable private fun EditField(label: String, value: String, onChange: (String) -> Unit) {     FormSection(title = label) {
emergency/src/main/java/com/vayunmathur/emergency/ui/OwnerAddressDialog.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/OwnerAddressDialog.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/OwnerAddressDialog.ktnew file mode 100644index 0000000000..1e660a6fbb--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/OwnerAddressDialog.kt@@ -0,0 +1,45 @@+package com.vayunmathur.emergency.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.emergency.R+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * Chooses which of a picked contact's postal addresses to save as the owner's+ * address. Shown only when the contact has several; zero or one address saves+ * without asking.+ */+@Composable+fun OwnerAddressDialog(+    name: String,+    addresses: List<String>,+    onConfirm: (String) -> Unit,+    onDismiss: () -> Unit,+) {+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text(stringResource(R.string.owner_address_chooser_title, name)) },+        text = {+            LazyColumn {+                items(addresses, key = { it }) { address ->+                    ListItem(+                        headlineContent = { Text(address) },+                        modifier = Modifier.clickable { onConfirm(address) },+                    )+                }+            }+        },+        confirmButton = { },+        dismissButton = {+            TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }+        },+    )+}
emergency/src/main/java/com/vayunmathur/emergency/ui/ViewInfoScreen.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/ui/ViewInfoScreen.kt b/emergency/src/main/java/com/vayunmathur/emergency/ui/ViewInfoScreen.ktindex 3b8ac03e60..c4eec91a71 100644--- a/emergency/src/main/java/com/vayunmathur/emergency/ui/ViewInfoScreen.kt+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/ViewInfoScreen.kt@@ -1,17 +1,23 @@ package com.vayunmathur.emergency.ui -import android.content.Intent import android.os.Bundle import android.os.UserManager-import android.provider.Settings import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyListScope+import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue-import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.emergency.R@@ -20,20 +26,22 @@ import com.vayunmathur.emergency.data.EmergencyInfo import com.vayunmathur.emergency.data.EmergencyKeys import com.vayunmathur.emergency.platform.EmergencyUiState import com.vayunmathur.emergency.platform.EmergencyViewModel+import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.LazyListScaffold-import com.vayunmathur.library.ui.SettingsRow-import com.vayunmathur.library.ui.SettingsSection import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.verticalShape  /**  * Read-only emergency info, reachable over the lock screen.  *  * Answers `android.telephony.action.EMERGENCY_ASSISTANCE` like GrapheneOS's  * ViewInfoActivity: the owner's medical details and emergency contacts for a first- * responder, with an edit entry hidden until setup is complete (same gate as the- * original's options-menu check on `USER_SETUP_COMPLETE`).+ * responder. Editing lives only in Settings (the ia.emergency injection) - there is+ * deliberately no edit entry here and no top bar: a responder reads this under stress,+ * so the content starts at the top and every datum is a large centered segment in a+ * labelled group. Groups use [verticalShape] so each reads as one block.  */ class ViewInfoActivity : ComponentActivity() { @@ -48,8 +56,6 @@ class ViewInfoActivity : ComponentActivity() {                 ViewInfoScreen(                     state = state,                     ownerName = ownerName(),-                    showEdit = isSetupComplete(),-                    onEdit = { startActivity(Intent(this, EditInfoActivity::class.java)) },                 )             }         }@@ -63,11 +69,6 @@ class ViewInfoActivity : ComponentActivity() {     private fun ownerName(): String =         runCatching { getSystemService(UserManager::class.java)?.userName.orEmpty() }             .getOrDefault("")--    private fun isSetupComplete(): Boolean =-        runCatching {-            Settings.Secure.getInt(contentResolver, "user_setup_complete", 0) == 1-        }.getOrDefault(true) }  /** The read-only info + contacts view. Stateless; the activity wires the ViewModel. */@@ -75,128 +76,149 @@ class ViewInfoActivity : ComponentActivity() { fun ViewInfoScreen(     state: EmergencyUiState,     ownerName: String,-    showEdit: Boolean,-    onEdit: () -> Unit, ) {+    // Resolved up front: the LazyListScope content below is not itself @Composable,+    // so stringResource() calls must happen here or inside item {} blocks.+    val ownerLabel = stringResource(R.string.group_owner)+    val contactLabel = stringResource(R.string.group_emergency_contact)+    val allergiesLabel = stringResource(R.string.section_allergies)+    val conditionsLabel = stringResource(R.string.section_conditions)+    val medicationsLabel = stringResource(R.string.section_current_medications)+    val ownerRows = ownerRows(state.info, ownerName)     LazyListScaffold(-        title = stringResource(R.string.app_name),-        horizontalPadding = 0.dp,+        // No title and no actions: the scaffold draws no bar, so the content starts+        // at the top. scrollBehavior is still required for the nested-scroll wiring.         scrollBehavior = appBarScrollBehavior(),     ) {-        if (ownerName.isNotBlank()) {+        if (state.loading) {             item {-                SettingsSection {-                    SettingsRow(title = ownerName)-                }+                Segment(value = stringResource(R.string.contacts_loading), index = 0, count = 1)             }-        }--        item {-            SettingsSection(title = stringResource(R.string.tab_title_info)) {-                if (state.loading) {-                    SettingsRow(title = stringResource(R.string.contacts_loading))+        } else if (ownerRows.isEmpty() && state.info.contacts.isEmpty() &&+            state.health.allergies.isEmpty() && state.health.conditions.isEmpty() &&+            state.health.medications.isEmpty()+        ) {+            item {+                Segment(value = stringResource(R.string.no_info), index = 0, count = 1)+            }+        } else {+            if (ownerRows.isNotEmpty()) {+                group(ownerLabel, ownerRows)+            }+            for ((contactIndex, contact) in state.info.contacts.withIndex()) {+                val name = contact.displayName.ifBlank { contact.phoneNumber }+                val detail = if (contact.phoneType.isBlank()) {+                    contact.phoneNumber                 } else {-                    val rows = infoRows(state.info)-                    if (rows.isEmpty()) {-                        SettingsRow(title = stringResource(R.string.no_info))-                    } else {-                        // Value front and centre (title), label small underneath (supporting).-                        for ((label, value) in rows) {-                            SettingsRow(title = value, supportingText = label)-                        }-                    }+                    "${contact.phoneType} · ${contact.phoneNumber}"                 }-            }-        }--        item {-            SettingsSection(title = stringResource(R.string.tab_title_contacts)) {-                if (!state.loading && state.info.contacts.isEmpty()) {-                    SettingsRow(title = stringResource(R.string.no_info))+                val title = if (state.info.contacts.size == 1) {+                    contactLabel+                } else {+                    "$contactLabel ${contactIndex + 1}"                 }+                group(title, listOf(name to null, detail to null))             }-        }--        for (contact in state.info.contacts) {-            item(key = contact.phoneUri.toString()) {-                val context = LocalContext.current-                SettingsRow(-                    title = contact.displayName.ifBlank { contact.phoneNumber },-                    supportingText = contactSubtitle(contact.phoneType, contact.phoneNumber),-                    onClick = {-                        runCatching {-                            context.startActivity(Intent(Intent.ACTION_VIEW, contact.phoneUri))-                        }-                    },-                )-            }-        }--        if (state.health.allergies.isNotEmpty()) {-            item {-                SettingsSection(title = stringResource(R.string.section_allergies)) {-                    for (allergy in state.health.allergies) {+            if (state.health.allergies.isNotEmpty()) {+                group(+                    allergiesLabel,+                    state.health.allergies.map { allergy ->                         val severity = when (allergy.criticality) {                             AllergyCriticality.High -> stringResource(R.string.allergy_high)                             AllergyCriticality.Low -> stringResource(R.string.allergy_low)                             AllergyCriticality.Unknown -> null                         }-                        SettingsRow(-                            title = allergy.displayName,-                            supportingText = allergy.reaction,-                            trailingContent = severity?.let { { Text(it) } },-                        )-                    }-                    SettingsRow(title = stringResource(R.string.from_health_connect))-                }+                        allergy.displayName to listOfNotNull(allergy.reaction, severity)+                            .joinToString(" · ").ifBlank { null }+                    },+                )             }-        }--        if (state.health.medications.isNotEmpty()) {-            item {-                SettingsSection(title = stringResource(R.string.section_current_medications)) {-                    for (medication in state.health.medications) {-                        SettingsRow(title = medication.displayName)-                    }-                    SettingsRow(title = stringResource(R.string.from_health_connect))-                }+            if (state.health.conditions.isNotEmpty()) {+                group(+                    conditionsLabel,+                    state.health.conditions.map { it.displayName to null },+                )+            }+            if (state.health.medications.isNotEmpty()) {+                group(+                    medicationsLabel,+                    state.health.medications.map { it.displayName to null },+                )             }         }+    }+} -        if (showEdit && !state.loading) {-            item {-                SettingsSection {-                    SettingsRow(-                        title = stringResource(R.string.edit_info),-                        onClick = onEdit,-                    )-                }-            }+/**+ * One labelled group of segments: a small heading plus each value as a joined block.+ * Each entry is a value with an optional detail line underneath.+ */+private fun LazyListScope.group(title: String, rows: List<Pair<String, String?>>) {+    item(key = "header-$title") {+        Text(+            text = title,+            modifier = Modifier+                .fillMaxWidth()+                .padding(horizontal = 20.dp)+                .padding(top = 16.dp, bottom = 4.dp),+            textAlign = TextAlign.Center,+            style = MaterialTheme.typography.titleMedium,+        )+    }+    rows.forEachIndexed { index, (value, detail) ->+        item(key = "$title-$index-$value") {+            Segment(value = value, detail = detail, index = index, count = rows.size)         }     } } -/** Non-empty identity rows in view order, each as a label to its display value. */+/**+ * One datum as a full-width segment of its group: the value large and centered, an+ * optional detail smaller beneath it. Outer corners rounded, inner joins square, so+ * the group reads as one block.+ */ @Composable-private fun infoRows(info: EmergencyInfo): List<Pair<String, String>> {-    val labels = mapOf(-        EmergencyKeys.NAME to stringResource(R.string.field_name),-        EmergencyKeys.ADDRESS to stringResource(R.string.field_address),-        EmergencyKeys.BLOOD_TYPE to stringResource(R.string.field_blood_type),-        EmergencyKeys.ORGAN_DONOR to stringResource(R.string.field_organ_donor),-    )-    val values = mapOf(-        EmergencyKeys.NAME to info.name,-        EmergencyKeys.ADDRESS to info.address,-        EmergencyKeys.BLOOD_TYPE to info.bloodType,-        EmergencyKeys.ORGAN_DONOR to info.organDonor,-    )-    // Name first, then the rest in view order.-    return (listOf(EmergencyKeys.NAME) + EmergencyKeys.VIEW_ORDER).mapNotNull { key ->-        val value = values[key].orEmpty()-        if (value.isBlank()) null else (labels[key].orEmpty() to value)+private fun Segment(value: String, detail: String? = null, index: Int, count: Int) {+    Card(+        modifier = Modifier+            .fillMaxWidth()+            .padding(horizontal = 16.dp, vertical = 1.dp),+        shape = verticalShape(index, count),+    ) {+        Column(+            modifier = Modifier+                .fillMaxWidth()+                .padding(horizontal = 20.dp, vertical = 12.dp),+            verticalArrangement = Arrangement.spacedBy(4.dp),+            horizontalAlignment = Alignment.CenterHorizontally,+        ) {+            Text(+                text = value,+                textAlign = TextAlign.Center,+                style = MaterialTheme.typography.headlineSmall,+            )+            if (detail != null) {+                Text(+                    text = detail,+                    textAlign = TextAlign.Center,+                    style = MaterialTheme.typography.titleMedium,+                )+            }+        }     } } -private fun contactSubtitle(type: String, number: String): String =-    if (type.isBlank()) number else "$type · $number"+/**+ * Owner group rows: lock-screen owner name first, then stored name/address when set.+ * Blood type / organ donor stay out: those live on the medical side, not the identity.+ */+@Composable+private fun ownerRows(info: EmergencyInfo, ownerName: String): List<Pair<String, String?>> {+    val rows = mutableListOf<Pair<String, String?>>()+    if (ownerName.isNotBlank()) rows += ownerName to null+    val nameLabel = stringResource(R.string.field_name)+    if (info.name.isNotBlank() && info.name != ownerName) rows += info.name to nameLabel+    val addressLabel = stringResource(R.string.field_address)+    if (info.address.isNotBlank()) rows += info.address to addressLabel+    return rows+}
emergency/src/main/res/values/strings.xml
diff --git a/emergency/src/main/res/values/strings.xml b/emergency/src/main/res/values/strings.xmlindex 635b0803c4..90888ad91e 100644--- a/emergency/src/main/res/values/strings.xml+++ b/emergency/src/main/res/values/strings.xml@@ -14,15 +14,33 @@     <string name="tab_title_info">Info</string>     <!-- View screen: tab showing the emergency contacts. Noun. -->     <string name="tab_title_contacts">Contacts</string>+    <!-- View screen: heading above the owner's name and address cards. Noun. -->+    <string name="group_owner">Owner</string>+    <!-- View screen: heading above each emergency contact's name and number cards. Noun phrase. -->+    <string name="group_emergency_contact">Emergency Contact</string>+    <!-- View screen: heading above the allergies group. Noun. -->+    <string name="section_allergies">Allergies</string>+    <!-- View screen: heading above the conditions group. Noun. -->+    <string name="section_conditions">Conditions</string>+    <!-- View screen: heading above the medications group. Noun. -->+    <string name="section_medications">Medications</string>     <!-- View screen: shown when neither medical info nor contacts are set. -->     <string name="no_info">No emergency information provided.</string>-    <!-- View screen: button that opens the editor. Verb phrase. -->-    <string name="edit_info">Edit information</string>      <!-- Edit screen: owner's name row. Noun. -->     <string name="field_name">Name</string>     <!-- Edit screen: address row. Noun. -->     <string name="field_address">Address</string>+    <!-- Edit screen: heading above the owner's picked identity. Noun phrase. -->+    <string name="section_owner_identity">Your identity</string>+    <!-- Edit screen: row that opens the contact picker for the owner's identity. Verb phrase. -->+    <string name="choose_owner_contact">Choose your contact</string>+    <!-- Edit screen: hint shown when no owner contact has been picked yet. -->+    <string name="owner_identity_empty">Pick your contact to fill in your name and address.</string>+    <!-- Address chooser: title asking which of the picked contact's addresses to use. Has the contact's name as its argument. -->+    <string name="owner_address_chooser_title">Which address for <xliff:g id="name" example="Sam Rivera">%1$s</xliff:g>?</string>+    <!-- Edit screen: shown when the picked owner contact could not be read. -->+    <string name="fail_pick_owner">Could not read that contact.</string>     <!-- Edit screen: blood-type row. Noun phrase. -->     <string name="field_blood_type">Blood type</string>     <!-- Edit screen: organ-donor row. Noun phrase. -->@@ -65,10 +83,8 @@     <!-- Shown in place of the contact list while contacts are still being read. -->     <string name="contacts_loading">Loading contacts…</string> -    <!-- View/edit screen: heading above allergies read from Health Connect. Noun. -->-    <string name="section_allergies">Allergies</string>-    <!-- View/edit screen: heading above current medications read from Health Connect. Noun phrase. -->-    <string name="section_current_medications">Current medications</string>+    <!-- View screen: heading above current medications read from Health Connect. Noun phrase. -->+    <string name="section_current_medications">Medications</string>     <!-- Attribution shown under the Health Connect sections. -->     <string name="from_health_connect">From Health Connect</string>     <!-- Allergy criticality shown as a trailing label on high-severity allergies. Noun phrase. -->
emergency/src/screenshotTest/kotlin/com/vayunmathur/emergency/ui/MetadataPreviews.kt
diff --git a/emergency/src/screenshotTest/kotlin/com/vayunmathur/emergency/ui/MetadataPreviews.kt b/emergency/src/screenshotTest/kotlin/com/vayunmathur/emergency/ui/MetadataPreviews.ktindex a926c87754..94ab6fec89 100644--- a/emergency/src/screenshotTest/kotlin/com/vayunmathur/emergency/ui/MetadataPreviews.kt+++ b/emergency/src/screenshotTest/kotlin/com/vayunmathur/emergency/ui/MetadataPreviews.kt@@ -49,8 +49,6 @@ class MetadataPreviews {                     health = sampleHealthConnect(),                 ),                 ownerName = "Sam Rivera",-                showEdit = true,-                onEdit = {},             )         }     }@@ -69,6 +67,21 @@ class MetadataPreviews {                 ),                 actions = EmergencyActions.Noop,                 onPickContact = {},+                onPickOwner = {},+            )+        }+    }++    @PreviewTest+    @Preview(name = "4-address", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview4OwnerAddress() {+        DynamicTheme(darkTheme = true) {+            OwnerAddressDialog(+                name = "Sam Rivera",+                addresses = listOf("1 Main St, Springfield", "9 Lake Ave, Shelbyville"),+                onConfirm = {},+                onDismiss = {},             )         }     }
emergency/src/test/java/com/vayunmathur/emergency/domain/OwnerPostalFormatTest.kt
diff --git a/emergency/src/test/java/com/vayunmathur/emergency/domain/OwnerPostalFormatTest.kt b/emergency/src/test/java/com/vayunmathur/emergency/domain/OwnerPostalFormatTest.ktnew file mode 100644index 0000000000..043e599c6e--- /dev/null+++ b/emergency/src/test/java/com/vayunmathur/emergency/domain/OwnerPostalFormatTest.kt@@ -0,0 +1,32 @@+package com.vayunmathur.emergency.domain++import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Checks for the postal fallback join used when a picked contact's address+ * row has no preformatted address.+ */+class OwnerPostalFormatTest {++    @Test+    fun allComponentsJoinWithCommas() {+        assertEquals(+            "1 Main St, Springfield, IL, 62701, USA",+            formatPostalFallback("1 Main St", "Springfield", "IL", "62701", "USA"),+        )+    }++    @Test+    fun blankAndNullComponentsAreDropped() {+        assertEquals(+            "Springfield, USA",+            formatPostalFallback(null, "Springfield", "", "   ", "USA"),+        )+    }++    @Test+    fun allBlankGivesEmptyString() {+        assertEquals("", formatPostalFallback(null, "", "  ", null, ""))+    }+}
et_tree.json
diff --git a/et_tree.json b/et_tree.jsonnew file mode 100644index 0000000000..46eb1f584e--- /dev/null+++ b/et_tree.json@@ -0,0 +1,4 @@+{+	"status": 403,+	"message": "Package size exceeded the configured limit of 50 MB."+}\ No newline at end of file
findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.ktindex df199f5f2f..322b36689c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/MapView.kt@@ -49,6 +49,8 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import com.vayunmathur.library.map.CameraState import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.GestureOptions+import com.vayunmathur.library.map.MapOptions import com.vayunmathur.library.map.VectorMap import kotlin.io.encoding.Base64 import kotlin.math.abs@@ -100,6 +102,7 @@ fun MapView(             VectorMap(                 cameraState = camera,                 zoomRange = 0f..20f,+                options = MapOptions(gestureOptions = GestureOptions.TiltLocked),                 onMapClick = { onMapClick() },             ) {                 if (initialized) {
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.ktindex 945c1f1b15..8b65ce93be 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt@@ -35,6 +35,8 @@ import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.map.CameraPosition import com.vayunmathur.library.map.GeoPoint+import com.vayunmathur.library.map.GestureOptions+import com.vayunmathur.library.map.MapOptions import com.vayunmathur.library.map.VectorMap import com.vayunmathur.library.map.rememberCameraState import com.vayunmathur.library.ui.AppScaffold@@ -224,7 +226,7 @@ private fun TrackingMap(order: Order, modifier: Modifier = Modifier) {     }      Box(modifier) {-        VectorMap(cameraState = camera) {+        VectorMap(cameraState = camera, options = MapOptions(gestureOptions = GestureOptions.TiltLocked)) {             // Distinct glyph per pin: menu = restaurant, arrow = courier, home = you.             restaurant?.let {                 MapMarker(it) { PinChrome(MaterialTheme.colorScheme.tertiary) { IconRestaurant() } }
games/chess/build.gradle.kts
diff --git a/games/chess/build.gradle.kts b/games/chess/build.gradle.ktsindex 69e7e55766..886f4ddae3 100644--- a/games/chess/build.gradle.kts+++ b/games/chess/build.gradle.kts@@ -14,10 +14,10 @@ android {         applicationId = "com.vayunmathur.games.chess"     }     androidResources {-        // Maia3's weights are read straight out of the APK, and a compressed asset would have-        // to be inflated into a heap buffer before ORT could open it. Costs nothing on download-        // size: quantised weights barely compress.-        noCompress += "onnx"+        // The ExecuTorch Vulkan model is staged the same way: ExecutorchSessions+        // copies it out of the APK before Module.load, so it must not be deflated.+        // Quantised weights barely compress, so this costs nothing on download size.+        noCompress += "pte"     } } 
games/chess/src/main/assets/README.md
diff --git a/games/chess/src/main/assets/README.md b/games/chess/src/main/assets/README.mdindex a8ff0f5eb9..30600e61fc 100644--- a/games/chess/src/main/assets/README.md+++ b/games/chess/src/main/assets/README.md@@ -1,69 +1,22 @@-# `maia3-5m.maml`-+# `maia3_vulkan_int8wo.pte` Maia3-5M, the chess AI. Converted from **[`UofTCSSLab/Maia3-5M`](https://huggingface.co/UofTCSSLab/Maia3-5M)**-(`maia3-5m.pt`, 20.0 MB fp32) to 6.8 MiB of int8.--Rebuild it byte for byte with:--    python scripts/ml/fetch_maia.py--which pins the upstream revision and the checkpoint's SHA-256, asserts the parameter inventory,-and writes this file. Committed rather than gitignored, for the same reason `:speech`'s voice-bundle is: a fresh checkout that silently ships a chess app with no opponent is worse than the-history.-+(`maia3-5m.pt`, 20.0 MB fp32) to an ExecuTorch export for the Vulkan delegate+(int8 weight-only, 6.3 MB, torch-level cos ≥ 0.9990 vs the ship w4 rung):+`tokens [1,64,97]` (square-major), `self_elo`/`oppo_elo [1]` in, `moves [1,4352]`+out. Exported with executorch 1.5.0+cpu — see `analysis/et-maia/export_maia.py`+(gitignored staging, not shipped). This is the only Maia runtime: a missing file,+an unlinked Vulkan delegate, or a failed run fails closed (no move), with no+`.tflite` fallback. ## What it is--An encoder-only transformer over 64 square tokens — width 256, 8 blocks, 8 heads, 5,230,084+An encoder-only transformer over 64 square tokens - width 256, 8 blocks, 8 heads, 5,230,084 parameters. Upstream calls the architecture "Chessformer"; the code is [CSSLab/maia3](https://github.com/CSSLab/maia3).- It **predicts human moves** rather than searching for good ones. One forward pass per move, no tree. Strength is a model input (`SelfElo` / `OppoElo`, 0..5000), so this one file covers all-four difficulty levels — see `Difficulty` in+four difficulty levels - see `Difficulty` in `games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt`.- It replaces Stockfish and its 86 MB `nn-71d6d32cb962.nnue`, which is where the APK's ~79 MB-reduction comes from. It also removed the last personal JitPack fork from the tree; see-`SUPPLY_CHAIN_RISKS.md`.--## Precision--Every `1x1` convolution is int8, quantised per output channel; the norms, the biases and the-two elo embeddings stay fp16 and are 1% of the parameters. Worst per-tensor correlation against-fp32 is 0.999941.--That was chosen on **move agreement**, not on the cosine gate, because a cosine says nothing-about whether the model still picks the same move:--| | size | move agreement vs fp32 | disagreements wider than fp16 rounding |-|---|---|---|---|-| fp16 | 13.3 MiB | — | — |-| **int8, per channel** | **6.8 MiB** | **99.0–99.5%** | **0** |-| int4, per 16 | 4.2 MiB | 91.2% | 14 |-| int4, per channel | 3.5 MiB | 88.0% | 29 |--int4 is rejected: its disagreements are the model changing its mind, not losing a coin flip,-and sub-row grouping gives back most of the saving without fixing it. 5.2M parameters have no-redundancy to spare. Re-measure any of this with `python scripts/ml/maia_quant_eval.py`.--## How it is checked--* `scripts/ml/test/test_maia.py` — the converter's tensor order, the int8 triple, and the two-  structural rewrites (the fused q/k/v split, the eight-fold attention-bias replication),-  against a toy model.-* `scripts/ml/maia_parity.py` — the real weights through the Rust interpreter against the-  PyTorch reference, over `maia_parity_fixture.json`. Agreement on the best **legal** move as-  well as on the numbers, because a wrong board encoding still plays legal chess.-* `scripts/ml/maia_quant_eval.py` — what the quantisation costs, in moves, over hundreds of-  positions at every shipping rating.-* `MaiaEncodingTest` in `src/test/` — the board planes, the move vocabulary and perft.--The forward pass is `library/ml/src/main/rust/src/nets/maia.rs`, which documents the parts that-fail silently: the post-norm block order, the RMS norms, and why the attention bias is a grouped-convolution.-+reduction comes from. ## Licence- Maia3's weights are released by the University of Toronto's Computational Social Science Lab. See the model card at the link above for terms.
games/chess/src/main/assets/maia3-5m.onnx
diff --git a/games/chess/src/main/assets/maia3-5m.onnx b/games/chess/src/main/assets/maia3-5m.onnxdeleted file mode 100644index 891b795f0c..0000000000Binary files a/games/chess/src/main/assets/maia3-5m.onnx and /dev/null differ
games/chess/src/main/assets/maia3_vulkan_int8wo.pte
diff --git a/games/chess/src/main/assets/maia3_vulkan_int8wo.pte b/games/chess/src/main/assets/maia3_vulkan_int8wo.ptenew file mode 100644index 0000000000..c7df58e7f4Binary files /dev/null and b/games/chess/src/main/assets/maia3_vulkan_int8wo.pte differ
games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.ktindex 3f9a9a38f7..74691fee44 100644--- a/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/util/MaiaEngine.kt@@ -142,7 +142,7 @@ class MaiaEngine(private val context: Context) {         model?.let { return it }         if (closed || attempts >= MAX_ATTEMPTS) return null         attempts++-        val handle = MaiaHandle.inAssets(context.assets)+        val handle = MaiaHandle.inContext(context)         if (!handle.isAvailable) {             handle.close()             return null
gradle.properties
diff --git a/gradle.properties b/gradle.propertiesindex 03fc140c7f..ac19b2afa1 100644--- a/gradle.properties+++ b/gradle.properties@@ -1,19 +1,23 @@-# Heap sized for a full local assembleDev of all modules at once: with-# parallel=true and workers.max=4, several modules run mergeExtDex/D8-# concurrently in the same daemon heap, and 3584m was exhausted (D8 dex merge-# OutOfMemoryError). 6144m gives the concurrent D8 workers enough headroom.-# On 16GB CI runners this -Xmx46g cannot start; the GitHub workflows-# (.github/workflows/android.yml + pr-compile-check.yml) override these via-# ~/.gradle/gradle.properties with a runner-appropriate heap + workers.max=2.+# Default daemon heap is sized for scoped work (:module: builds, lint, agents):+# small Xms so idle daemons are cheap and several can coexist without the OS+# killing them (a kill forces a full multi-minute reconfigure on next build).+# Full-repo builds (`./install all`, ~100 modules with concurrent D8 dex merge)+# OOM on this heap, so install/install.ps1 auto-escalate with+# -Dorg.gradle.jvmargs=<46g big-build heap> + --max-workers=32 when — and only+# when — the `all` keyword is expanded (a separate big daemon; the small one+# stays alive). Do not raise the default here — override locally in+# ~/.gradle/gradle.properties instead (same mechanism CI uses). # # MaxMetaspaceSize=1024m: the previous 512m cap was killing the daemon on # release builds (R8 fullMode + lintVitalRelease + KSP + Kotlin compile all-# load class metadata into the same daemon's metaspace; with parallel=4 we+# load class metadata into the same daemon's metaspace; with parallel workers we # easily blew past 512m).-org.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8+org.gradle.jvmargs=-Xmx8g -Xms512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8 kotlin.daemon.jvm.options=-Xmx1536m -# Use more workers in parallel for multi-module compilation.+# Cap parallel workers so concurrent D8/Kotlin workers fit in the default heap.+# install/install.ps1 raise this for full builds.+org.gradle.workers.max=2 org.gradle.parallel=true org.gradle.caching=true 
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex af95e88d49..252bc6f080 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -112,6 +112,10 @@ quickjs = "1.0.15" onnxruntimeAndroid = "1.27.0" onnxruntimeReduced = "1.27.0-r1" litertlmAndroid = "0.14.0"+litert = "2.1.0"+# ExecuTorch (XNNPACK-lowered .pte models, e.g. selfie segmentation). Maven Central+# latest stable; verified 1.4.0 on 2026-09-16 (org.pytorch:executorch-android).+executorch = "1.4.0"  # Git jgit = "7.8.0.202609011348-r"@@ -305,6 +309,18 @@ onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android" # 1.11.0 (close$default moved onto the SendChannel interface via -Xjvm-default=all); older # versions crash its JNI callback with NoSuchMethodError, so keep kotlinxCoroutines at 1.11.0. litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" }+# LiteRT (TFLite) runtime for the quantized .tflite ladder (ladder_v2 ship rungs).+# Google Maven, single self-contained `litert` artifact (CompiledModel API ++# libLiteRt.so; no litert-api split yet at 2.1.0, so no duplicate-namespace clash).+litert-android = { module = "com.google.ai.edge.litert:litert", version.ref = "litert" }+# ExecuTorch runtime for XNNPACK-lowered .pte models. Single `executorch-android` AAR+# (org.pytorch.executorch.Module API + libexecutorch.so; fbjni/soloader come transitively).+executorch-android = { module = "org.pytorch:executorch-android", version.ref = "executorch" }+# fbjni + soloader: transitive deps of executorch-android above, pinned to the versions in its+# POM (0.7.0 / 0.10.5). Needed explicitly because :library:ml consumes the custom Vulkan AAR+# (library/ml/libs/) as a file dep, which carries no POM.+fbjni = { module = "com.facebook.fbjni:fbjni", version = "0.7.0" }+soloader-nativeloader = { module = "com.facebook.soloader:nativeloader", version = "0.10.5" }  # Git jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" }
install
diff --git a/install b/installindex 5d7d71577d..1e407461bf 100755--- a/install+++ b/install@@ -511,6 +511,16 @@ if [[ "$VARIANT_LC" == "release" && $ALL_EXPANDED -eq 1 ]]; then   gradle_args_str="$gradle_args_str -Pandroid.r8.maxWorkers=8" fi +# --- Big-build heap: gradle.properties defaults to a small daemon heap sized for+# scoped work. A full-repo build ("all", ~100 modules, concurrent D8 dex merge)+# OOMs on it, so escalate here — and only here (ALL_EXPANDED). -D spawns a+# separate big daemon; the small one stays alive for normal builds.+if [[ $ALL_EXPANDED -eq 1 ]]; then+  GRADLE_ARGS+=(-D"org.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8")+  GRADLE_ARGS+=(--max-workers=32)+  gradle_args_str="$gradle_args_str -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32"+fi+ # --- versionCodeOverride: MAOS refuses to update a system package to the same # versionCode, so an APK built from the same version.txt as the on-device OS image # can never be installed over it. Query the device once; if any requested package
install.ps1
diff --git a/install.ps1 b/install.ps1index 6e1cadc98e..b89406afa4 100644--- a/install.ps1+++ b/install.ps1@@ -507,6 +507,16 @@ if ($VariantLc -eq 'release' -and $allExpanded) {     $gradleArgsStr += ' -Pandroid.r8.maxWorkers=8' } +# --- Big-build heap: gradle.properties defaults to a small daemon heap sized for+# scoped work. A full-repo build ("all", ~100 modules, concurrent D8 dex merge)+# OOMs on it, so escalate here — and only here ($allExpanded). -D spawns a+# separate big daemon; the small one stays alive for normal builds.+if ($allExpanded) {+    $gradleArgs += @('-Dorg.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8')+    $gradleArgs += @('--max-workers=32')+    $gradleArgsStr += ' -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=32'+}+ # --- versionCodeOverride: MAOS refuses to update a system package to the same # versionCode, so an APK built from the same version.txt as the on-device OS image # can never be installed over it. Query the device once; if any requested package
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.ktindex 40096f2613..916c3ee6f6 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt@@ -6,132 +6,73 @@ package com.vayunmathur.library.downloadservice  * The server must host each file under https://data.vayunmathur.com/models/  * and set Content-Length + ETag.  *- * # Gemma 4 is nine files, not one+ * # Gemma 4 is one file on LiteRT-LM  *- * The chat LLM is `onnx-community/gemma-4-E2B-it-ONNX` (Apache-2.0 and ungated),- * specifically the q4f16 quant family, run on `:library:ml`'s reduced ONNX Runtime build- * via `GemmaOnnxHandle` (embed graph per turn + KV-cached decode, vision/audio towers as- * soft tokens). Files, with upstream names kept so external-data resolution needs no- * mapping:- *- *   models/decoder_model_merged_q4f16.onnx + .onnx_data  (~1.5 GB decoder)- *   models/embed_tokens_q4f16.onnx + .onnx_data          (~1.6 GB embeddings)- *   models/tokenizer.json                               (~19 MB BPE table)- *   models/vision_encoder_q4f16.onnx + .onnx_data       (~99 MB, optional tower)- *   models/audio_encoder_q4f16.onnx + .onnx_data        (~171 MB, optional tower)- *- * The first five must be present before the assistant will start - see- * `GemmaOnnxHandle.FILES`. The two towers are optional at load: a device that never sends- * a picture or a clip still answers text.+ * The chat LLM is `litert-community/gemma-4-E2B-it-litert-lm` (Apache-2.0),+ * the `gemma-4-E2B-it.litertlm` bundle (~2.6 GB, CPU backend), run on the+ * LiteRT-LM runtime via `Gemma4Engine` in `:openassistant`. It must be present+ * before the assistant will start.  */ object ModelUrls {     const val MIRROR_BASE = "https://data.vayunmathur.com/models/" -    /** The decoder export (graph only; weights ride alongside in the `.onnx_data`). */-    const val GEMMA_DECODER_FILE = "decoder_model_merged_q4f16.onnx"-    const val GEMMA_DECODER_URL = "${MIRROR_BASE}decoder_model_merged_q4f16.onnx"-    const val GEMMA_DECODER_SHA256 =-        "73c0f1fe04f9a3a048fb3319c0671b6cf0346bf33a3a8624c853bcffe01c24a4"--    const val GEMMA_DECODER_DATA_FILE = "decoder_model_merged_q4f16.onnx_data"-    const val GEMMA_DECODER_DATA_URL = "${MIRROR_BASE}decoder_model_merged_q4f16.onnx_data"-    const val GEMMA_DECODER_DATA_SHA256 =-        "3b27245a7396cb7039a4e4118bd2a8aa35106bae381522edf7c4867b5f22bb10"--    /** The embedding graph + tables. */-    const val GEMMA_EMBED_FILE = "embed_tokens_q4f16.onnx"-    const val GEMMA_EMBED_URL = "${MIRROR_BASE}embed_tokens_q4f16.onnx"-    const val GEMMA_EMBED_SHA256 =-        "d7ca53f6a169471b5699b2f57ee4c7aa2c73732b0152f3909e64b71384444825"--    const val GEMMA_EMBED_DATA_FILE = "embed_tokens_q4f16.onnx_data"-    const val GEMMA_EMBED_DATA_URL = "${MIRROR_BASE}embed_tokens_q4f16.onnx_data"-    const val GEMMA_EMBED_DATA_SHA256 =-        "024b199e6358ed42970f807686add5f9430d7e254ca7ce22fc9c83f015b9c517"--    /** The BPE table: 262,144 entries plus 24 added tokens. */-    const val GEMMA_TOKENIZER_FILE = "tokenizer.json"-    const val GEMMA_TOKENIZER_URL = "${MIRROR_BASE}tokenizer.json"-    const val GEMMA_TOKENIZER_SHA256 =-        "47bd35616c7c782aaca6ccf48c75f3461d5877170984b8836b375107d0a9f566"--    /**-     * The vision tower (optional, same terms as the old `.maml` tower).-     */-    const val GEMMA_VISION_FILE = "vision_encoder_q4f16.onnx"-    const val GEMMA_VISION_URL = "${MIRROR_BASE}vision_encoder_q4f16.onnx"-    const val GEMMA_VISION_SHA256 =-        "e0a4e48e519ade4eeddbb4cdadb812a7251aea871f7fb5f50576615fd3af22a3"+    /** The litertlm bundle (CPU; vision/audio towers included in the bundle). */+    const val GEMMA_LITERTLM_FILE = "gemma-4-E2B-it.litertlm"+    const val GEMMA_LITERTLM_URL = "${MIRROR_BASE}gemma-4-E2B-it.litertlm"+    const val GEMMA_LITERTLM_SHA256 =+        "181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c" -    const val GEMMA_VISION_DATA_FILE = "vision_encoder_q4f16.onnx_data"-    const val GEMMA_VISION_DATA_URL = "${MIRROR_BASE}vision_encoder_q4f16.onnx_data"-    const val GEMMA_VISION_DATA_SHA256 =-        "0835071d2c79c105f8e1b549b7f8dd8c9af07fa95f01ead2e7add280602d3c6d"+    val GEMMA_LITERTLM =+        ModelDownloadItem(GEMMA_LITERTLM_URL, GEMMA_LITERTLM_FILE, "Gemma 4", GEMMA_LITERTLM_SHA256)      /**-     * The audio tower (optional, same terms as the old `.maml` tower).+     * The ExecuTorch SpinQuant `.pte` (Vulkan 8da4w, text-only) plus its BPE table, served+     * by `Gemma4EtEngine` when present.+     *+     * SHAs verified against the staged files in `analysis/et-gemma/`; `GEMMA_LITERTLM`+     * untouched. Neither file is in [INITIAL] — first launch must not gate on them.+     * `ensureLoaded` resolves them opportunistically; absent means "litertlm serves",+     * never a throw.      */-    const val GEMMA_AUDIO_FILE = "audio_encoder_q4f16.onnx"-    const val GEMMA_AUDIO_URL = "${MIRROR_BASE}audio_encoder_q4f16.onnx"-    const val GEMMA_AUDIO_SHA256 =-        "5e0deb22791685c792d4b8e089deef9670fa4a4cecde434213d6a742e58fc3fa"+    const val GEMMA_ET_FILE = "gemma-4-e2b-vulkan-8da4w.pte"+    const val GEMMA_ET_URL = "${MIRROR_BASE}openassistant/gemma-4-e2b-vulkan-8da4w.pte"+    const val GEMMA_ET_SHA256 =+        "f57a627f9fc487003913be05c1d4d5ac75f6473550809c0a345e91c10a428e2a" -    const val GEMMA_AUDIO_DATA_FILE = "audio_encoder_q4f16.onnx_data"-    const val GEMMA_AUDIO_DATA_URL = "${MIRROR_BASE}audio_encoder_q4f16.onnx_data"-    const val GEMMA_AUDIO_DATA_SHA256 =-        "df58e61a00bafa9449ee5fd52895ce952f158bbdd1fe38df8a68f48f36842e62"+    const val GEMMA_ET_TOKENIZER_FILE = "gemma4_et_tokenizer.json"+    const val GEMMA_ET_TOKENIZER_URL = "${MIRROR_BASE}openassistant/gemma_tokenizer.json"+    const val GEMMA_ET_TOKENIZER_SHA256 =+        "4667f2089529e8e7657cfb6d1c19910ae71ff5f28aa7ab2ff2763330affad795" -    val GEMMA_DECODER =-        ModelDownloadItem(GEMMA_DECODER_URL, GEMMA_DECODER_FILE, "Model", GEMMA_DECODER_SHA256)-    val GEMMA_DECODER_DATA = ModelDownloadItem(-        GEMMA_DECODER_DATA_URL, GEMMA_DECODER_DATA_FILE, "Weights", GEMMA_DECODER_DATA_SHA256,-    )-    val GEMMA_EMBED =-        ModelDownloadItem(GEMMA_EMBED_URL, GEMMA_EMBED_FILE, "Embeddings", GEMMA_EMBED_SHA256)-    val GEMMA_EMBED_DATA = ModelDownloadItem(-        GEMMA_EMBED_DATA_URL, GEMMA_EMBED_DATA_FILE, "Embeddings", GEMMA_EMBED_DATA_SHA256,-    )-    val GEMMA_TOKENIZER = ModelDownloadItem(-        GEMMA_TOKENIZER_URL,-        GEMMA_TOKENIZER_FILE,-        "Tokenizer",-        GEMMA_TOKENIZER_SHA256,-    )-    val GEMMA_VISION =-        ModelDownloadItem(GEMMA_VISION_URL, GEMMA_VISION_FILE, "Vision", GEMMA_VISION_SHA256)-    val GEMMA_VISION_DATA = ModelDownloadItem(-        GEMMA_VISION_DATA_URL, GEMMA_VISION_DATA_FILE, "Vision", GEMMA_VISION_DATA_SHA256,-    )-    val GEMMA_AUDIO =-        ModelDownloadItem(GEMMA_AUDIO_URL, GEMMA_AUDIO_FILE, "Audio", GEMMA_AUDIO_SHA256)-    val GEMMA_AUDIO_DATA = ModelDownloadItem(-        GEMMA_AUDIO_DATA_URL, GEMMA_AUDIO_DATA_FILE, "Audio", GEMMA_AUDIO_DATA_SHA256,+    val GEMMA_ET = ModelDownloadItem(GEMMA_ET_URL, GEMMA_ET_FILE, "Gemma 4 ET", GEMMA_ET_SHA256)+    val GEMMA_ET_TOKENIZER = ModelDownloadItem(+        GEMMA_ET_TOKENIZER_URL, GEMMA_ET_TOKENIZER_FILE, "Gemma 4 ET tokenizer",+        GEMMA_ET_TOKENIZER_SHA256,     ) +     /**-     * Everything downloaded on OpenAssistant first launch.-     *-     * Smallest first, so a user on a slow connection sees progress early and so the two large-     * files are the ones a resume is most likely to land in the middle of. The two towers go-     * after the tokenizer and before the two large ones: together they are ~270 MB, they are-     * what make the assistant able to answer about a photograph or a recording, and a resume-     * that stalls in the decoder should not leave them unfetched.+     * Everything downloaded on OpenAssistant first launch: the single litertlm bundle.      */     val INITIAL = listOf(-        GEMMA_TOKENIZER,-        GEMMA_VISION, GEMMA_VISION_DATA, GEMMA_AUDIO, GEMMA_AUDIO_DATA,-        GEMMA_DECODER, GEMMA_DECODER_DATA, GEMMA_EMBED, GEMMA_EMBED_DATA,+        GEMMA_LITERTLM,     )      /**      * Files an earlier build downloaded and this one does not use.      *-     * Deleted on startup rather than left to rot: the `.maml` set alone was 2.8 GB, and a-     * user upgrading would otherwise carry both copies forever.+     * Deleted on startup rather than left to rot: the ONNX set alone was ~3.4 GB, and a+     * user upgrading would otherwise carry both copies forever. (The `gemma-4-E2B-it.litertlm`+     * name stays listed because pre-ONNX builds predated it; the current bundle reuses the+     * name, so a fresh download lands after this cleanup runs — order matters, and+     * `InitialModelDownloadChecker` runs after `cleanupLegacyModelFile`.)+     *+     * The ET pair (`GEMMA_ET_FILE`, `GEMMA_ET_TOKENIZER_FILE`) is deliberately NOT listed:+     * they are opportunistically resolved, never required, so a partial download must not+     * be deleted out from under a future `ensureLoaded`.      */     val OBSOLETE = listOf(         "gemma4-2b.litertlm",-        "gemma-4-E2B-it.litertlm",         "gemma4.litertlm",         "gemma4-4b.litertlm",         "gemma4_text.maml",@@ -140,6 +81,15 @@ object ModelUrls {         "gemma4_vision.maml",         "gemma4_audio.maml",         "gemma4_prefix.kv",+        "decoder_model_merged_q4f16.onnx",+        "decoder_model_merged_q4f16.onnx_data",+        "embed_tokens_q4f16.onnx",+        "embed_tokens_q4f16.onnx_data",+        "tokenizer.json",+        "vision_encoder_q4f16.onnx",+        "vision_encoder_q4f16.onnx_data",+        "audio_encoder_q4f16.onnx",+        "audio_encoder_q4f16.onnx_data",     ) } 
library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktindex 84e2e25516..0dbfe01394 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -24,11 +24,12 @@ import kotlin.math.log2  * the whole Compose path are unchanged until something tilts or rotates the camera: a north-up,  * level camera composes exactly the axis-aligned matrices it always did.  *- * [bearing] is a rotation, which composes into the clip matrices as a plain 2x2 and is still- * honoured only on the [SurfaceMapRenderer.camera] path, because the Compose overlays are laid- * out north-up. [pitch] is the perspective tilt; unlike bearing it *is* honoured on the Compose- * path, because [Projection] is now pitch-aware (ray/plane), so `MapMarker`s and pins follow the- * tilt instead of floating off the ground.+ * [bearing] is a rotation, which composes into the clip matrices as a plain 2x2 and is+ * honoured on both the [SurfaceMapRenderer.camera] and the Compose paths: [Projection]+ * carries it, so `MapMarker`s and pins rotate with the basemap. [pitch] is the perspective+ * tilt; like bearing it *is* honoured on the Compose path, because [Projection] is now+ * pitch-aware (ray/plane), so `MapMarker`s and pins follow the tilt instead of floating+ * off the ground.  */ data class CameraPosition(     val target: GeoPoint = GeoPoint(0.0, 0.0),@@ -39,11 +40,9 @@ data class CameraPosition(      * Zero is north-up and is what every phone screen uses. Android Auto's heading-up      * navigation is the one caller that sets it, through [SurfaceMapRenderer.camera].      *-     * **Setting it on a [CameraState] does nothing.** The Compose path forces it to zero-     * before the frame, because [Projection]'s bearing is north-up and everything positioned-     * through it — every `MapMarker`, pin and cluster — would stay put while the basemap turned-     * underneath. Ignoring it is a visible no-op; honouring it would be a silent wrong-     * render that nothing reports.+     * Honoured on both paths: the Compose path carries it through [Projection] (which+     * rotates overlays with the basemap) and the renderer path passes it to the native+     * frame, so setting it rotates the whole map — basemap, markers, pins and clusters.      */     val bearing: Double = 0.0,     /**@@ -112,7 +111,7 @@ class CameraState(initial: CameraPosition = CameraPosition()) {      */     val projection: Projection? by derivedStateOf {         viewportDp?.let { vp ->-            Projection(position.target, position.zoom, vp.width, vp.height, position.pitch, labelQueryProvider, markerPickProvider)+            Projection(position.target, position.zoom, vp.width, vp.height, position.pitch, position.bearing, labelQueryProvider, markerPickProvider)         }     } @@ -212,13 +211,17 @@ class CameraState(initial: CameraPosition = CameraPosition()) {         var zoom = position.zoom          // Pan: dragging content one way shifts the world the same way, so the-        // center moves opposite to the pan.+        // center moves opposite to the pan. The gesture arrives in screen space but the+        // Mercator math below is in world space, so inverse-rotate it by the bearing first+        // (mirroring `Projection.positionFromScreenLocation`'s inverse step). At zero+        // bearing the rotation is the identity and this is unchanged.+        val panWorld = unrotatePan(panDp, position.bearing)         val cWorld = Mercator.project(position.target.longitude, position.target.latitude, zoom)         var cx = cWorld.x         var cy = cWorld.y         if (scrollEnabled) {-            cx -= panDp.x-            cy -= panDp.y+            cx -= panWorld.x+            cy -= panWorld.y         }         var center = Mercator.unproject(cx, cy, zoom) @@ -290,14 +293,33 @@ private fun anchoredZoom(     anchorDp: Offset,     vp: Size, ): CameraPosition {-    val dx = anchorDp.x - vp.width / 2.0-    val dy = anchorDp.y - vp.height / 2.0+    // The anchor is a screen point; its offset from the viewport centre is what the+    // Mercator math consumes, so inverse-rotate that offset by the bearing first (same+    // step as the pan in `onGesture`). At zero bearing this is the identity.+    val rawDx = anchorDp.x - vp.width / 2.0+    val rawDy = anchorDp.y - vp.height / 2.0+    val anchorWorld = unrotatePan(Offset(rawDx.toFloat(), rawDy.toFloat()), from.bearing)+    val dx = anchorWorld.x.toDouble()+    val dy = anchorWorld.y.toDouble()     val cw = Mercator.project(from.target.longitude, from.target.latitude, from.zoom)     val geo = Mercator.unproject(cw.x + dx, cw.y + dy, from.zoom)     val gw = Mercator.project(geo.longitude, geo.latitude, newZoom)     return from.copy(target = Mercator.unproject(gw.x - dx, gw.y - dy, newZoom), zoom = newZoom) } +/**+ * A screen-space delta back into world space: the inverse of [Projection]'s bearing rotation+ * (`x = cos*sx - sin*sy, y = sin*sx + cos*sy`). Short-circuited at zero so the north-up path+ * is bit-identical.+ */+private fun unrotatePan(pan: Offset, bearingDeg: Double): Offset {+    if (bearingDeg == 0.0) return pan+    val radians = Math.toRadians(bearingDeg)+    val cos = kotlin.math.cos(radians)+    val sin = kotlin.math.sin(radians)+    return Offset((cos * pan.x - sin * pan.y).toFloat(), (sin * pan.x + cos * pan.y).toFloat())+}+ private fun lerp(start: Double, end: Double, t: Double): Double = start + (end - start) * t  /**
library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt b/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.ktindex eb9e0d0da1..804c9e320f 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/ImageOverlay.kt@@ -3,9 +3,9 @@ package com.vayunmathur.library.map import androidx.compose.ui.graphics.ImageBitmap  /**- * A georeferenced translucent image drawn over the basemap. Because the map is- * north-up and axis-aligned, the [bitmap] is stretched into the screen rect of- * [bounds]'s corners (see [RasterMap]). Replaces maplibre's+ * A georeferenced translucent image drawn over the basemap. The [bitmap] is stretched into+ * the screen quad of [bounds]' corners: axis-aligned north-up, rotated with the basemap+ * under a bearing (see [RasterMap]). Replaces maplibre's  * `RasterLayer` + `rememberImageSource` + `PositionQuad`.  */ data class ImageOverlay(
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 312c08a706..87f236be5e 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@@ -110,7 +110,7 @@ internal fun Modifier.mapGestures(         // of a pan. A pinch (fingers moving apart / opposite) or a twist is left untouched, so         // zoom still works.         .pointerInput(cameraState, gestures, density) {-            if (!gestures.isScrollEnabled && !gestures.isZoomEnabled) {+            if ((!gestures.isScrollEnabled && !gestures.isZoomEnabled) || !gestures.isTiltEnabled) {                 return@pointerInput             }             detectVerticalTiltGestures { dyPx -> cameraState.onTilt(dyPx / density) }
library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.ktindex 29e35d47cb..7200bd7a75 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapOptions.kt@@ -1,19 +1,24 @@ package com.vayunmathur.library.map  /**- * Which pan/zoom/rotate gestures are enabled. Tilt (two-finger vertical drag) is always on- * where the detector runs; rotation needs no separate detector, so it is one flag here.+ * Which pan/zoom/rotate/tilt gestures are enabled. Tilt is the two-finger vertical drag;+ * rotation needs no separate detector, so it is one flag here.  */ data class GestureOptions(     val isScrollEnabled: Boolean = true,     val isZoomEnabled: Boolean = true,     val isRotateEnabled: Boolean = true,+    val isTiltEnabled: Boolean = true, ) {     companion object {         /** Pan + zoom, rotation locked north-up (the old default behaviour). */         val RotationLocked =             GestureOptions(isScrollEnabled = true, isZoomEnabled = true, isRotateEnabled = false) +        /** Pan + zoom only: no twist-rotate, no two-finger tilt. What every app but `maps` uses. */+        val TiltLocked =+            GestureOptions(isScrollEnabled = true, isZoomEnabled = true, isRotateEnabled = false, isTiltEnabled = false)+         /** All gestures disabled (static map). */         val AllDisabled = GestureOptions(isScrollEnabled = false, isZoomEnabled = false)     }@@ -44,4 +49,23 @@ data class MapOptions(      * [LayerOptions] for why, and for what turning one on costs.      */     val layerOptions: LayerOptions = LayerOptions(),+    /**+     * Where tiles come from. [TileSource.Server] (default) streams range requests for+     * `planet.mamaps` over HTTP with a disk range cache; [TileSource.LocalFile] reads a+     * pushed `.mamaps` archive from the app's external files dir and does no networking.+     * Today only `maps` pushes an archive, so every other app stays on the default.+     */+    val tileSource: TileSource = TileSource.Server, )++/**+ * Where the renderer reads its tiles from.+ */+enum class TileSource {+    /** Stream `planet.mamaps` range requests over HTTP, cached on disk. */+    Server,+    /** Read a pushed `.mamaps` archive from external files; no networking. Falls back to+     * [Server] when no archive file is present, so a missing push degrades to streaming+     * rather than a blank map. */+    LocalFile,+}
library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapScope.ktindex 7d5842a3cd..a7881a74d6 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapScope.kt@@ -84,7 +84,11 @@ class MapScope internal constructor(private val cameraState: CameraState) {                 }                 val offscreen = x + width < 0 || y + height < 0 ||                     x > viewportWidth || y > viewportHeight-                if (offscreen) return@layout+                // Under a bearing the markers rotate about the viewport centre while this cull+                // box does not, so a marker near an edge could be culled while still visible.+                // The projection is already bearing-aware, so only the cull needs widening:+                // skip it (or expand by the rotated support extents) when rotated.+                if (offscreen && cameraState.position.bearing == 0.0) return@layout                 placeables.forEach { it.place(x, y) }             }         }
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 79e476b3f5..9a760cb5aa 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@@ -48,8 +48,9 @@ data class PlacedLabel(  * At [pitchDeg] `== 0` this is the plain orthographic inverse it always was. When tilted it  * mirrors the native perspective in `camera::Camera` exactly — [screenLocationFromPosition]  * projects through the same divide, [positionFromScreenLocation] intersects the eye ray with the- * ground plane — so Compose overlays land where the renderer drew the basemap under them. Bearing- * is not carried here: the Compose path renders north-up, so a projection for it does too.+ * ground plane — so Compose overlays land where the renderer drew the basemap under them.+ * [bearingDeg] rotates the map clockwise-from-north exactly as the native `Camera::rotation`+ * 2x2 does, so the Compose overlays agree with the rotated basemap; `0.0` is north-up.  *  * [labelQuery] answers [queryRenderedLabels]: null until a rendered surface  * registers one (see `VulkanMapSurface`), so a projection without a live@@ -61,6 +62,7 @@ class Projection internal constructor(     private val widthDp: Float,     private val heightDp: Float,     private val pitchDeg: Double = 0.0,+    private val bearingDeg: Double = 0.0,     private val labelQuery: ((DpRect, Set<String>) -> List<PlacedLabel>)? = null,     private val markerPick: ((Float, Float) -> Long)? = null, ) {@@ -77,8 +79,23 @@ class Projection internal constructor(     fun screenLocationFromPosition(position: GeoPoint): DpOffset {         val c = Mercator.project(center.longitude, center.latitude, zoom)         val p = Mercator.project(position.longitude, position.latitude, zoom)-        val sx = p.x - c.x-        val sy = p.y - c.y+        val dx = p.x - c.x+        val dy = p.y - c.y+        // Bearing rotation first (mirroring `Camera::rotation`): a world offset becomes a+        // screen offset via sx = cos*dx + sin*dy, sy = -sin*dx + cos*dy. At zero bearing+        // this is the identity, so the north-up path is unchanged.+        val sx: Double+        val sy: Double+        if (bearingDeg == 0.0) {+            sx = dx+            sy = dy+        } else {+            val radians = Math.toRadians(bearingDeg)+            val cos = cos(radians)+            val sin = sin(radians)+            sx = cos * dx + sin * dy+            sy = -sin * dx + cos * dy+        }         if (pitchDeg == 0.0) {             return DpOffset((sx + halfW).toFloat().dp, (sy + halfH).toFloat().dp)         }@@ -124,12 +141,20 @@ class Projection internal constructor(             val w = d - psin * sy             sx = ndcX * w / fx         }-        return Mercator.unproject(c.x + sx, c.y + sy, zoom)+        // Inverse bearing rotation (mirroring `Camera::screen_to_world`): the screen offset back+        // to a world offset via x = cos*sx - sin*sy, y = sin*sx + cos*sy.+        if (bearingDeg == 0.0) {+            return Mercator.unproject(c.x + sx, c.y + sy, zoom)+        }+        val radians = Math.toRadians(bearingDeg)+        val cos = cos(radians)+        val sin = sin(radians)+        return Mercator.unproject(c.x + cos * sx - sin * sy, c.y + sin * sx + cos * sy, zoom)     }      /** The lon/lat bounds of the currently visible viewport. */     fun queryVisibleBoundingBox(): GeoBounds {-        if (pitchDeg == 0.0) {+        if (pitchDeg == 0.0 && bearingDeg == 0.0) {             val topLeft = positionFromScreenLocation(DpOffset(0.dp, 0.dp))             val bottomRight = positionFromScreenLocation(DpOffset(widthDp.dp, heightDp.dp))             return GeoBounds(@@ -139,9 +164,10 @@ class Projection internal constructor(                 north = topLeft.latitude,             )         }-        // Tilted: the visible ground is a trapezoid, so take the AABB of all four screen corners'-        // ground points. The top edge recedes toward the horizon, so this box is larger than the-        // untilted one — correctly, since that ground really is on screen.+        // Tilted and/or rotated: the visible ground is a trapezoid or a rotated rectangle, so+        // take the AABB of all four screen corners' ground points. The box grows up to sqrt(2)+        // at 45 degrees — correctly, since that ground really is on screen (mirroring the+        // native `viewport_bounds` support function).         val corners = listOf(             positionFromScreenLocation(DpOffset(0.dp, 0.dp)),             positionFromScreenLocation(DpOffset(widthDp.dp, 0.dp)),
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex 09c85a9365..88ed043a46 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -137,9 +137,9 @@ class SurfaceMapRenderer(      * 60 Hz costs the assignment plus an [invalidate], which is a timestamp and an      * already-posted check.      *-     * [CameraPosition.bearing] rotates the map for heading-up navigation. It is only-     * usable through this property: the Compose path takes its camera from a-     * [CameraState], whose [Projection] is north-up only.+     * [CameraPosition.bearing] rotates the map for heading-up navigation. Usable through this+     * property and through a [CameraState] on the Compose path: [Projection] now carries the+     * bearing, so overlays rotate with the basemap on both paths.      *      * Ignored while [composeCamera] is set, which is the Compose path only.      */@@ -267,12 +267,23 @@ class SurfaceMapRenderer(     }      /**-     * A `.mamaps` archive pushed to the device's external files dir, if present. When it-     * exists the renderer opens it directly and does no networking; otherwise this is-     * `null` and the renderer uses the built-in URL and its range cache unchanged.+     * Where tiles come from — see [TileSource]. Remembered so a surface attached after a+     * host sets it still starts on the right source; changing it after attach takes+     * effect on the next attach (detach + attach), since workers open their archive once+     * at creation. Defaults to [TileSource.Server].+     */+    var tileSource: TileSource = TileSource.Server++    /**+     * A `.mamaps` archive pushed to the device's external files dir, if present and+     * [tileSource] is [TileSource.LocalFile]. When it exists the renderer opens it+     * directly and does no networking; otherwise this is `null` and the renderer uses+     * the built-in URL and its range cache unchanged (including the LocalFile fallback+     * when no archive was pushed).      */     private val localArchivePath: String?         get() {+            if (tileSource != TileSource.LocalFile) return null             val root = appContext.getExternalFilesDir(null) ?: appContext.filesDir             val local = File(root, LOCAL_ARCHIVE_NAME)             return if (local.exists()) local.absolutePath else null@@ -397,15 +408,10 @@ class SurfaceMapRenderer(         val position: CameraPosition         val widthDp: Float         val heightDp: Float-        // Forced to zero on the Compose path, even though CameraState now carries a-        // twist-gesture bearing: `Projection` — and therefore every `MapMarker`, pin-        // and cluster positioned through it — is north-up only for bearing, so honouring-        // one there would rotate the basemap out from under overlays that did not rotate-        // with it. The twist gesture still turns the state (the compass reads it), but the-        // Compose basemap stays north-up; only the overlay-free `[camera]` path below draws-        // it. Tilt is different: `Projection` is pitch-aware (ray/plane), so pitch *is*-        // honoured on both paths and overlays follow it. Bearing is reachable only through-        // [camera], on a surface with no Compose overlays above it.+        // The Compose path carries the twist-gesture bearing end to end: `CameraState`+        // holds it, `Projection` rotates overlays with it, and the native frame below draws+        // the basemap with it — so the basemap and everything positioned through the+        // projection turn together. Tilt is honoured the same way on both paths.         val bearing: Float         val state = composeCamera         if (state != null) {@@ -413,7 +419,7 @@ class SurfaceMapRenderer(             position = state.position             widthDp = viewport.width             heightDp = viewport.height-            bearing = 0f+            bearing = position.bearing.toFloat()         } else {             if (widthPx <= 0 || heightPx <= 0 || density <= 0f) return false             position = camera
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 a37cce945c..a2c6616138 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@@ -16,6 +16,8 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle@@ -193,6 +195,7 @@ fun VectorMap(             darkBasemap = darkBasemap,             muted = style == MapStyle.Muted,             layerOptions = options.layerOptions,+            tileSource = options.tileSource,             userPuck = userPuck,             regionMask = regionMask,             trafficColors = trafficColors,@@ -215,11 +218,13 @@ fun VectorMap( }  /**- * A georeferenced image stretched into its bounds' screen rect.+ * A georeferenced image drawn over the basemap.  *- * Drawn in Compose above the Vulkan surface rather than inside the renderer. The map is- * north-up and axis-aligned, so this is one screen-aligned quad — exactly what the raster- * renderer did with `drawImage`, and visually identical. Doing it on the GPU side would+ * Drawn in Compose above the Vulkan surface rather than inside the renderer. North-up this+ * is one screen-aligned quad — exactly what the raster renderer did with `drawImage`, and+ * visually identical. Under a bearing the bounds' corners project through the rotated+ * [Projection], so the overlay draws as a rotated quad matching the basemap beneath it.+ * Doing it on the GPU side would  * mean a texture pipeline: a `VkImage`, a sampler, a descriptor set and a second set of  * upload paths, for a single full-screen quad that Compose already composites.  *@@ -231,25 +236,63 @@ fun VectorMap( private fun GeoreferencedOverlay(overlay: ImageOverlay, cameraState: CameraState) {     Canvas(Modifier.fillMaxSize()) {         val projection = cameraState.projection ?: return@Canvas+        val bearing = cameraState.position.bearing         val northWest = projection.screenLocationFromPosition(             GeoPoint(overlay.bounds.west, overlay.bounds.north)         )+        val northEast = projection.screenLocationFromPosition(+            GeoPoint(overlay.bounds.east, overlay.bounds.north)+        )         val southEast = projection.screenLocationFromPosition(             GeoPoint(overlay.bounds.east, overlay.bounds.south)         )-        val left = northWest.x.toPx().roundToInt()-        val top = northWest.y.toPx().roundToInt()-        val right = southEast.x.toPx().roundToInt()-        val bottom = southEast.y.toPx().roundToInt()-        drawImage(-            image = overlay.bitmap,-            srcOffset = IntOffset.Zero,-            srcSize = IntSize(overlay.bitmap.width, overlay.bitmap.height),-            dstOffset = IntOffset(left, top),-            // A zero or negative extent is a degenerate bbox, which drawImage rejects.-            dstSize = IntSize((right - left).coerceAtLeast(1), (bottom - top).coerceAtLeast(1)),-            alpha = overlay.opacity,+        val southWest = projection.screenLocationFromPosition(+            GeoPoint(overlay.bounds.west, overlay.bounds.south)         )+        if (bearing == 0.0) {+            val left = northWest.x.toPx().roundToInt()+            val top = northWest.y.toPx().roundToInt()+            val right = southEast.x.toPx().roundToInt()+            val bottom = southEast.y.toPx().roundToInt()+            drawImage(+                image = overlay.bitmap,+                srcOffset = IntOffset.Zero,+                srcSize = IntSize(overlay.bitmap.width, overlay.bitmap.height),+                dstOffset = IntOffset(left, top),+                // A zero or negative extent is a degenerate bbox, which drawImage rejects.+                dstSize = IntSize((right - left).coerceAtLeast(1), (bottom - top).coerceAtLeast(1)),+                alpha = overlay.opacity,+            )+            return@Canvas+        }+        // Rotated: draw the bounds as a quadrilateral following the same corner order the+        // basemap rotated by. drawImage has no quad overload, so clip to the rotated path+        // and draw the axis-aligned image over its AABB — the clip keeps only the quad.+        val nwX = northWest.x.toPx(); val nwY = northWest.y.toPx()+        val neX = northEast.x.toPx(); val neY = northEast.y.toPx()+        val seX = southEast.x.toPx(); val seY = southEast.y.toPx()+        val swX = southWest.x.toPx(); val swY = southWest.y.toPx()+        val path = Path().apply {+            moveTo(nwX, nwY)+            lineTo(neX, neY)+            lineTo(seX, seY)+            lineTo(swX, swY)+            close()+        }+        clipPath(path) {+            val left = minOf(nwX, neX, seX, swX).roundToInt()+            val top = minOf(nwY, neY, seY, swY).roundToInt()+            val right = maxOf(nwX, neX, seX, swX).roundToInt()+            val bottom = maxOf(nwY, neY, seY, swY).roundToInt()+            drawImage(+                image = overlay.bitmap,+                srcOffset = IntOffset.Zero,+                srcSize = IntSize(overlay.bitmap.width, overlay.bitmap.height),+                dstOffset = IntOffset(left, top),+                dstSize = IntSize((right - left).coerceAtLeast(1), (bottom - top).coerceAtLeast(1)),+                alpha = overlay.opacity,+            )+        }     } } 
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 46d23c6974..d468de6f2d 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@@ -53,6 +53,7 @@ internal fun VulkanMapSurface(     darkBasemap: Boolean,     muted: Boolean,     layerOptions: LayerOptions = LayerOptions(),+    tileSource: TileSource = TileSource.Server,     userPuck: UserPuck? = null,     /** Dim everything outside the administrative region this names. `null` draws no mask. */     regionMask: RegionMask? = null,@@ -96,7 +97,7 @@ internal fun VulkanMapSurface( ) {     val context = LocalContext.current     val density = LocalDensity.current.density-    val host = remember(context) { MapSurfaceHost(context, cameraState, density, onFrame) }+    val host = remember(context, tileSource) { MapSurfaceHost(context, cameraState, density, tileSource, onFrame) }     val renderer = host.renderer      // Task-17 pick wiring: the projection answers queryRenderedLabels from@@ -267,11 +268,13 @@ private class MapSurfaceHost(     context: Context,     cameraState: CameraState,     density: Float,+    tileSource: TileSource,     onFrame: () -> Unit, ) : TextureView.SurfaceTextureListener {      val renderer = SurfaceMapRenderer(context, density, onFrame).apply {         composeCamera = cameraState+        this.tileSource = tileSource     }      private var surface: Surface? = null
library/map/src/main/rust/build.rs
diff --git a/library/map/src/main/rust/build.rs b/library/map/src/main/rust/build.rsindex 02da8bee23..10f78a82f9 100644--- a/library/map/src/main/rust/build.rs+++ b/library/map/src/main/rust/build.rs@@ -23,8 +23,8 @@ use std::process::Command;  fn main() {     let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));-    let shader_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"))-        .join("shaders");+    let shader_dir =+        PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")).join("shaders");      let glslc = find_glslc();     println!("cargo:rerun-if-changed=build.rs");@@ -143,7 +143,12 @@ fn find_glslc() -> PathBuf {         }     } -    if Command::new(executable).arg("--version").output().map(|o| o.status.success()).unwrap_or(false) {+    if Command::new(executable)+        .arg("--version")+        .output()+        .map(|o| o.status.success())+        .unwrap_or(false)+    {         return PathBuf::from(executable);     } @@ -183,7 +188,9 @@ fn sdk_dir_from_local_properties() -> Option<PathBuf> {                 let line = line.trim();                 if let Some(value) = line.strip_prefix("sdk.dir=") {                     // Gradle properties escape the Windows separator.-                    return Some(PathBuf::from(value.replace("\\\\", "\\").replace("\\:", ":")));+                    return Some(PathBuf::from(+                        value.replace("\\\\", "\\").replace("\\:", ":"),+                    ));                 }             }             return None;
library/map/src/main/rust/shaders/fill.vert
diff --git a/library/map/src/main/rust/shaders/fill.vert b/library/map/src/main/rust/shaders/fill.vert

Diff truncated.