Modern Apps git

← Modern-Apps.git

various fixes

Commit
3ce476b98add41f5fbb6cd8b8149d662b1611ff8
Author
vayun-mathur <[email protected]>
When
2026-09-16 00:38 UTC (2 months ago)
Parents
24ab5fc

Diff

.github/ISSUE_TEMPLATE/bug_report.yml
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 21c2c9f9dc..50d761807b 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -26,6 +26,7 @@ body:         - contacts         - education         - email+        - emergency         - euicc         - everysync         - files
.github/ISSUE_TEMPLATE/feature_request.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlindex a9b6d40d7c..f3177467ef 100644--- a/.github/ISSUE_TEMPLATE/feature_request.yml+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -26,6 +26,7 @@ body:         - contacts         - education         - email+        - emergency         - euicc         - everysync         - files
.github/workflows/issue_labeler.yml
diff --git a/.github/workflows/issue_labeler.yml b/.github/workflows/issue_labeler.ymlindex f8bc7a75ec..74d93fe575 100644--- a/.github/workflows/issue_labeler.yml+++ b/.github/workflows/issue_labeler.yml@@ -21,7 +21,7 @@ jobs:              if (match && match[1]) {               const selectedApp = match[1].trim().toLowerCase();-              const validApps = ['alchemist', 'appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'musicbrainz', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'tools:holidaygen', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];+              const validApps = ['alchemist', 'appstore', 'arrows', 'astronomy', 'auto', 'backup', 'calculator', 'calendar', 'camera', 'cast', 'chess', 'clock', 'code', 'communicate', 'contacts', 'education', 'email', 'emergency', 'euicc', 'everysync', 'files', 'findfamily', 'flashcards', 'fooddelivery', 'health', 'hub', 'keyboard', 'launcher', 'logicgate', 'logviewer', 'maps', 'measure', 'minesweeper', 'music', 'musicbrainz', 'networklocation', 'nonogram', 'notes', 'office', 'openassistant', 'passwords', 'pdf', 'photos', 'pipes', 'parentalcontrols', 'screentime', 'setupwizard', 'share', 'solitaire', 'speech', 'sudoku', 'taxi', 'things', 'tools:holidaygen', 'translate', 'travel', 'tuner', 'unblockjam', 'updater', 'vpn', 'watch', 'voxels', 'weather', 'web', 'wordmaker', 'youpipe'];                if (validApps.includes(selectedApp)) {                 await github.rest.issues.addLabels({
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 7f4b4019f6..f4b6b6a7a7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2328,6 +2328,7 @@ name = "ml_vulkan" version = "0.1.0" dependencies = [  "anyhow",+ "ash",  "jni",  "log",  "onnx-vulkan",@@ -2551,7 +2552,6 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "onnx-vulkan" version = "0.0.1"-source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b" dependencies = [  "log",  "onnx-vulkan-core",@@ -2563,7 +2563,6 @@ dependencies = [ [[package]] name = "onnx-vulkan-core" version = "0.0.1"-source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b" dependencies = [  "anyhow",  "log",@@ -2574,7 +2573,6 @@ dependencies = [ [[package]] name = "onnx-vulkan-frontend" version = "0.0.1"-source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b" dependencies = [  "log",  "onnx-vulkan-core",@@ -2586,7 +2584,6 @@ dependencies = [ [[package]] name = "onnx-vulkan-tune" version = "0.0.1"-source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b" dependencies = [  "onnx-vulkan-core",  "onnx-vulkan-frontend",@@ -4112,7 +4109,6 @@ dependencies = [ [[package]] name = "vk-compute" version = "0.0.1"-source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b" dependencies = [  "anyhow",  "ash",
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 7af0724a7e..d9f673a31b 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -232,3 +232,13 @@ lto = true codegen-units = 1 strip = true panic = "abort"++# vk-compute c_char fix (ash 0.38): cargo only honours [patch] in the+# workspace root, so the override lives here; the member manifest documents+# it alongside the vendored tree per library/ml/src/main/rust/VENDORING.md.+[patch."https://github.com/automataIA/onnx-vulkan-rs"]+vk-compute = { path = "library/ml/src/main/rust/vendor/vk-compute" }+onnx-vulkan = { path = "library/ml/src/main/rust/vendor/onnx-vulkan" }+onnx-vulkan-core = { path = "library/ml/src/main/rust/vendor/onnx-vulkan-core" }+onnx-vulkan-frontend = { path = "library/ml/src/main/rust/vendor/onnx-vulkan-frontend" }+onnx-vulkan-tune = { path = "library/ml/src/main/rust/vendor/onnx-vulkan-tune" }
README.md
diff --git a/README.md b/README.mdindex 6612180b5b..d214110b70 100644--- a/README.md+++ b/README.md@@ -61,6 +61,7 @@ Though some apps may have exceptions, generally a 64-bit device running at least | **Contacts** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/contacts) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.contacts/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Contacts&packageName=com.vayunmathur.contacts&apk=contacts-release.apk) | | **Education** | MA-3 | [Homepage](https://ma.vayunmathur.com/apps/education) | In Progress | In Progress | | **Email** | MA-1 | [Homepage](https://ma.vayunmathur.com/apps/email) | [![F-Droid](https://img.shields.io/badge/F--Droid-Download-blue?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.email) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Email&packageName=com.vayunmathur.email&apk=email-release.apk) |+| **Emergency** | MA-C | [Homepage](https://ma.vayunmathur.com/apps/emergency) | In Progress | In Progress | | **eUICC** | MA-C | [Homepage](https://ma.vayunmathur.com/apps/euicc) | In Progress | In Progress | | **EverySync** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/everysync) | In Progress | In Progress | | **Files** | MA-2 | [Homepage](https://ma.vayunmathur.com/apps/files) | [![MA Repo](https://img.shields.io/badge/MA_Repo-Download-green?logo=f-droid&style=flat-square)](https://f-droid.org/packages/com.vayunmathur.files/) | [![Obtainium](https://img.shields.io/badge/Obtainium-Download-purple?style=flat-square)](https://api.vayunmathur.com/obtainium-link?name=Files&packageName=com.vayunmathur.files&apk=files-release.apk) |
analysis_build_err.txt
diff --git a/analysis_build_err.txt b/analysis_build_err.txtnew file mode 100644index 0000000000..6f0baab705--- /dev/null+++ b/analysis_build_err.txt@@ -0,0 +1,400 @@+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\astronomy\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\photos\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\office\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\weather\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\pdf\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\camera\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\maps\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\networklocation\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\euicc\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\passwords\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\vpn\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\library\e2ee-p2p\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\measure\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\communicate\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\youpipe\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: profiles for the non root package will be ignored, specify profiles at the workspace root:+package:   C:\Users\Vayun\Documents\code\Modern-Apps\share\src\main\rust\Cargo.toml+workspace: C:\Users\Vayun\Documents\code\Modern-Apps\Cargo.toml+warning: C:\Users\Vayun\Documents\code\Modern-Apps\third_party\betocore\crypto_provider_rustcrypto\Cargo.toml: `default-features` is ignored for rand, since `default-features` was not specified for `workspace.dependencies.rand`, this could become a hard error in the future+    Checking ml_vulkan v0.1.0 (C:\Users\Vayun\Documents\code\Modern-Apps\library\ml\src\main\rust)+error[E0432]: unresolved import `ash`+  --> library\ml\src\main\rust\src\device.rs:29:5+   |+29 | use ash::{Entry, vk};+   |     ^^^ use of unresolved module or unlinked crate `ash`+   |+   = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0432]: unresolved import `super::vulkan_session::KvCache`+  --> library\ml\src\main\rust\src\jni_bridge.rs:61:41+   |+61 | use super::vulkan_session::{GpuSession, KvCache};+   |                                         ^^^^^^^ no `KvCache` in `vulkan_session`++error[E0433]: cannot find `GpuTensor` in `onnx_vulkan`+   --> library\ml\src\main\rust\src\vulkan_session.rs:101:49+    |+101 |             inputs.into_iter().map(onnx_vulkan::GpuTensor::from).collect();+    |                                                 ^^^^^^^^^ could not find `GpuTensor` in `onnx_vulkan`+    |+help: an enum with a similar name exists+    |+101 -             inputs.into_iter().map(onnx_vulkan::GpuTensor::from).collect();+101 +             inputs.into_iter().map(onnx_vulkan::Tensor::from).collect();+    |++error[E0425]: cannot find type `GpuTensor` in crate `onnx_vulkan`+   --> library\ml\src\main\rust\src\vulkan_session.rs:100:42+    |+100 |         let gpu_inputs: Vec<onnx_vulkan::GpuTensor> =+    |                                          ^^^^^^^^^+    |+   ::: C:\Users\Vayun\.cargo\git\checkouts\onnx-vulkan-rs-91074aa5a2270394\c3aa968\crates\onnx-vulkan-core\src\device.rs:36:1+    |+ 36 | pub enum Tensor<'a> {+    | ------------------- similarly named enum `Tensor` defined here+    |+help: an enum with a similar name exists+    |+100 -         let gpu_inputs: Vec<onnx_vulkan::GpuTensor> =+100 +         let gpu_inputs: Vec<onnx_vulkan::Tensor> =+    |++error[E0425]: cannot find function `probe_json` in module `probe`+   --> library\ml\src\main\rust\src\jni_bridge.rs:165:47+    |+165 |         jstring_or_null(&mut env, Some(probe::probe_json()))+    |                                               ^^^^^^^^^^ not found in `probe`++error[E0308]: mismatched types+  --> library\ml\src\main\rust\src\vulkan_session.rs:66:60+   |+66 |         onnx_vulkan::Error::Load(msg) => VulcanError::Load(msg),+   |                                          ----------------- ^^^ expected `String`, found `Error`+   |                                          |+   |                                          arguments to this enum variant are incorrect+   |+note: tuple variant defined here+  --> library\ml\src\main\rust\src\vulkan_session.rs:25:5+   |+25 |     Load(String),+   |     ^^^^+help: try using a conversion method+   |+66 |         onnx_vulkan::Error::Load(msg) => VulcanError::Load(msg.to_string()),+   |                                                               ++++++++++++++error[E0599]: no associated function or constant named `from_bytes` found for struct `Session` in the current scope+   --> library\ml\src\main\rust\src\vulkan_session.rs:81:45+    |+ 81 |         let session = onnx_vulkan::Session::from_bytes(bytes, base_dir).map_err(map_native_error)?;+    |                                             ^^^^^^^^^^ associated function or constant not found in `Session`+    |+note: if you're trying to build a new `Session` consider using one of the following associated functions:+      Session::load+      Session::load_from_bytes+   --> C:\Users\Vayun\.cargo\git\checkouts\onnx-vulkan-rs-91074aa5a2270394\c3aa968\crates\onnx-vulkan\src\lib.rs:147:5+    |+147 |     pub fn load(path: impl AsRef<Path>) -> Result<Self> {+    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+...+154 |     pub fn load_from_bytes(bytes: &[u8], base_dir: Option<&Path>) -> Result<Self> {+    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+help: there is an associated function `load_from_bytes` with a similar name+    |+ 81 |         let session = onnx_vulkan::Session::load_from_bytes(bytes, base_dir).map_err(map_native_error)?;+    |                                             +++++++error[E0599]: the method `into_iter` exists for struct `Run<'_>`, but its trait bounds were not satisfied+   --> library\ml\src\main\rust\src\vulkan_session.rs:104:14+    |+103 | /         gpu_outputs+104 | |             .into_iter()+    | |             -^^^^^^^^^ method cannot be called on `Run<'_>` due to unsatisfied trait bounds+    | |_____________|+    |+    |+   ::: C:\Users\Vayun\.cargo\git\checkouts\onnx-vulkan-rs-91074aa5a2270394\c3aa968\crates\onnx-vulkan\src\lib.rs:726:1+    |+726 |   pub struct Run<'a> {+    |   ------------------ doesn't satisfy `Run<'_>: IntoIterator` or `Run<'_>: Iterator`+    |+    = note: the following trait bounds were not satisfied:+            `Run<'_>: Iterator`+            which is required by `Run<'_>: IntoIterator`+            `&Run<'_>: Iterator`+            which is required by `&Run<'_>: IntoIterator`+            `&mut Run<'_>: Iterator`+            which is required by `&mut Run<'_>: IntoIterator`++error[E0277]: the trait bound `VulcanError: From<Infallible>` is not satisfied+   --> library\ml\src\main\rust\src\vulkan_session.rs:105:27+    |+105 |             .map(|tensor| HostTensor::try_from(tensor).map_err(VulcanError::from))+    |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound+    |+help: the trait `From<Infallible>` is not implemented for `VulcanError`+      but trait `From<TensorError>` is implemented for it+   --> library\ml\src\main\rust\src\vulkan_session.rs:37:14+    |+ 37 |     Tensor(#[from] TensorError),+    |              ^^^^+    = help: for that trait implementation, expected `TensorError`, found `Infallible`++error[E0277]: the trait bound `VulcanError: From<Infallible>` is not satisfied+   --> library\ml\src\main\rust\src\vulkan_session.rs:105:64+    |+105 |             .map(|tensor| HostTensor::try_from(tensor).map_err(VulcanError::from))+    |                                                                ^^^^^^^^^^^ unsatisfied trait bound+    |+help: the trait `From<Infallible>` is not implemented for `VulcanError`+      but trait `From<TensorError>` is implemented for it+   --> library\ml\src\main\rust\src\vulkan_session.rs:37:14+    |+ 37 |     Tensor(#[from] TensorError),+    |              ^^^^+    = help: for that trait implementation, expected `TensorError`, found `Infallible`++error[E0599]: no method named `plan_stats` found for reference `&Session` in the current scope+   --> library\ml\src\main\rust\src\vulkan_session.rs:115:78+    |+115 |                 Some(session) => format!("key={} plan={}", self.key, session.plan_stats()),+    |                                                                              ^^^^^^^^^^ method not found in `&Session`++error[E0061]: this function takes 2 arguments but 0 arguments were supplied+   --> library\ml\src\main\rust\src\vulkan_session.rs:151:20+    |+151 |             cache: onnx_vulkan::KvCache::new(),+    |                    ^^^^^^^^^^^^^^^^^^^^^^^^^-- two arguments of type `&Session` and `usize` are missing+    |+note: associated function defined here+   --> C:\Users\Vayun\.cargo\git\checkouts\onnx-vulkan-rs-91074aa5a2270394\c3aa968\crates\onnx-vulkan\src\lib.rs:634:12+    |+634 |     pub fn new(session: &Session, max_seq_len: usize) -> Result<Self> {+    |            ^^^+help: provide the arguments+    |+151 |             cache: onnx_vulkan::KvCache::new(/* &Session */, /* usize */),+    |                                              +++++++++++++++++++++++++++++error[E0308]: mismatched types+   --> library\ml\src\main\rust\src\vulkan_session.rs:151:20+    |+151 |             cache: onnx_vulkan::KvCache::new(),+    |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `KvCache`, found `Result<KvCache, Error>`+    |+    = note: expected struct `KvCache`+                 found enum `Result<KvCache, onnx_vulkan::Error>`+help: consider using `Result::expect` to unwrap the `Result<KvCache, onnx_vulkan::Error>` value, panicking if the value is a `Result::Err`+    |+151 |             cache: onnx_vulkan::KvCache::new().expect("REASON"),+    |                                               +++++++++++++++++++error[E0308]: mismatched types+    --> library\ml\src\main\rust\src\jni_bridge.rs:78:20+     |+  78 |     env.get_string(value)+     |         ---------- ^^^^^ expected `&JString<'_>`, found `JString<'_>`+     |         |+     |         arguments to this method are incorrect+     |+note: method defined here+    --> C:\Users\Vayun\.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\jni-0.21.1\src\wrapper\jnienv.rs:1629:12+     |+1629 |     pub fn get_string<'other_local: 'obj_ref, 'obj_ref>(+     |            ^^^^^^^^^^+help: consider borrowing here+     |+  78 |     env.get_string(&value)+     |                    +++error[E0061]: this function takes 3 arguments but 2 arguments were supplied+   --> library\ml\src\main\rust\src\jni_bridge.rs:184:15+    |+184 |         match GpuSession::load(&bytes, &tag) {+    |               ^^^^^^^^^^^^^^^^         ---- argument #2 of type `Option<&str>` is missing+    |+note: associated function defined here+   --> library\ml\src\main\rust\src\vulkan_session.rs:80:12+    |+ 80 |     pub fn load(bytes: &[u8], base_dir: Option<&str>, key: &str) -> Result<Self, VulcanError> {+    |            ^^^^               ----------------------+help: provide the argument+    |+184 |         match GpuSession::load(&bytes, /* Option<&str> */, &tag) {+    |                                        +++++++++++++++++++++error[E0599]: no associated function or constant named `preflight` found for struct `GpuSession` in the current scope+   --> library\ml\src\main\rust\src\jni_bridge.rs:204:41+    |+204 |         let summary = match GpuSession::preflight(&bytes) {+    |                                         ^^^^^^^^^ associated function or constant not found in `GpuSession`+    |+   ::: library\ml\src\main\rust\src\vulkan_session.rs:52:1+    |+ 52 | pub struct GpuSession {+    | --------------------- associated function or constant `preflight` not found for this struct+    |+note: if you're trying to build a new `GpuSession`, consider using `GpuSession::load` which returns `Result<GpuSession, VulcanError>`+   --> library\ml\src\main\rust\src\vulkan_session.rs:80:5+    |+ 80 |     pub fn load(bytes: &[u8], base_dir: Option<&str>, key: &str) -> Result<Self, VulcanError> {+    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^++error[E0599]: no associated function or constant named `load_path` found for struct `GpuSession` in the current scope+   --> library\ml\src\main\rust\src\jni_bridge.rs:224:27+    |+224 |         match GpuSession::load_path(&path) {+    |                           ^^^^^^^^^ associated function or constant not found in `GpuSession`+    |+   ::: library\ml\src\main\rust\src\vulkan_session.rs:52:1+    |+ 52 | pub struct GpuSession {+    | --------------------- associated function or constant `load_path` not found for this struct+    |+note: if you're trying to build a new `GpuSession`, consider using `GpuSession::load` which returns `Result<GpuSession, VulcanError>`+   --> library\ml\src\main\rust\src\vulkan_session.rs:80:5+    |+ 80 |     pub fn load(bytes: &[u8], base_dir: Option<&str>, key: &str) -> Result<Self, VulcanError> {+    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^++error[E0308]: mismatched types+   --> library\ml\src\main\rust\src\jni_bridge.rs:263:71+    |+263 |         let output = with_session(handle, None, |session| session.run(&input).ok());+    |                                                                   --- ^^^^^^ expected `Vec<HostTensor>`, found `&Vec<u8>`+    |                                                                   |+    |                                                                   arguments to this method are incorrect+    |+    = note: expected struct `Vec<tensors::HostTensor>`+            found reference `&Vec<u8>`+note: method defined here+   --> library\ml\src\main\rust\src\vulkan_session.rs:92:12+    |+ 92 |     pub fn run(&self, inputs: Vec<HostTensor>) -> Result<Vec<HostTensor>, VulcanError> {+    |            ^^^        -----------------------++error[E0308]: mismatched types+   --> library\ml\src\main\rust\src\jni_bridge.rs:264:34+    |+264 |         jbytes_or_null(&mut env, output)+    |         --------------           ^^^^^^ expected `Option<Vec<u8>>`, found `Option<Vec<HostTensor>>`+    |         |+    |         arguments to this function are incorrect+    |+    = note: expected enum `Option<Vec<u8>>`+               found enum `Option<Vec<tensors::HostTensor>>`+note: function defined here+   --> library\ml\src\main\rust\src\jni_bridge.rs:97:4+    |+ 97 | fn jbytes_or_null(env: &mut JNIEnv, data: Option<Vec<u8>>) -> jbyteArray {+    |    ^^^^^^^^^^^^^^                   ---------------------++error[E0599]: no method named `output_shapes_json` found for mutable reference `&mut GpuSession` in the current scope+   --> library\ml\src\main\rust\src\jni_bridge.rs:278:26+    |+278 |             Some(session.output_shapes_json())+    |                          ^^^^^^^^^^^^^^^^^^ method not found in `&mut GpuSession`++error[E0599]: no method named `output_names_json` found for mutable reference `&mut GpuSession` in the current scope+   --> library\ml\src\main\rust\src\jni_bridge.rs:293:70+    |+293 |         let json = with_session(handle, None, |session| Some(session.output_names_json()));+    |                                                                      ^^^^^^^^^^^^^^^^^ method not found in `&mut GpuSession`++error[E0599]: no method named `create_kv` found for mutable reference `&mut GpuSession` in the current scope+   --> library\ml\src\main\rust\src\jni_bridge.rs:310:27+    |+310 |             match session.create_kv(max_tokens) {+    |                           ^^^^^^^^^ method not found in `&mut GpuSession`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:142:16+    |+142 |     instance: &ash::Instance,+    |                ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:165:16+    |+165 |     instance: &ash::Instance,+    |                ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:194:45+    |+194 | fn create_instance(entry: &Entry) -> Result<ash::Instance, DeviceError> {+    |                                             ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:207:16+    |+207 |     instance: &ash::Instance,+    |                ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:249:15+    |+249 |     instance: ash::Instance,+    |               ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:251:14+    |+251 |     logical: ash::Device,+    |              ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++error[E0433]: cannot find module or crate `ash` in this scope+   --> library\ml\src\main\rust\src\device.rs:260:37+    |+260 |     pub const fn logical(&self) -> &ash::Device {+    |                                     ^^^ use of unresolved module or unlinked crate `ash`+    |+    = help: if you wanted to use a crate named `ash`, use `cargo add ash` to add it to your `Cargo.toml`++Some errors have detailed explanations: E0061, E0277, E0308, E0425, E0432, E0433, E0599.+For more information about an error, try `rustc --explain E0061`.+error: could not compile `ml_vulkan` (lib) due to 29 previous errors
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 b71d65ec20..d0dec5823a 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -73,11 +73,16 @@ private val KNOWN_RUST_ABIS = listOf(  *                   the modules that need a second ABI pay for the extra cargo build;  *                   pass [ABI_ARMV7] for libraries consumed by an app that sets  *                   `nativeAbis { armv7 = true }`.+ * @param features   Cargo features to enable via `--features`. Resolved to a plain+ *                   String list at configuration time so the build stays+ *                   configuration-cache compatible (only the strings cross into+ *                   the task action, never the Project).  */ fun Project.rustNativeLib(     crate: String,     remapLabel: String = crate,     extraAbis: List<String> = emptyList(),+    features: List<String> = emptyList(), ) {     // Serialize cargoBuild across all Rust modules to avoid concurrent rustup installs.     val rustLock = gradle.sharedServices.registerIfAbsent(@@ -117,6 +122,11 @@ fun Project.rustNativeLib(             )     } +    // Config-cache compatible: snapshot to plain Strings at configuration time so+    // only the strings (never the Project) cross into the task actions below.+    val cargoFeatureArgs: List<String> =+        if (features.isNotEmpty()) listOf("--features", features.joinToString(",")) else emptyList()+     val perAbi = rustAbis.map { abi ->         val (abiDir, triple) = abi         tasks.register<Exec>("cargoBuild_${abiDir.replace('-', '_')}") {@@ -153,6 +163,17 @@ fun Project.rustNativeLib(             // Same staleness hazard as shaders above: without this the task stays up             // to date and the old bindings ship.             file("src/main/rust/schema").takeIf { it.isDirectory }?.let { inputs.dir(it) }+            // Whole-crate safety net: track every source under src/main/rust so ANY+            // rust change invalidates cargoBuild - crucially the vendored dependency+            // crates under vendor/ (e.g. :library:ml's vendor/onnx-vulkan-core), which+            // the path-specific inputs above do NOT cover. Before this, editing a+            // vendored crate left the task UP-TO-DATE and shipped a stale .so. Exclude+            // target/ because cargo writes this task's own .so there; folding build+            // output back in as an input means the task can never be up to date. The+            // FileTree is a FileCollection resolved at configuration time, so only the+            // file set (never the Project) crosses into the task action.+            inputs.files(fileTree("src/main/rust") { exclude("target/**") })+                .withPropertyName("rustCrateTree")             // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)             inputs.file(rootProject.file("Cargo.toml"))             inputs.file(rootProject.file("Cargo.lock"))@@ -205,7 +226,15 @@ fun Project.rustNativeLib(             }             environment("CARGO_INCREMENTAL", "0") -            commandLine("$cargoBin/cargo$exeExt", "build", "--locked", "--release", "--target", triple)+            commandLine(+                "$cargoBin/cargo$exeExt",+                "build",+                "--locked",+                "--release",+                "--target",+                triple,+                *cargoFeatureArgs.toTypedArray(),+            )              doLast {                 destSo.parentFile.mkdirs()
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.ktindex 5462c71ea7..cb10f97e35 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -6,6 +6,8 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.MutableIntState+import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue@@ -76,10 +78,19 @@ internal class CameraScreenState(     val panoCurrentAngle: Float,     val panoDirection: Int,     val panoPitch: Float,+    // Composition-local state that must OUTLIVE this holder: rememberCameraScreenState+    // recreates the holder whenever any collected value changes (roll, zoom, ...), which+    // is many times a second. These are backed by stable remember{}s so the portrait mask+    // survives long enough for the preview to render it, and the open settings pane and+    // icon rotation don't reset. Passing the backing state in (rather than declaring+    // mutableStateOf here) means every recreated holder shares the same instance.+    activeSettingState: MutableState<CameraSetting?>,+    maskBitmapState: MutableState<Bitmap?>,+    deviceRotationState: MutableIntState, ) {-    var activeSetting by mutableStateOf<CameraSetting?>(null)-    var maskBitmap by mutableStateOf<Bitmap?>(null)-    var deviceRotation by mutableIntStateOf(0)+    var activeSetting by activeSettingState+    var maskBitmap by maskBitmapState+    var deviceRotation by deviceRotationState      val isPhotoType get() = cameraMode in listOf(CameraMode.PHOTO, CameraMode.PORTRAIT, CameraMode.PANORAMA, CameraMode.PHOTOSPHERE)     val isSloMo get() = cameraMode == CameraMode.SLOW_MO@@ -164,6 +175,13 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen     val panoDirection by viewModel.panoramaEngine.sweepDirection.collectAsState()     val panoPitch by viewModel.panoramaEngine.currentPitch.collectAsState() +    // Kept OUTSIDE the remember(keys) below so they survive holder recreation. Without this+    // the portrait bokeh mask (written from BokehAnalyzer's background thread) is reset to+    // null every time a collected value like roll changes, and the preview never blurs.+    val activeSettingState = remember { mutableStateOf<CameraSetting?>(null) }+    val maskBitmapState = remember { mutableStateOf<Bitmap?>(null) }+    val deviceRotationState = remember { mutableIntStateOf(0) }+     return remember(         cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, isRecording, recordingDuration,         timerCountdown, qrResult, aspectRatio, zoomRatio, mirrorFront, timerDuration,@@ -229,6 +247,9 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen             panoCurrentAngle = panoCurrentAngle,             panoDirection = panoDirection,             panoPitch = panoPitch,+            activeSettingState = activeSettingState,+            maskBitmapState = maskBitmapState,+            deviceRotationState = deviceRotationState,         )     } }
emergency/build.gradle.kts
diff --git a/emergency/build.gradle.kts b/emergency/build.gradle.ktsnew file mode 100644index 0000000000..a3c3ad8513--- /dev/null+++ b/emergency/build.gradle.kts@@ -0,0 +1,25 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "emergency"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.emergency"+    }+}++dependencies {+    // Read-only Personal Health Record (FHIR) access, to surface allergies and current+    // medications from Health Connect on the view screen. Same client the health app uses.+    implementation(libs.androidx.connect.client)++    // Contact-URI serialize/parse tests call android.net.Uri.parse, which the unit-test stub+    // android.jar does not implement ("not mocked"). Robolectric supplies the framework+    // shadows so those round-trips can be asserted on the JVM; same reason pdf uses it.+    testImplementation(libs.robolectric)+}
emergency/src/main/AndroidManifest.xml
diff --git a/emergency/src/main/AndroidManifest.xml b/emergency/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..06c3c9724d--- /dev/null+++ b/emergency/src/main/AndroidManifest.xml@@ -0,0 +1,296 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">+    <!--+      A like-for-like replacement for GrapheneOS's EmergencyInfo+      (platform_packages_apps_EmergencyInfo, package com.android.emergency), namespaced to+      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.++      Privileged-only declarations (MANAGE_USERS, WRITE_SECURE_SETTINGS, CALL_PRIVILEGED,+      READ_PRIVILEGED_PHONE_STATE) follow the parentalcontrols/screentime precedent: declared+      with ProtectedPermissions ignored, used only inside runCatching with an explicit denied+      path. They stay inert until the MAOS build promotes this app; nothing crashes without+      them. The one deliberate omission is EmergencyDialerTrampoline (DIAL_EMERGENCY), which+      GrapheneOS itself ships disabled - we delegate call placement to Settings, we are not+      a dialer.+    -->+    <!-- Countdown vibration waveform during the SOS countdown. -->+    <uses-permission android:name="android.permission.VIBRATE" />+    <!-- The SOS receiver fires the call broadcast from the background alarm. -->+    <uses-permission android:name="android.permission.START_ACTIVITIES_FROM_BACKGROUND" />+    <!-- The SOS countdown runs as a foreground service with its notification. -->+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <!-- specialUse foreground subtype for the SOS countdown service. -->+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />+    <!-- Reads the SIM emergency-number list so the SOS screen names the real number. -->+    <uses-permission android:name="android.permission.READ_PHONE_STATE" />+    <!-- Privileged half of emergency-number lookup. Inert without priv-app promotion. -->+    <uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"+        tools:ignore="ProtectedPermissions" />+    <!-- Places the fallback emergency call when Settings' emergency provider is absent. -->+    <uses-permission android:name="android.permission.CALL_PHONE" />+    <!-- Guards the gesture provider, mirroring GrapheneOS. Inert without promotion. -->+    <uses-permission android:name="android.permission.CALL_PRIVILEGED"+        tools:ignore="ProtectedPermissions" />+    <!-- Emergency contacts are read from the contacts provider. Runtime grant. -->+    <uses-permission android:name="android.permission.READ_CONTACTS" />+    <!-- Owner name/icon on the view screen. Graceful fallback without it. -->+    <uses-permission android:name="android.permission.MANAGE_USERS"+        tools:ignore="ProtectedPermissions" />+    <!-- Gesture provider persists EMERGENCY_GESTURE_* to Settings.Secure. Priv-only. -->+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"+        tools:ignore="ProtectedPermissions" />+    <!-- The SOS alarm must fire at the exact countdown end. -->+    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />+    <!-- Re-arms nothing persistent, but the countdown alarm must survive reboot windows. -->+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+    <!-- SOS countdown and restriction-trip notices. A normal runtime permission. -->+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />++    <!--+      Read-only Personal Health Record access, to surface allergies and current medications from+      Health Connect on the view card. Requested from the edit screen and allowed to be refused;+      only grantable on Android 15 with an updated Health Connect module, so on older devices the+      card simply shows the stored fields. Mirrors the health app's medical read permissions.+    -->+    <uses-permission android:name="android.permission.health.READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES" />+    <uses-permission android:name="android.permission.health.READ_MEDICAL_DATA_MEDICATIONS" />++    <!-- Not requested, deliberately: no INTERNET. Medical info, contacts and the SOS+         countdown are all local; the call itself goes through the telephony stack. -->+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"+        tools:node="remove" />++    <application+        android:allowBackup="false"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:defaultToDeviceProtectedStorage="true"+        android:directBootAware="true"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <!--+          Read-only view: medical info + emergency contacts, reachable over the lock screen.+          Answers android.telephony.action.EMERGENCY_ASSISTANCE like GrapheneOS's+          ViewInfoActivity. No launcher entry - reached from Settings, the lock screen and+          the SOS flow, the same way EmergencyInfo is.+        -->+        <activity+            android:name=".ui.ViewInfoActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:label="@string/app_name"+            android:launchMode="singleTask"+            android:showWhenLocked="true"+            android:taskAffinity="com.android.settings"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.telephony.action.EMERGENCY_ASSISTANCE" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+        </activity>++        <!--+          Edit entry: contacts + medical info. Answers android.settings.EDIT_EMERGENCY_INFO+          like GrapheneOS's EditInfoActivity.+        -->+        <activity+            android:name=".ui.EditInfoActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:label="@string/app_name"+            android:launchMode="singleTask"+            android:taskAffinity="com.android.settings"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.settings.EDIT_EMERGENCY_INFO" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+        </activity>++        <!--+          Settings first-run suggestion, independent of the edit activity so it can be+          disabled once any info or contact is set (see EmergencyRepository). Mirrors+          GrapheneOS's EditInfoSuggestion alias.+        -->+        <activity-alias+            android:name=".ui.EditInfoSuggestion"+            android:exported="true"+            android:label="@string/app_name"+            android:targetActivity=".ui.EditInfoActivity">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="com.android.settings.suggested.category.FIRST_IMPRESSION" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.dismiss"+                android:value="11,15,30" />+            <meta-data+                android:name="com.android.settings.title"+                android:resource="@string/settings_suggestion_title" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/settings_suggestion_body" />+            <meta-data+                android:name="com.android.settings.icon"+                android:resource="@mipmap/ic_launcher" />+        </activity-alias>++        <!--+          The Settings > Safety & emergency row. Mirrors GrapheneOS's EmergencyInfoActivity+          alias: same IA_SETTINGS action, same ia.emergency category, same order and profile.+        -->+        <activity-alias+            android:name=".ui.EmergencyInfoAlias"+            android:exported="false"+            android:icon="@mipmap/ic_launcher"+            android:label="@string/app_name"+            android:targetActivity=".ui.EditInfoActivity">+            <intent-filter>+                <action android:name="com.android.settings.action.IA_SETTINGS" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+            <meta-data+                android:name="com.android.settings.category"+                android:value="com.android.settings.category.ia.emergency" />+            <meta-data+                android:name="com.android.settings.order"+                android:value="60" />+            <meta-data+                android:name="com.android.settings.icon"+                android:resource="@mipmap/ic_launcher" />+            <meta-data+                android:name="com.android.settings.icon_tintable"+                android:value="true" />+            <meta-data+                android:name="com.android.settings.summary"+                android:resource="@string/injection_summary_empty" />+            <meta-data+                android:name="com.android.settings.profile"+                android:value="primary_profile_only" />+        </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.+        -->+        <activity+            android:name=".ui.SosActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:excludeFromRecents="true"+            android:exported="false"+            android:launchMode="singleInstance"+            android:showWhenLocked="true"+            android:theme="@style/Theme.General" />++        <!--+          SOS countdown service: notification + exact alarm + vibration + warning sound.+          Not exported: started explicitly by the SOS screen and the receiver.+          specialUse, following screentime's FocusService: this is not an ongoing call+          (phoneCall type would need FOREGROUND_SERVICE_PHONE_CALL and misdescribes a+          countdown), it keeps the gesture countdown alive while the screen is off.+        -->+        <service+            android:name=".service.SosCountdownService"+            android:exported="false"+            android:foregroundServiceType="specialUse">+            <property+                android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+                android:value="Counts down to placing an emergency call so the gesture survives the screen turning off." />+        </service>++        <!--+          SOS outcomes: MAKE places the call (via Settings' emergency provider, falling back+          to an explicit emergency-call intent) and CANCEL stops the service. Not exported:+          both are explicit-class intents from our own notification, alarm and screen.+        -->+        <receiver+            android:name=".receiver.SosActionReceiver"+            android:exported="false">+            <intent-filter>+                <action android:name="com.vayunmathur.emergency.broadcast.MAKE_EMERGENCY_CALL" />+                <action android:name="com.vayunmathur.emergency.broadcast.CANCEL_EMERGENCY_COUNTDOWN" />+            </intent-filter>+        </receiver>++        <!-- Settings search indexing for the emergency rows. -->+        <provider+            android:name=".platform.EmergencySearchIndexablesProvider"+            android:authorities="com.vayunmathur.emergency"+            android:exported="true"+            android:grantUriPermissions="true"+            android:multiprocess="false"+            android:permission="android.permission.READ_SEARCH_INDEXABLES">+            <intent-filter>+                <action android:name="android.content.action.SEARCH_INDEXABLES_PROVIDER" />+            </intent-filter>+        </provider>++        <!-- Avatar photo sharing for the medical-info editor. -->+        <provider+            android:name="androidx.core.content.FileProvider"+            android:authorities="com.vayunmathur.emergency.files"+            android:exported="false"+            android:grantUriPermissions="true">+            <meta-data+                android:name="android.support.FILE_PROVIDER_PATHS"+                android:resource="@xml/file_paths" />+        </provider>++        <!--+          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.+        -->+        <provider+            android:name=".platform.GestureProvider"+            android:authorities="com.vayunmathur.emergency.gesture"+            android:exported="true"+            android:permission="android.permission.CALL_PRIVILEGED" />++        <!--+          Health Connect requires an app that reads medical data to answer the permissions+          rationale intent, and to expose a VIEW_PERMISSION_USAGE entry point. Both mirror the+          health app: the rationale screen can be empty, and the alias points Settings at it.+        -->+        <activity+            android:name=".ui.PermissionsRationaleActivity"+            android:exported="true">+            <intent-filter>+                <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />+            </intent-filter>+        </activity>++        <activity-alias+            android:name="ViewPermissionUsageActivity"+            android:exported="true"+            android:permission="android.permission.START_VIEW_PERMISSION_USAGE"+            android:targetActivity=".ui.PermissionsRationaleActivity">+            <intent-filter>+                <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />+                <category android:name="android.intent.category.HEALTH_PERMISSIONS" />+            </intent-filter>+        </activity-alias>+    </application>++    <!-- Avatar capture in the medical-info editor. -->+    <queries>+        <intent>+            <action android:name="android.media.action.IMAGE_CAPTURE" />+        </intent>+        <intent>+            <action android:name="android.intent.action.GET_CONTENT" />+            <data android:mimeType="image/*" />+        </intent>+    </queries>+</manifest>
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.ktnew file mode 100644index 0000000000..458d89e870--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyInfo.kt@@ -0,0 +1,62 @@+package com.vayunmathur.emergency.data++import android.graphics.Bitmap+import android.net.Uri++/**+ * The owner's identity details plus their emergency contacts.+ *+ * Allergies and medications are deliberately absent: they are read live from Health Connect+ * (see [com.vayunmathur.emergency.platform.HealthConnectMedical]), never typed in by hand.+ * Contacts are stored as `|`-separated `CommonDataKinds.Phone.CONTENT_URI` strings exactly+ * like `EmergencyContactsPreference.serialize` (`|` separator, legacy string-set guard on+ * read).+ */+data class EmergencyInfo(+    val name: String = "",+    val address: String = "",+    val bloodType: String = "",+    val organDonor: String = "",+    val contacts: List<EmergencyContact> = emptyList(),+) {+    /** True once anything a first responder could use has been entered. */+    fun hasAnythingSet(): Boolean =+        name.isNotBlank() || address.isNotBlank() || bloodType.isNotBlank() ||+            organDonor.isNotBlank() || contacts.isNotEmpty()+}++/** One emergency contact: the phone-table URI plus a snapshot for display. */+data class EmergencyContact(+    /** `ContactsContract.CommonDataKinds.Phone.CONTENT_URI` for the chosen number. */+    val phoneUri: Uri,+    val displayName: String,+    val phoneNumber: String,+    val phoneType: String,+    /** The contact's photo, or null when it has none. Never persisted; re-read onload. */+    val photo: Bitmap? = null,+)++/** Preference keys. Order matches the fields shown in the view/edit screens. */+object EmergencyKeys {+    const val NAME = "name"+    const val ADDRESS = "address"+    const val BLOOD_TYPE = "blood_type"+    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+}++/** `|` separator from `EmergencyContactsPreference`; quoted for split. */+const val CONTACT_SEPARATOR = "|"++/** Serializes contact URIs the GrapheneOS way: `uri|uri` with no trailing separator. */+fun serializeContacts(uris: List<Uri>): String = uris.joinToString(CONTACT_SEPARATOR) { it.toString() }++/** Splits a serialized contact string into URIs, dropping blanks. */+fun parseContactUris(serialized: String): List<Uri> =+    serialized.split(CONTACT_SEPARATOR).mapNotNull {+        val trimmed = it.trim()+        if (trimmed.isEmpty()) null else runCatching { Uri.parse(trimmed) }.getOrNull()+    }
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.ktnew file mode 100644index 0000000000..a823a060eb--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/EmergencyRepository.kt@@ -0,0 +1,166 @@+package com.vayunmathur.emergency.data++import android.content.ComponentName+import android.content.Context+import android.content.SharedPreferences+import android.content.pm.PackageManager+import android.net.Uri+import android.os.UserManager+import android.util.Log+import androidx.core.content.edit+import com.vayunmathur.emergency.platform.ContactReader+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.withContext++private const val TAG = "EmergencyRepository"++/**+ * Stores the owner's medical info and emergency contacts.+ *+ * Shape mirrors GrapheneOS: default SharedPreferences (not device-protected storage - the+ * direct-boot note below explains why), `|`-serialised contact URIs, re-validation of stored+ * URIs on every load with dead contacts pruned and re-persisted, and the Settings suggestion+ * alias disabled once anything is set (`PreferenceUtils.updateSettingsSuggestionState`).+ *+ * Direct-boot guard: contacts are never persisted while the user is locked+ * (`EmergencyContactsPreference.persistEmergencyContacts`), because contact resolution needs+ * the credential-encrypted contacts provider. Reads pre-unlock return whatever is already+ * stored without pruning.+ */+class EmergencyRepository private constructor(private val app: Context) {++    private val prefs: SharedPreferences by lazy {+        // Device-protected storage so the lock-screen view can read post-reboot pre-unlock;+        // contact URIs stored here are only *resolved* once unlocked (see load below).+        val device = app.createDeviceProtectedStorageContext()+        device.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+    }++    private val mutable = MutableStateFlow(EmergencyInfo())+    val info: StateFlow<EmergencyInfo> = mutable.asStateFlow()++    suspend fun load() = withContext(Dispatchers.IO) {+        val info = readStored()+        val resolved = if (isUnlocked()) resolveAndPrune(info) else info+        mutable.value = resolved+    }++    suspend fun saveInfo(+        name: String,+        address: String,+        bloodType: String,+        organDonor: 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()+    }++    /** 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)+        val contact = reader.read(phoneUri) ?: return@withContext false+        val current = mutable.value.contacts+        if (current.any { it.phoneUri == phoneUri }) return@withContext true+        persistUris(current.map { it.phoneUri } + phoneUri)+        mutable.value = mutable.value.copy(contacts = current + contact)+        updateSuggestionState()+        true+    }++    suspend fun removeContact(phoneUri: Uri) = withContext(Dispatchers.IO) {+        val current = mutable.value.contacts+        val next = current.filterNot { it.phoneUri == phoneUri }+        if (next.size == current.size) return@withContext+        persistUris(next.map { it.phoneUri })+        mutable.value = mutable.value.copy(contacts = next)+        updateSuggestionState()+    }++    private fun readStored(): EmergencyInfo {+        // Legacy guard (b/28194605): contacts were once a string set; a ClassCastException+        // means the stored value predates the `|` format and is ignored.+        val serialized = runCatching { prefs.getString(EmergencyKeys.CONTACTS, "") }+            .getOrElse {+                Log.w(TAG, "ignoring legacy contact storage", it)+                ""+            }.orEmpty()+        val uris = parseContactUris(serialized)+        // Pre-unlock the contacts cannot be resolved; carry the URIs with blank snapshots.+        val contacts = if (isUnlocked()) {+            ContactReader(app).readAll(uris)+        } else {+            uris.map { EmergencyContact(it, "", "", "") }+        }+        return EmergencyInfo(+            name = prefs.getString(EmergencyKeys.NAME, "").orEmpty(),+            address = prefs.getString(EmergencyKeys.ADDRESS, "").orEmpty(),+            bloodType = prefs.getString(EmergencyKeys.BLOOD_TYPE, "").orEmpty(),+            organDonor = prefs.getString(EmergencyKeys.ORGAN_DONOR, "").orEmpty(),+            contacts = contacts,+        )+    }++    /**+     * Re-validates stored URIs, dropping contacts deleted from the address book and+     * re-persisting when anything was pruned - GrapheneOS's `deserializeAndFilter`.+     */+    private fun resolveAndPrune(info: EmergencyInfo): EmergencyInfo {+        val uris = info.contacts.map { it.phoneUri }+        val resolved = ContactReader(app).readAll(uris)+        if (resolved.size != uris.size) {+            persistUris(resolved.map { it.phoneUri })+            return info.copy(contacts = resolved)+        }+        return info+    }++    private fun persistUris(uris: List<Uri>) {+        // Never persist pre-unlock: same guard as GrapheneOS.+        if (!isUnlocked()) return+        prefs.edit { putString(EmergencyKeys.CONTACTS, serializeContacts(uris)) }+    }++    private fun isUnlocked(): Boolean =+        app.getSystemService(UserManager::class.java)?.isUserUnlocked != false++    /**+     * Disables the Settings first-run suggestion once anything is set, re-enables when the+     * last detail is removed - GrapheneOS's `updateSettingsSuggestionState`.+     */+    private fun updateSuggestionState() {+        val state = if (mutable.value.hasAnythingSet()) {+            PackageManager.COMPONENT_ENABLED_STATE_DISABLED+        } else {+            PackageManager.COMPONENT_ENABLED_STATE_ENABLED+        }+        runCatching {+            app.packageManager.setComponentEnabledSetting(+                ComponentName(app, SUGGESTION_CLASS),+                state,+                PackageManager.DONT_KILL_APP,+            )+        }.onFailure { Log.w(TAG, "could not update the settings suggestion state", it) }+    }++    companion object {+        private const val PREFS = "emergency_info"+        private const val SUGGESTION_CLASS = "com.vayunmathur.emergency.ui.EditInfoSuggestion"++        @Volatile+        private var instance: EmergencyRepository? = null++        fun get(context: Context): EmergencyRepository =+            instance ?: synchronized(this) {+                instance ?: EmergencyRepository(context.applicationContext).also { instance = it }+            }+    }+}
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.ktnew file mode 100644index 0000000000..2de2766d07--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/data/ImportedMedical.kt@@ -0,0 +1,22 @@+package com.vayunmathur.emergency.data++/**+ * A single allergy read from Health Connect's Personal Health Record store.+ *+ * Read-only: unlike the free-text medical fields, these come from a provider or pharmacy sync+ * and are never edited here, so there is no id, onset date or FHIR round-trip - just what a+ * first responder needs to read off the screen.+ */+data class ImportedAllergy(+    val displayName: String,+    val criticality: AllergyCriticality,+    val reaction: String?,+)++/** A single current medication read from Health Connect. Read-only, like [ImportedAllergy]. */+data class ImportedMedication(+    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.ktnew file mode 100644index 0000000000..4dd43121de--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/domain/FhirMedicalParse.kt@@ -0,0 +1,134 @@+package com.vayunmathur.emergency.domain++import com.vayunmathur.emergency.data.AllergyCriticality+import com.vayunmathur.emergency.data.ImportedAllergy+import com.vayunmathur.emergency.data.ImportedMedication+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive++/**+ * Reads the display fields the emergency view needs out of FHIR R4 JSON.+ *+ * This is the read-only, emergency-scoped cousin of the health app's `FhirRecords`: that app+ * round-trips full `AllergyEntry`/`MedicationEntry` rows through Room, whereas here we only ever+ * show a name (and, for allergies, how bad the reaction is), so the parsing stops at the first+ * usable display string. Reading is forgiving on purpose - resources synced from a real health+ * system carry codings and extensions this never produces, and anything unrecognised is dropped+ * rather than throwing, exactly as `FhirRecords` does.+ *+ * Pure and Android-free so it can be unit-tested on the JVM; the Health Connect plumbing that+ * feeds it JSON lives in `platform/HealthConnectMedical`.+ */+object FhirMedicalParse {++    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    /** RxNorm, the one medication terminology Health Connect ships codings for. */+    private const val RXNORM_SYSTEM = "http://www.nlm.nih.gov/research/umls/rxnorm"++    /**+     * One `AllergyIntolerance` resource, or null when it is not one or has no usable name.+     *+     * Resolved (`clinicalStatus` inactive/resolved) allergies are dropped: an emergency card+     * should show what the patient is allergic to now, not what they have outgrown.+     */+    fun parseAllergy(data: String): ImportedAllergy? {+        val root = parse(data) ?: return null+        if (root.str("resourceType") != "AllergyIntolerance") return null+        if (!isActive(root["clinicalStatus"] as? JsonObject)) return null++        val code = root["code"] as? JsonObject+        val displayName = displayFrom(code) ?: return null++        val reaction = (root["reaction"] as? JsonArray)?.firstNotNullOfOrNull { entry ->+            ((entry as? JsonObject)?.get("manifestation") as? JsonArray)+                ?.firstNotNullOfOrNull { conceptText(it as? JsonObject) }+        }++        return ImportedAllergy(+            displayName = displayName,+            criticality = criticalityFrom(root.str("criticality")),+            reaction = reaction,+        )+    }++    /**+     * One current medication, or null when the resource is not a medication, has no usable+     * name, or is not currently being taken.+     *+     * Both `MedicationRequest` and `MedicationStatement` appear in the medications category;+     * either is accepted as long as its status marks it current (active / intended /+     * on-hold for a request; active / intended for a statement). Completed or stopped courses+     * are dropped - "current medication" is what the user asked for.+     */+    fun parseCurrentMedication(data: String): ImportedMedication? {+        val root = parse(data) ?: return null+        val type = root.str("resourceType")+        if (type != "MedicationRequest" && type != "MedicationStatement") return null+        if (!isCurrentMedicationStatus(root.str("status"))) return null++        val concept = root["medicationCodeableConcept"] as? JsonObject+        val displayName = displayFrom(concept) ?: return null+        return ImportedMedication(displayName = displayName)+    }++    /** High first, then low, then unknown - the order an emergency list should read in. */+    fun sortAllergies(allergies: List<ImportedAllergy>): List<ImportedAllergy> =+        allergies.sortedBy {+            when (it.criticality) {+                AllergyCriticality.High -> 0+                AllergyCriticality.Low -> 1+                AllergyCriticality.Unknown -> 2+            }+        }++    // --- helpers -------------------------------------------------------------++    private fun parse(data: String): JsonObject? =+        runCatching { json.parseToJsonElement(data) as? JsonObject }.getOrNull()++    /** A coded concept's best display: coding display (RxNorm first) → text → any coding display. */+    private fun displayFrom(concept: JsonObject?): String? {+        if (concept == null) return null+        val codings = concept["coding"] as? JsonArray+        val rxnorm = codings?.firstOrNull {+            (it as? JsonObject).str("system") == RXNORM_SYSTEM+        } as? JsonObject+        return rxnorm.str("display")+            ?: concept.str("text")+            ?: (codings?.firstOrNull() as? JsonObject).str("display")+    }++    private fun conceptText(concept: JsonObject?): String? {+        if (concept == null) return null+        return concept.str("text")+            ?: ((concept["coding"] as? JsonArray)?.firstOrNull() as? JsonObject).str("display")+    }++    /** True unless clinicalStatus explicitly says inactive or resolved. Absent status = active. */+    private fun isActive(clinicalStatus: JsonObject?): Boolean {+        val code = (clinicalStatus?.get("coding") as? JsonArray)+            ?.firstNotNullOfOrNull { (it as? JsonObject).str("code") }+            ?: return true+        return code != "inactive" && code != "resolved"+    }++    private fun isCurrentMedicationStatus(status: String?): Boolean = when (status) {+        "active", "intended", "on-hold" -> true+        // A statement uses a narrower set; "active"/"intended" already covered above.+        else -> false+    }++    private fun criticalityFrom(value: String?): AllergyCriticality = when (value) {+        "high" -> AllergyCriticality.High+        "low" -> AllergyCriticality.Low+        else -> AllergyCriticality.Unknown+    }++    private fun JsonObject?.str(key: String): String? {+        val primitive = this?.get(key) as? JsonPrimitive ?: return null+        return if (primitive.isString) primitive.content else null+    }+}
emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt b/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.ktnew file mode 100644index 0000000000..9c9cbbb51b--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/notifications/SosNotifications.kt@@ -0,0 +1,89 @@+package com.vayunmathur.emergency.notifications++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat+import com.vayunmathur.emergency.R+import com.vayunmathur.emergency.receiver.SosActionReceiver++/**+ * The SOS countdown notification.+ *+ * Mirrors GrapheneOS's `EmergencyActionForegroundService.buildCountDownNotification`: an+ * ongoing, high-importance alarm-category row naming the number about to be dialled, with a+ * cancel action that fires `CANCEL_EMERGENCY_COUNTDOWN` at our own receiver. Unlike+ * GrapheneOS's RemoteViews chronometer layout, this uses the platform `NotificationCompat`+ * countdown (`setUsesChronometer` + `setChronometerCountDown`) so there is no custom layout+ * to maintain - the semantics (counting down to the call, one-tap cancel) are identical.+ *+ * Posted by the foreground service (which owns the channel); also used for the content+ * intent target so tapping the row reopens the SOS screen.+ */+object SosNotifications {++    const val CHANNEL_ID = "emergency_sos"+    const val NOTIFICATION_ID = 0x112++    fun ensureChannel(context: Context) {+        val nm = context.getSystemService(NotificationManager::class.java) ?: return+        nm.createNotificationChannel(+            NotificationChannel(+                CHANNEL_ID,+                context.getString(R.string.sos_channel_name),+                NotificationManager.IMPORTANCE_HIGH,+            ).apply {+                description = context.getString(R.string.sos_channel_description)+            },+        )+    }++    fun countdown(+        context: Context,+        number: String,+        targetElapsedRealtime: Long,+        contentIntent: PendingIntent,+    ): Notification {+        val cancel = PendingIntent.getBroadcast(+            context,+            0,+            Intent(context, SosActionReceiver::class.java)+                .setAction(SosActionReceiver.ACTION_CANCEL_COUNTDOWN),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        return NotificationCompat.Builder(context, CHANNEL_ID)+            .setSmallIcon(android.R.drawable.ic_dialog_alert)+            .setContentTitle(context.getString(R.string.sos_title))+            .setContentText(context.getString(R.string.sos_notification_text, number))+            .setPriority(NotificationCompat.PRIORITY_HIGH)+            .setCategory(NotificationCompat.CATEGORY_ALARM)+            .setOngoing(true)+            .setAutoCancel(false)+            .setOnlyAlertOnce(true)+            .setContentIntent(contentIntent)+            .setUsesChronometer(true)+            .setChronometerCountDown(true)+            .setWhen(targetElapsedRealtime)+            .addAction(+                android.R.drawable.ic_delete,+                context.getString(R.string.sos_cancel),+                cancel,+            )+            .build()+    }++    /** Posts or updates the countdown row; never throws (a missing notice must not kill SOS). */+    fun notify(context: Context, notification: Notification) {+        ensureChannel(context)+        val nm = context.getSystemService(NotificationManager::class.java) ?: return+        runCatching { nm.notify(NOTIFICATION_ID, notification) }+    }++    fun cancel(context: Context) {+        val nm = context.getSystemService(NotificationManager::class.java) ?: return+        runCatching { nm.cancel(NOTIFICATION_ID) }+    }+}
emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.ktnew file mode 100644index 0000000000..566a12eed8--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/ContactReader.kt@@ -0,0 +1,85 @@+package com.vayunmathur.emergency.platform++import android.content.ContentUris+import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.net.Uri+import android.provider.ContactsContract+import android.util.Log+import com.vayunmathur.emergency.data.EmergencyContact+import java.io.ByteArrayInputStream++private const val TAG = "EmergencyContactReader"++/**+ * Reads emergency contacts from the contacts provider.+ *+ * Mirrors GrapheneOS's `EmergencyContactManager`: name, number, type label and photo are read+ * from the stored `CommonDataKinds.Phone.CONTENT_URI`; `isValid` re-checks that the URI still+ * resolves so contacts deleted from the address book can be pruned. Needs `READ_CONTACTS`+ * (a normal runtime grant); without it every read returns null and the UI must prompt.+ */+class ContactReader(private val context: Context) {++    /** Reads one contact, or null when the URI no longer resolves or access is denied. */+    fun read(phoneUri: Uri): EmergencyContact? {+        val cursor = runCatching {+            context.contentResolver.query(+                phoneUri,+                arrayOf(+                    ContactsContract.Contacts.DISPLAY_NAME,+                    ContactsContract.CommonDataKinds.Phone.NUMBER,+                    ContactsContract.CommonDataKinds.Phone.TYPE,+                    ContactsContract.CommonDataKinds.Phone.LABEL,+                    ContactsContract.Contacts.Photo.PHOTO_ID,+                ),+                null, null, null,+            )+        }.getOrElse {+            Log.w(TAG, "unable to read contact $phoneUri", it)+            return null+        } ?: return null+        cursor.use {+            if (!it.moveToNext()) return null+            val name = it.getString(0).orEmpty()+            val number = it.getString(1).orEmpty()+            if (number.isBlank()) return null+            val type = ContactsContract.CommonDataKinds.Phone.getTypeLabel(+                context.resources, it.getInt(2), it.getString(3),+            ).toString()+            val photo = readPhoto(it.getLong(4))+            return EmergencyContact(phoneUri, name, number, type, photo)+        }+    }++    /** Reads all URIs, silently dropping ones that no longer resolve. */+    fun readAll(uris: List<Uri>): List<EmergencyContact> = uris.mapNotNull { read(it) }++    /** True when [phoneUri] is non-null and still resolves to a number. */+    fun isValid(phoneUri: Uri?): Boolean {+        if (phoneUri == null) return false+        val cursor = runCatching {+            context.contentResolver.query(phoneUri, null, null, null, null)+        }.getOrElse {+            Log.w(TAG, "unable to validate contact $phoneUri", it)+            return false+        } ?: return false+        cursor.use { return it.moveToFirst() }+    }++    private fun readPhoto(photoId: Long): Bitmap? {+        if (photoId <= 0) return null+        val photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, photoId)+        val cursor = runCatching {+            context.contentResolver.query(+                photoUri, arrayOf(ContactsContract.Contacts.Photo.PHOTO), null, null, null,+            )+        }.getOrNull() ?: return null+        cursor.use {+            if (!it.moveToNext()) return null+            val data = it.getBlob(0) ?: return null+            return runCatching { BitmapFactory.decodeStream(ByteArrayInputStream(data)) }.getOrNull()+        }+    }+}
emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.ktnew file mode 100644index 0000000000..e6c11cbe56--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyNumberLookup.kt@@ -0,0 +1,61 @@+package com.vayunmathur.emergency.platform++import android.content.Context+import android.content.pm.PackageManager+import android.telephony.SubscriptionManager+import android.telephony.TelephonyManager+import android.telephony.emergency.EmergencyNumber+import android.util.Log+import androidx.core.content.getSystemService++private const val TAG = "EmergencyNumberLookup"++/**+ * Picks the number the SOS countdown is about to dial.+ *+ * Mirrors `EmergencyNumberUtils.getPoliceNumber`: the user override (see [GestureProvider])+ * wins; otherwise the first police-category number from the SIM emergency-number list+ * (database-sourced entries preferred); otherwise the `112` fallback. Needs+ * `READ_PHONE_STATE` for `getEmergencyNumberList` - without the grant (or without+ * telephony at all) this returns the fallback rather than failing.+ */+class EmergencyNumberLookup(private val context: Context) {++    fun policeNumber(override: String?): String {+        if (!override.isNullOrBlank()) return override+        return defaultPoliceNumber()+    }++    fun defaultPoliceNumber(): String {+        if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {+            return FALLBACK_NUMBER+        }+        if (!hasPhoneStateGrant()) return FALLBACK_NUMBER+        val telecom = context.getSystemService<TelephonyManager>() ?: return FALLBACK_NUMBER+        val lists = runCatching {+            telecom.getEmergencyNumberList(EmergencyNumber.EMERGENCY_SERVICE_CATEGORY_POLICE)+        }.getOrElse {+            Log.w(TAG, "could not read the emergency-number list", it)+            return FALLBACK_NUMBER+        }+        if (lists.isNullOrEmpty()) return FALLBACK_NUMBER+        val subId = SubscriptionManager.getDefaultSubscriptionId()+        val numbers = lists[subId] ?: lists.values.firstOrNull().orEmpty()+        if (numbers.isEmpty()) return FALLBACK_NUMBER+        // Database-sourced entries are well-categorised; prefer them like SettingsLib does.+        val preferred = numbers.firstOrNull {+            EmergencyNumber.EMERGENCY_NUMBER_SOURCE_DATABASE in it.emergencyNumberSources+        } ?: numbers.first()+        return preferred.number.ifBlank { FALLBACK_NUMBER }+    }++    private fun hasPhoneStateGrant(): Boolean {+        val result = context.checkSelfPermission(android.Manifest.permission.READ_PHONE_STATE)+        return result == PackageManager.PERMISSION_GRANTED+    }++    companion object {+        /** SettingsLib `FALL_BACK_NUMBER`: the GSM emergency number, reachable everywhere. */+        const val FALLBACK_NUMBER = "112"+    }+}
emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencySearchIndexablesProvider.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencySearchIndexablesProvider.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencySearchIndexablesProvider.ktnew file mode 100644index 0000000000..b461db7298--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencySearchIndexablesProvider.kt@@ -0,0 +1,48 @@+package com.vayunmathur.emergency.platform++import android.content.ContentProvider+import android.content.ContentValues+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.Bundle++/**+ * Answers Settings' search-indexables query so the Safety & emergency rows are searchable.+ *+ * GrapheneOS's `EmergencySearchIndexablesProvider` serves static index data from resources;+ * ours serves an empty result: the rows themselves are declared in the manifest (IA_SETTINGS+ * injection + suggestion alias), which is what makes them resolve and rank. Returning an+ * empty cursor rather than throwing keeps Settings' indexer from logging failures against us.+ */+class EmergencySearchIndexablesProvider : ContentProvider() {++    override fun call(authority: String, method: String, arg: String?, extras: Bundle?): Bundle? =+        Bundle()++    override fun onCreate(): Boolean = true++    override fun query(+        uri: Uri,+        projection: Array<String>?,+        selection: String?,+        selectionArgs: Array<String>?,+        sortOrder: String?,+    ): Cursor = MatrixCursor(+        arrayOf("rank", "xmlResId", "className", "iconResId", "intentAction", "intentTargetPackage",+            "intentTargetClass", "key", "userId"),+    )++    override fun getType(uri: Uri): String? = null++    override fun insert(uri: Uri, values: ContentValues?): Uri? = null++    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0++    override fun update(+        uri: Uri,+        values: ContentValues?,+        selection: String?,+        selectionArgs: Array<String>?,+    ): Int = 0+}
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.ktnew file mode 100644index 0000000000..ac88ae4076--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyUiContract.kt@@ -0,0 +1,117 @@+package com.vayunmathur.emergency.platform++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.ImportedMedication++/**+ * The UI contract between [EmergencyViewModel]/[SosCoordinator] and the screens in `ui`.+ *+ * Pages take a state value plus an actions interface rather than the ViewModel itself, so+ * they can be rendered by a `@Preview` - which is what the store listing images are+ * generated from (see `src/screenshotTest`). It lives beside the ViewModel rather than in+ * `ui` so the dependency runs one way.+ */++/**+ * Allergies and current medications read from Health Connect, shown alongside the stored+ * fields. All read-only; empty and [available] false on devices without the PHR feature.+ */+data class HealthConnectMedicalState(+    /** The device's Health Connect module exposes Personal Health Records. */+    val available: Boolean = false,+    /** Both medical read permissions are granted. */+    val granted: Boolean = false,+    val allergies: List<ImportedAllergy> = emptyList(),+    val medications: List<ImportedMedication> = emptyList(),+)++/** Everything the view/edit screens draw. */+data class EmergencyUiState(+    val info: EmergencyInfo = EmergencyInfo(),+    /** True while the stored info is still being loaded. */+    val loading: Boolean = true,+    /** False until READ_CONTACTS is granted; the contact list must prompt, not show empty. */+    val hasContactsAccess: Boolean = false,+    /** Last add-contact failure, for a one-shot message; null when none. */+    val addFailed: Boolean = false,+    /** Allergies and current medications from Health Connect, when available and granted. */+    val health: HealthConnectMedicalState = HealthConnectMedicalState(),+)++interface EmergencyActions {+    /** Persists the manually-entered identity fields (allergies/medications come from HC). */+    fun saveInfo(+        name: String,+        address: String,+        bloodType: String,+        organDonor: String,+    ) {}++    /** Adds the picked contact URI; sets [EmergencyUiState.addFailed] when rejected. */+    fun addContact(phoneUri: Uri) {}++    fun removeContact(phoneUri: Uri) {}++    /** Re-reads stored info and re-checks the contacts grant. */+    fun refresh() {}++    /** Clears the one-shot add-failure flag after it has been shown. */+    fun clearAddFailed() {}++    /** Re-reads Health Connect allergies/medications after a permission grant. */+    fun refreshHealthConnect() {}++    companion object {+        val Noop: EmergencyActions = object : EmergencyActions {}+    }+}++/** Everything the SOS countdown screen draws. */+data class SosUiState(+    /** The number about to be dialled (override-aware). */+    val number: String = EmergencyNumberLookup.FALLBACK_NUMBER,+    /** Milliseconds left when the screen opened; the screen counts down from here. */+    val totalMillis: Long = 0,+    /** False when the gesture is off - the screen must exit, not count down. */+    val gestureEnabled: Boolean = false,+    /** True once the state above has been read. */+    val loaded: Boolean = false,+)++interface SosActions {+    /** Hands the remaining countdown to the foreground service and finishes the screen. */+    fun continueInBackground(remainingMillis: Long) {}++    /** Cancels the countdown entirely (alarm + service + sound). */+    fun cancel() {}++    companion object {+        val Noop: SosActions = object : SosActions {}+    }+}++/** Preview/sample contact for screenshots. */+fun sampleContact(): EmergencyContact = EmergencyContact(+    phoneUri = Uri.parse("content://com.android.contacts/data/1"),+    displayName = "Alex Rivera",+    phoneNumber = "(555) 010-2030",+    phoneType = "Mobile",+)++/** Preview/sample Health Connect data for screenshots. */+fun sampleHealthConnect(): HealthConnectMedicalState = HealthConnectMedicalState(+    available = true,+    granted = true,+    allergies = listOf(+        ImportedAllergy("Penicillin", com.vayunmathur.emergency.data.AllergyCriticality.High, "Anaphylaxis"),+        ImportedAllergy("Peanuts", com.vayunmathur.emergency.data.AllergyCriticality.High, "Hives"),+        ImportedAllergy("Pollen", com.vayunmathur.emergency.data.AllergyCriticality.Low, null),+    ),+    medications = listOf(+        ImportedMedication("Salbutamol 100mcg inhaler"),+        ImportedMedication("Lisinopril 10mg"),+    ),+)
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.ktnew file mode 100644index 0000000000..2bfeccea1b--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/EmergencyViewModel.kt@@ -0,0 +1,113 @@+package com.vayunmathur.emergency.platform++import android.Manifest+import android.app.Application+import android.content.pm.PackageManager+import android.net.Uri+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.emergency.data.EmergencyRepository+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++class EmergencyViewModel(app: Application) : AndroidViewModel(app), EmergencyActions {++    private val repository = EmergencyRepository.get(app)+    private val healthConnect = HealthConnectMedical(app)+    private val loaded = MutableStateFlow(false)+    private val hasContactsAccess = MutableStateFlow(false)+    private val addFailed = MutableStateFlow(false)+    private val health = MutableStateFlow(HealthConnectMedicalState())++    val state: StateFlow<EmergencyUiState> = combine(+        repository.info,+        loaded,+        hasContactsAccess,+        addFailed,+        health,+    ) { flows ->+        @Suppress("UNCHECKED_CAST")+        val info = flows[0] as com.vayunmathur.emergency.data.EmergencyInfo+        EmergencyUiState(+            info = info,+            loading = !(flows[1] as Boolean),+            hasContactsAccess = flows[2] as Boolean,+            addFailed = flows[3] as Boolean,+            health = flows[4] as HealthConnectMedicalState,+        )+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), EmergencyUiState())++    init {+        refresh()+    }++    override fun refresh() {+        viewModelScope.launch(Dispatchers.IO) {+            hasContactsAccess.value = checkContactsGrant()+            repository.load()+            loaded.value = true+        }+        refreshHealthConnect()+    }++    override fun refreshHealthConnect() {+        viewModelScope.launch(Dispatchers.IO) {+            val available = healthConnect.isAvailable()+            if (!available) {+                health.value = HealthConnectMedicalState(available = false)+                return@launch+            }+            val granted = healthConnect.hasPermissions()+            if (!granted) {+                health.value = HealthConnectMedicalState(available = true, granted = false)+                return@launch+            }+            health.value = HealthConnectMedicalState(+                available = true,+                granted = true,+                allergies = healthConnect.readAllergies(),+                medications = healthConnect.readCurrentMedications(),+            )+        }+    }++    override fun saveInfo(+        name: String,+        address: String,+        bloodType: String,+        organDonor: String,+    ) {+        viewModelScope.launch {+            repository.saveInfo(name, address, bloodType, organDonor)+        }+    }++    override fun addContact(phoneUri: Uri) {+        viewModelScope.launch(Dispatchers.IO) {+            addFailed.value = !repository.addContact(phoneUri)+        }+    }++    override fun removeContact(phoneUri: Uri) {+        viewModelScope.launch(Dispatchers.IO) {+            repository.removeContact(phoneUri)+        }+    }++    override fun clearAddFailed() {+        addFailed.value = false+    }++    private fun checkContactsGrant(): Boolean =+        getApplication<Application>().checkSelfPermission(Manifest.permission.READ_CONTACTS) ==+            PackageManager.PERMISSION_GRANTED++    private companion object {+        const val STOP_TIMEOUT_MS = 5_000L+    }+}
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.ktnew file mode 100644index 0000000000..e8ac61fbed--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/GestureProvider.kt@@ -0,0 +1,238 @@+package com.vayunmathur.emergency.platform++import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.content.SharedPreferences+import android.database.Cursor+import android.net.Uri+import android.os.Bundle+import android.os.SystemClock+import android.provider.Settings+import android.util.Log++private const val TAG = "EmergencyGestureProvider"++/**+ * Gesture state for Settings, speaking the settingslib `EmergencyNumberUtils` protocol.+ *+ * Mirrors GrapheneOS's `EmergencyGestureContentProvider`: a `call()`-only provider (query,+ * insert, update and delete throw) whose methods get/set the SOS gesture toggles and the+ * emergency-number override. The string literals below are SettingsLib's+ * `EmergencyNumberUtils` constants, restated because a Gradle app cannot link SettingsLib.+ *+ * Writes land in `Settings.Secure`, which needs `WRITE_SECURE_SETTINGS` - a priv-app-only+ * grant. Every write is guarded: without the grant the call returns a denied bundle instead+ * of throwing into Settings. Reads work regardless; defaults come from local resources+ * (GrapheneOS reads `com.android.internal` bools we cannot see).+ *+ * Authority is ours (`com.vayunmathur.emergency.gesture`); the MAOS build must rewire+ * `EMERGENCY_NUMBER_OVERRIDE_AUTHORITY` if it wants Settings to call this provider.+ */+class GestureProvider : ContentProvider() {++    private fun prefs(): SharedPreferences =+        requireContext().getSharedPreferences(OVERRIDE_PREFS, Context.MODE_PRIVATE)++    override fun call(authority: String, method: String, arg: String?, extras: Bundle?): Bundle? {+        val out = Bundle()+        when (method) {+            METHOD_GET_NUMBER_OVERRIDE -> {+                out.putString(+                    EXTRA_CALL_NUMBER,+                    prefs().getString(EXTRA_CALL_NUMBER, null),+                )+            }+            METHOD_SET_NUMBER_OVERRIDE -> {+                prefs().edit()+                    .putString(EXTRA_CALL_NUMBER, extras?.getString(EXTRA_CALL_NUMBER))+                    .apply()+            }+            METHOD_SET_GESTURE -> {+                if (!writeSecure(SecureKeys.GESTURE_ENABLED, extras, EXTRA_VALUE)) {+                    return denied(out)+                }+            }+            METHOD_SET_GESTURE_UI_SHOWING -> {+                val showing = extras?.getInt(EXTRA_UI_SHOWING_VALUE, 0) ?: 0+                if (!writeSecureInt(SecureKeys.GESTURE_UI_SHOWING, showing.toLong())) {+                    return denied(out)+                }+                if (showing != 0) {+                    writeSecureInt(+                        SecureKeys.GESTURE_UI_LAST_STARTED_MILLIS,+                        SystemClock.elapsedRealtime(),+                    )+                }+            }+            METHOD_SET_SOUND -> {+                if (!writeSecure(SecureKeys.GESTURE_SOUND_ENABLED, extras, EXTRA_VALUE)) {+                    return denied(out)+                }+            }+            METHOD_GET_GESTURE_ENABLED -> {+                out.putInt(EXTRA_VALUE, readSecureInt(+                    SecureKeys.GESTURE_ENABLED,+                    defaultGestureEnabled(),+                ))+            }+            METHOD_GET_SOUND_ENABLED -> {+                out.putInt(EXTRA_VALUE, readSecureInt(+                    SecureKeys.GESTURE_SOUND_ENABLED,+                    defaultSoundEnabled(),+                ))+            }+            else -> {+                Log.w(TAG, "unknown gesture method $method from $authority")+                return null+            }+        }+        return out+    }++    /** Current number override, for the SOS screen; null when the user set none. */+    fun numberOverride(context: Context): String? = numberOverrideStatic(context)++    /** Whether the SOS gesture is on; local default when Settings.Secure is unreadable. */+    fun isGestureEnabled(context: Context): Boolean = isGestureEnabledStatic(context)++    /** Whether the SOS warning sound is on; local default when unreadable. */+    fun isSoundEnabled(context: Context): Boolean = isSoundEnabledStatic(context)++    private fun writeSecure(key: String, extras: Bundle?, valueKey: String): Boolean {+        val value = extras?.getInt(valueKey) ?: return false+        return writeSecureInt(key, value.toLong())+    }++    private fun writeSecureInt(key: String, value: Long): Boolean {+        // Long storage for the UI-showing timestamp; ints for the toggles.+        return runCatching {+            val resolver = requireContext().contentResolver+            if (key == SecureKeys.GESTURE_UI_LAST_STARTED_MILLIS) {+                Settings.Secure.putLong(resolver, key, value)+            } else {+                Settings.Secure.putInt(resolver, key, value.toInt())+            }+            true+        }.getOrElse {+            Log.w(TAG, "cannot write $key; is WRITE_SECURE_SETTINGS held?", it)+            false+        }+    }++    private fun readSecureInt(key: String, default: Int): Int =+        readSecureInt(requireContext(), key, default)++    private fun denied(out: Bundle): Bundle {+        // SettingsLib treats a null bundle as "provider absent, use compiled default"; a bundle+        // carrying the off value says "present but disabled", which is the honest answer when+        // the Secure write was refused.+        out.putInt(EXTRA_VALUE, SETTING_OFF)+        return out+    }++    private fun defaultGestureEnabled(): Int =+        if (requireContext().resources.getBoolean(com.vayunmathur.emergency.R.bool.default_emergency_gesture_enabled)) {+            SETTING_ON+        } else {+            SETTING_OFF+        }++    private fun defaultSoundEnabled(): Int =+        if (requireContext().resources.getBoolean(com.vayunmathur.emergency.R.bool.default_emergency_gesture_sound_enabled)) {+            SETTING_ON+        } else {+            SETTING_OFF+        }++    override fun onCreate(): Boolean = true++    override fun query(+        uri: Uri,+        projection: Array<String>?,+        selection: String?,+        selectionArgs: Array<String>?,+        sortOrder: String?,+    ): Cursor = throw UnsupportedOperationException()++    override fun getType(uri: Uri): String = throw UnsupportedOperationException()++    override fun insert(uri: Uri, values: ContentValues?): Uri =+        throw UnsupportedOperationException()++    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int =+        throw UnsupportedOperationException()++    override fun update(+        uri: Uri,+        values: ContentValues?,+        selection: String?,+        selectionArgs: Array<String>?,+    ): Int = throw UnsupportedOperationException()++    companion object {+        private const val OVERRIDE_PREFS = "local_emergency_number_override_shared_pref"++        /**+         * `Settings.Secure` gesture keys as literals: they are `@hide`/system-API in the+         * framework (`Settings.Secure.EMERGENCY_GESTURE_*`), so a Gradle app cannot reference+         * the constants. Values from AOSP `Settings.java`; the put/get calls themselves are+         * public API and fail gracefully without `WRITE_SECURE_SETTINGS`.+         */+        private object SecureKeys {+            const val GESTURE_ENABLED = "emergency_gesture_enabled"+            const val GESTURE_SOUND_ENABLED = "emergency_gesture_sound_enabled"+            const val GESTURE_UI_SHOWING = "emergency_gesture_ui_showing"+            const val GESTURE_UI_LAST_STARTED_MILLIS = "emergency_gesture_ui_last_started_millis"+        }++        /** Static read of the number override for non-provider callers (receiver, lookup). */+        fun numberOverrideStatic(context: Context): String? =+            runCatching {+                context.getSharedPreferences(OVERRIDE_PREFS, Context.MODE_PRIVATE)+                    .getString(EXTRA_CALL_NUMBER, null)+            }.getOrNull()++        /** Static gesture-enabled read (provider instance not required). */+        fun isGestureEnabledStatic(context: Context): Boolean =+            readSecureInt(+                context,+                SecureKeys.GESTURE_ENABLED,+                context.resources.getBoolean(+                    com.vayunmathur.emergency.R.bool.default_emergency_gesture_enabled,+                ).toSetting(),+            ) == SETTING_ON++        /** Static sound-enabled read (provider instance not required). */+        fun isSoundEnabledStatic(context: Context): Boolean =+            readSecureInt(+                context,+                SecureKeys.GESTURE_SOUND_ENABLED,+                context.resources.getBoolean(+                    com.vayunmathur.emergency.R.bool.default_emergency_gesture_sound_enabled,+                ).toSetting(),+            ) == SETTING_ON++        private fun Boolean.toSetting(): Int = if (this) SETTING_ON else SETTING_OFF++        // SettingsLib EmergencyNumberUtils literals (see plan). Do not "clean these up" into+        // nicer names: they are a wire protocol shared with Settings.+        const val METHOD_GET_NUMBER_OVERRIDE = "GET_EMERGENCY_NUMBER_OVERRIDE"+        const val METHOD_SET_NUMBER_OVERRIDE = "SET_EMERGENCY_NUMBER_OVERRIDE"+        const val METHOD_SET_GESTURE = "SET_EMERGENCY_GESTURE"+        const val METHOD_SET_GESTURE_UI_SHOWING = "SET_EMERGENCY_GESTURE_UI_SHOWING"+        const val METHOD_SET_SOUND = "SET_EMERGENCY_SOUND"+        const val METHOD_GET_GESTURE_ENABLED = "GET_EMERGENCY_GESTURE"+        const val METHOD_GET_SOUND_ENABLED = "GET_EMERGENCY_SOUND"+        const val EXTRA_CALL_NUMBER = "emergency_gesture_call_number"+        const val EXTRA_UI_SHOWING_VALUE = "emergency_gesture_ui_showing_value"+        const val EXTRA_VALUE = "emergency_setting_value"+        const val SETTING_ON = 1+        const val SETTING_OFF = 0++        private fun readSecureInt(context: Context, key: String, default: Int): Int =+            runCatching {+                Settings.Secure.getInt(context.contentResolver, key, default)+            }.getOrDefault(default)+    }+}
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.ktnew file mode 100644index 0000000000..02631cc5aa--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/HealthConnectMedical.kt@@ -0,0 +1,117 @@+@file:OptIn(androidx.health.connect.client.feature.ExperimentalPersonalHealthRecordApi::class)++package com.vayunmathur.emergency.platform++import android.content.Context+import android.util.Log+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.HealthConnectFeatures+import androidx.health.connect.client.permission.HealthPermission+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.ImportedMedication+import com.vayunmathur.emergency.domain.FhirMedicalParse++private const val TAG = "EmergencyHealthConnect"++/**+ * Read-only window onto Health Connect's Personal Health Record store, for the two things an+ * emergency card wants that the free-text fields cannot keep current: the patient's allergies+ * and what they are taking right now.+ *+ * Mirrors the health app's `PersonalHealthRecords`, pared to reads: PHR needs Android 15 with an+ * updated Health Connect module, so [isAvailable] gates everything and every method degrades to+ * empty rather than throwing on older devices or when the permission is refused. The emergency+ * app therefore always works from its own stored fields, with this layered on when present.+ *+ * Reads span every data source, not just any this app owns, because the whole point is to show+ * records a hospital or pharmacy synced in - which by definition live elsewhere.+ */+class HealthConnectMedical(context: Context) {++    private val appContext = context.applicationContext++    private val client: HealthConnectClient? by lazy {+        runCatching {+            if (HealthConnectClient.getSdkStatus(appContext) == HealthConnectClient.SDK_AVAILABLE) {+                HealthConnectClient.getOrCreate(appContext)+            } else {+                null+            }+        }.getOrElse {+            Log.w(TAG, "Health Connect client unavailable", it)+            null+        }+    }++    /** True when the device's Health Connect module exposes the Personal Health Record feature. */+    fun isAvailable(): Boolean {+        val client = client ?: return false+        return runCatching {+            client.features.getFeatureStatus(+                HealthConnectFeatures.FEATURE_PERSONAL_HEALTH_RECORD,+            ) == HealthConnectFeatures.FEATURE_STATUS_AVAILABLE+        }.getOrElse {+            Log.w(TAG, "Could not query the Personal Health Record feature status", it)+            false+        }+    }++    /** Whether both medical read permissions this feature needs are currently granted. */+    suspend fun hasPermissions(): Boolean {+        val client = client ?: return false+        return runCatching {+            client.permissionController.getGrantedPermissions().containsAll(PERMISSIONS)+        }.getOrDefault(false)+    }++    /** Active allergies, most critical first; empty when unavailable, denied, or none recorded. */+    suspend fun readAllergies(): List<ImportedAllergy> {+        val parsed = readCategory(MedicalResource.MEDICAL_RESOURCE_TYPE_ALLERGIES_INTOLERANCES)+            .mapNotNull { FhirMedicalParse.parseAllergy(it) }+        return FhirMedicalParse.sortAllergies(parsed).distinctBy { it.displayName }+    }++    /** Current medications; empty when unavailable, denied, or none recorded. */+    suspend fun readCurrentMedications(): List<ImportedMedication> =+        readCategory(MedicalResource.MEDICAL_RESOURCE_TYPE_MEDICATIONS)+            .mapNotNull { FhirMedicalParse.parseCurrentMedication(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()+        val client = client ?: return emptyList()+        return runCatching {+            val out = mutableListOf<String>()+            var response = client.readMedicalResources(+                ReadMedicalResourcesInitialRequest(medicalResourceType, emptySet(), PAGE_SIZE),+            )+            out += response.medicalResources.map { it.fhirResource.data }+            var token = response.nextPageToken+            while (token != null) {+                response = client.readMedicalResources(ReadMedicalResourcesPageRequest(token, PAGE_SIZE))+                out += response.medicalResources.map { it.fhirResource.data }+                token = response.nextPageToken+            }+            out+        }.getOrElse {+            // Reads can fail when the device is locked (medical data is credential-encrypted) or+            // the permission was revoked; the card just falls back to its own fields.+            Log.w(TAG, "Could not read medical resources of type $medicalResourceType", it)+            emptyList()+        }+    }++    companion object {+        /** The read permissions the emergency card needs. Requested from the edit screen. */+        val PERMISSIONS = setOf(+            HealthPermission.PERMISSION_READ_MEDICAL_DATA_ALLERGIES_INTOLERANCES,+            HealthPermission.PERMISSION_READ_MEDICAL_DATA_MEDICATIONS,+        )++        private const val PAGE_SIZE = 500+    }+}
emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.ktnew file mode 100644index 0000000000..2136143f08--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/SosCoordinator.kt@@ -0,0 +1,57 @@+package com.vayunmathur.emergency.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.service.SosCountdownService+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/**+ * Owns the SOS countdown screen's state and its handoff to the background.+ *+ * Mirrors `EmergencyActionFragment`'s half of the flow: the screen itself counts down (see+ * `ui/SosScreen`), and this coordinator resolves the number, gates on the gesture toggle,+ * and - when the screen is dismissed mid-countdown - continues via [SosCountdownService]+ * instead of dropping the call. Cancelling stops everything through [SosActionReceiver].+ */+class SosCoordinator(app: Application, private val openedWithMillis: Long) :+    AndroidViewModel(app), SosActions {++    private val mutable = MutableStateFlow(SosUiState())+    val state: StateFlow<SosUiState> = mutable.asStateFlow()++    init {+        viewModelScope.launch(Dispatchers.IO) {+            val app = getApplication<Application>()+            val enabled = GestureProvider.isGestureEnabledStatic(app)+            val number = EmergencyNumberLookup(app)+                .policeNumber(GestureProvider.numberOverrideStatic(app))+            val total = if (openedWithMillis > 0) {+                openedWithMillis+            } else {+                app.resources.getInteger(+                    com.vayunmathur.emergency.R.integer.sos_count_down_millis,+                ).toLong()+            }+            mutable.value = SosUiState(+                number = number,+                totalMillis = total,+                gestureEnabled = enabled,+                loaded = true,+            )+        }+    }++    override fun continueInBackground(remainingMillis: Long) {+        if (remainingMillis > 0) SosCountdownService.start(getApplication(), remainingMillis)+    }++    override fun cancel() {+        SosActionReceiver.stopCountdown(getApplication())+    }+}
emergency/src/main/java/com/vayunmathur/emergency/platform/SosSound.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/platform/SosSound.kt b/emergency/src/main/java/com/vayunmathur/emergency/platform/SosSound.ktnew file mode 100644index 0000000000..2e077eab75--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/platform/SosSound.kt@@ -0,0 +1,79 @@+package com.vayunmathur.emergency.platform++import android.content.Context+import android.media.AudioManager+import android.media.ToneGenerator+import android.util.Log+import androidx.core.content.getSystemService++private const val TAG = "EmergencySosSound"++/**+ * The SOS warning sound.+ *+ * Mirrors GrapheneOS's `EmergencyActionAlarmHelper`: while the countdown runs, the alarm+ * stream is maxed and a warning tone plays; on stop the user's volume is restored. Two+ * deliberate substitutions: the tone comes from `ToneGenerator` (alarm stream,+ * `TONE_CDMA_EMERGENCY_RINGBACK`, looped for the countdown) instead of GrapheneOS's bundled+ * `R.raw.alarm` - a Gradle module cannot ship their audio file and a siren sample would need+ * licensing review - and the sound gate reads our [GestureProvider] static instead of+ * `Settings.Secure` directly (same value, same default).+ *+ * Volume restore is best-effort: if the process dies mid-countdown the stream stays loud+ * until the user touches volume, exactly like the original (whose reset also lives in+ * `stopWarningSound`).+ */+class SosSound(private val context: Context) {++    private var tone: ToneGenerator? = null+    private var savedVolume = UNKNOWN_VOLUME+    private var resetNeeded = false++    /** Starts the warning tone; no-op when the SOS sound is disabled. */+    fun play() {+        if (!GestureProvider.isSoundEnabledStatic(context)) return+        if (tone != null) return+        val audio = context.getSystemService<AudioManager>() ?: return+        runCatching {+            if (savedVolume == UNKNOWN_VOLUME) {+                savedVolume = audio.getStreamVolume(AudioManager.STREAM_ALARM)+            }+            resetNeeded = true+            audio.setStreamVolume(+                AudioManager.STREAM_ALARM,+                audio.getStreamMaxVolume(AudioManager.STREAM_ALARM),+                0,+            )+            ToneGenerator(AudioManager.STREAM_ALARM, ToneGenerator.MAX_VOLUME).also {+                tone = it+                // Loop the emergency-ringback tone for the whole countdown; stop() ends it.+                it.startTone(ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK)+            }+        }.onFailure {+            Log.w(TAG, "could not start the SOS warning tone", it)+            tone?.release()+            tone = null+        }+    }++    /** Returns the alarm volume the user had before [play] maxed it, or -1 when unknown. */+    fun userAlarmVolume(): Int = savedVolume++    /** Stops the tone and restores the user's alarm volume. */+    fun stop() {+        runCatching { tone?.stopTone() }+        runCatching { tone?.release() }+        tone = null+        if (resetNeeded && savedVolume != UNKNOWN_VOLUME) {+            val audio = context.getSystemService<AudioManager>()+            runCatching {+                audio?.setStreamVolume(AudioManager.STREAM_ALARM, savedVolume, 0)+            }.onFailure { Log.w(TAG, "could not restore the alarm volume", it) }+            resetNeeded = false+        }+    }++    companion object {+        const val UNKNOWN_VOLUME = -1+    }+}
emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.kt b/emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.ktnew file mode 100644index 0000000000..d545b10548--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/receiver/SosActionReceiver.kt@@ -0,0 +1,136 @@+package com.vayunmathur.emergency.receiver++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.telecom.TelecomManager+import android.util.Log+import androidx.core.content.getSystemService+import com.vayunmathur.emergency.platform.EmergencyNumberLookup+import com.vayunmathur.emergency.platform.GestureProvider+import com.vayunmathur.emergency.service.SosCountdownService++private const val TAG = "EmergencySosReceiver"++/**+ * Handles SOS outcomes.+ *+ * Mirrors GrapheneOS's `EmergencyActionBroadcastReceiver`: `MAKE_EMERGENCY_CALL` places the+ * call and then tears the service down (intentional fall-through in the original; an explicit+ * `stopCountdown` call here); `CANCEL_EMERGENCY_COUNTDOWN` cancels the scheduled alarm and+ * stops the service. Both actions are explicit-class intents from our own notification,+ * alarm and screen - the manifest filter is documentation, not an open door.+ *+ * Call placement delegates to Settings' emergency provider+ * (`content://com.android.settings.emergency` / `MAKE_EMERGENCY_CALL`), exactly like+ * `EmergencyActionUtils.placeEmergencyCall`. When Settings has no such provider (a MAOS+ * Settings build that does not implement it), this falls back to an explicit+ * `ACTION_CALL_EMERGENCY` telecom intent carrying the resolved number - so the gesture still+ * dials instead of silently dying.+ */+class SosActionReceiver : BroadcastReceiver() {++    override fun onReceive(context: Context, intent: Intent) {+        val app = context.applicationContext+        when (intent.action) {+            ACTION_MAKE_CALL -> {+                Log.i(TAG, "SOS countdown finished; placing the emergency call")+                placeCall(app)+                stopCountdown(app)+            }+            ACTION_CANCEL_COUNTDOWN -> {+                Log.i(TAG, "SOS countdown cancelled; stopping the service")+                stopCountdown(app)+            }+            else -> Log.w(TAG, "unknown SOS action ${intent.action}; ignoring")+        }+    }++    private fun placeCall(app: Context) {+        if (placeViaSettings(app)) return+        placeViaTelecom(app)+    }++    /**+     * Asks Settings to place the call, the GrapheneOS path. Returns false when Settings has+     * no emergency provider so the caller falls back to telecom.+     */+    private fun placeViaSettings(app: Context): Boolean =+        runCatching {+            val result = app.contentResolver.call(+                SETTINGS_EMERGENCY_AUTHORITY,+                SETTINGS_MAKE_CALL,+                null,+                null,+            )+            // A null bundle means "no provider answered"; any bundle means Settings took it.+            result != null+        }.getOrElse {+            Log.w(TAG, "Settings emergency provider did not take the call", it)+            false+        }++    /** Direct emergency dial of the resolved number. Needs CALL_PHONE (runtime grant). */+    private fun placeViaTelecom(app: Context) {+        val number = EmergencyNumberLookup(app)+            .policeNumber(GestureProvider.numberOverrideStatic(app))+        val telecom = app.getSystemService<TelecomManager>()+        if (telecom == null) {+            Log.w(TAG, "no TelecomManager; cannot place the emergency call")+            return+        }+        // Intent.ACTION_CALL_EMERGENCY as a literal: the constant is hidden in this SDK's+        // Intent (same story as the Secure gesture keys), and the action string is stable+        // platform surface ("android.intent.action.CALL_EMERGENCY", routed to the emergency+        // dialer by Telecom).+        val intent = Intent(ACTION_CALL_EMERGENCY).apply {+            data = Uri.fromParts("tel", number, null)+            flags = Intent.FLAG_ACTIVITY_NEW_TASK+        }+        runCatching { app.startActivity(intent) }+            .onFailure { Log.w(TAG, "could not place the emergency call to $number", it) }+    }++    companion object {+        const val ACTION_MAKE_CALL = "com.vayunmathur.emergency.broadcast.MAKE_EMERGENCY_CALL"+        const val ACTION_CANCEL_COUNTDOWN =+            "com.vayunmathur.emergency.broadcast.CANCEL_EMERGENCY_COUNTDOWN"++        /** `Intent.ACTION_CALL_EMERGENCY`, hidden in this SDK — see placeViaTelecom. */+        private const val ACTION_CALL_EMERGENCY = "android.intent.action.CALL_EMERGENCY"++        /** Settings' emergency-call provider, the `EmergencyActionUtils` literals. */+        private val SETTINGS_EMERGENCY_AUTHORITY: Uri = Uri.Builder()+            .scheme("content")+            .authority("com.android.settings.emergency")+            .build()+        private const val SETTINGS_MAKE_CALL = "com.android.settings.emergency.MAKE_EMERGENCY_CALL"++        fun makeCallIntent(context: Context): Intent =+            Intent(ACTION_MAKE_CALL).setClass(context, SosActionReceiver::class.java)++        fun makeCallPendingIntent(context: Context): PendingIntent =+            PendingIntent.getBroadcast(+                context, 0, makeCallIntent(context), PendingIntent.FLAG_IMMUTABLE,+            )++        fun cancelIntent(context: Context): Intent =+            Intent(ACTION_CANCEL_COUNTDOWN).setClass(context, SosActionReceiver::class.java)++        fun cancelPendingIntent(context: Context): PendingIntent =+            PendingIntent.getBroadcast(+                context, 0, cancelIntent(context), PendingIntent.FLAG_IMMUTABLE,+            )++        /** Cancels the scheduled call alarm and stops the countdown service. */+        fun stopCountdown(context: Context) {+            val app = context.applicationContext+            val alarms = app.getSystemService<AlarmManager>()+            runCatching { alarms?.cancel(makeCallPendingIntent(app)) }+            SosCountdownService.stop(app)+        }+    }+}
emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt
diff --git a/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt b/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.ktnew file mode 100644index 0000000000..7fc7a2583d--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/service/SosCountdownService.kt@@ -0,0 +1,132 @@+package com.vayunmathur.emergency.service++import android.app.AlarmManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.IBinder+import android.os.SystemClock+import android.os.VibrationEffect+import android.os.Vibrator+import android.telecom.TelecomManager+import android.util.Log+import androidx.core.content.getSystemService+import com.vayunmathur.emergency.notifications.SosNotifications+import com.vayunmathur.emergency.platform.EmergencyNumberLookup+import com.vayunmathur.emergency.platform.GestureProvider+import com.vayunmathur.emergency.platform.SosSound+import com.vayunmathur.emergency.receiver.SosActionReceiver+import com.vayunmathur.emergency.ui.SosActivity++private const val TAG = "EmergencySosService"++/**+ * Counts down to the emergency call in the background.+ *+ * Mirrors GrapheneOS's `EmergencyActionForegroundService`: started when the SOS screen is+ * dismissed mid-countdown (or directly with remaining time), posts the ongoing countdown+ * notification, schedules the exact alarm that fires `MAKE_EMERGENCY_CALL`, and plays the+ * vibration waveform + warning sound. No telephony on the device (or an invalid remaining+ * time) stops the service immediately - there is nothing to count down to.+ */+class SosCountdownService : Service() {++    private var vibrator: Vibrator? = null+    private var sound: SosSound? = null++    override fun onCreate() {+        super.onCreate()+        vibrator = getSystemService()+        sound = SosSound(this)+    }++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        val remainingMs = intent?.getLongExtra(EXTRA_REMAINING_MS, -1) ?: -1+        if (remainingMs <= 0) {+            Log.w(TAG, "invalid remaining countdown time; nothing to do")+            stopSelf()+            return START_NOT_STICKY+        }+        if (!packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {+            Log.w(TAG, "no telephony on this device; nothing to do")+            stopSelf()+            return START_NOT_STICKY+        }+        // Touching TelecomManager here (instead of only in the receiver) fails fast when the+        // telecom stack is missing, the way GrapheneOS's onCreate null-check does.+        if (getSystemService<TelecomManager>() == null) {+            Log.w(TAG, "no TelecomManager; nothing to do")+            stopSelf()+            return START_NOT_STICKY+        }++        val number = EmergencyNumberLookup(this)+            .policeNumber(GestureProvider.numberOverrideStatic(this))+        val targetElapsed = SystemClock.elapsedRealtime() + remainingMs+        val contentIntent = PendingIntent.getActivity(+            this, 0, SosActivity.intent(this, remainingMs),+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        val notification = SosNotifications.countdown(this, number, targetElapsed, contentIntent)+        SosNotifications.notify(this, notification)+        startForeground(SosNotifications.NOTIFICATION_ID, notification)++        scheduleCall(remainingMs)+        vibrator?.vibrate(VIBRATION_EFFECT)+        if (GestureProvider.isSoundEnabledStatic(this)) sound?.play()++        return START_NOT_STICKY+    }++    override fun onDestroy() {+        sound?.stop()+        vibrator?.cancel()+        SosNotifications.cancel(this)+        super.onDestroy()+    }++    override fun onBind(intent: Intent?): IBinder? = null++    private fun scheduleCall(remainingMs: Long) {+        val alarms = getSystemService<AlarmManager>() ?: return+        runCatching {+            alarms.setExactAndAllowWhileIdle(+                AlarmManager.RTC_WAKEUP,+                System.currentTimeMillis() + remainingMs,+                SosActionReceiver.makeCallPendingIntent(this),+            )+        }.onFailure { Log.w(TAG, "could not schedule the SOS call alarm", it) }+    }++    companion object {+        private const val EXTRA_REMAINING_MS = "service.extra.remaining_time_ms"++        /** Alarm + vibration pattern from GrapheneOS's service (timings/amplitudes verbatim). */+        private val VIBRATION_EFFECT: VibrationEffect =+            VibrationEffect.createWaveform(+                longArrayOf(200, 20, 20, 20, 20, 100, 20, 600),+                intArrayOf(0, 39, 82, 139, 213, 0, 127, 0),+                -1,+            )++        /** Starts the background countdown with [remainingMs] left on the clock. */+        fun start(context: Context, remainingMs: Long) {+            val intent = Intent(context, SosCountdownService::class.java)+                .putExtra(EXTRA_REMAINING_MS, remainingMs)+            runCatching { context.startForegroundService(intent) }+                .onFailure { Log.w(TAG, "could not start the SOS countdown service", it) }+        }++        /** Cancels the scheduled call and stops the service. */+        fun stop(context: Context) {+            val app = context.applicationContext+            runCatching {+                app.getSystemService<AlarmManager>()+                    ?.cancel(SosActionReceiver.makeCallPendingIntent(app))+            }+            runCatching { app.stopService(Intent(app, SosCountdownService::class.java)) }+        }+    }+}
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.ktnew file mode 100644index 0000000000..9c572658e3--- /dev/null+++ b/emergency/src/main/java/com/vayunmathur/emergency/ui/EditInfoScreen.kt@@ -0,0 +1,234 @@+package com.vayunmathur.emergency.ui++import android.Manifest+import android.content.Intent+import android.os.Bundle+import android.provider.ContactsContract+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.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.health.connect.client.PermissionController+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.emergency.R+import com.vayunmathur.emergency.platform.EmergencyActions+import com.vayunmathur.emergency.platform.EmergencyUiState+import com.vayunmathur.emergency.platform.EmergencyViewModel+import com.vayunmathur.emergency.platform.HealthConnectMedical+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.FormSection+import com.vayunmathur.library.ui.LabeledTextField+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.TextButton+import com.vayunmathur.library.ui.appBarScrollBehavior++/**+ * Edits the owner's identity 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.+ */+class EditInfoActivity : ComponentActivity() {++    private val viewModel: EmergencyViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                EditInfoPage(viewModel = viewModel)+            }+        }+    }++    override fun onResume() {+        super.onResume()+        viewModel.refresh()+    }+}++/** Binds the ViewModel to the stateless screen, owning the pick/permission launchers. */+@Composable+private fun EditInfoPage(viewModel: EmergencyViewModel) {+    val state by viewModel.state.collectAsStateWithLifecycle()+    

Diff truncated.