Modern Apps git

← Modern-Apps.git

various fixes

Commit
1fd92190ebf24e67b6349f1f71abcbc612e31779
Author
vayun-mathur <[email protected]>
When
2026-09-15 03:36 UTC (2 months ago)
Parents
486f7ac

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 1c39477c97..7f4b4019f6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -35,7 +35,7 @@ dependencies = [  "percent-encoding",  "precomputed-hash",  "regex",- "rustc-hash",+ "rustc-hash 2.1.3",  "seahash",  "serde",  "serde_json",@@ -280,6 +280,27 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]]+name = "beef"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"++[[package]]+name = "bit-set"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"+ [[package]] name = "bitfield-struct" version = "0.12.1"@@ -495,6 +516,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"+ [[package]] name = "chacha20" version = "0.9.1"@@ -637,6 +664,15 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]]+name = "codespan-reporting"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"+dependencies = [+ "unicode-width 0.2.2",+]+ [[package]] name = "color" version = "0.3.3"@@ -1211,6 +1247,12 @@ dependencies = [  "zeroize", ] +[[package]]+name = "fixedbitset"+version = "0.5.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"+ [[package]] name = "flatbuffers" version = "25.12.19"@@ -1232,6 +1274,18 @@ dependencies = [  "zlib-rs", ] +[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"+ [[package]] name = "foldhash" version = "0.2.0"@@ -1344,8 +1398,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e" dependencies = [  "bytemuck",- "foldhash",- "hashbrown",+ "foldhash 0.2.0",+ "hashbrown 0.17.1",  "log",  "peniko",  "png",@@ -1354,6 +1408,18 @@ dependencies = [  "vello_common 0.0.9", ] +[[package]]+name = "gpu-allocator"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795"+dependencies = [+ "ash",+ "log",+ "presser",+ "thiserror 2.0.20",+]+ [[package]] name = "group" version = "0.13.0"@@ -1382,16 +1448,26 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [  "cfg-if",  "crunchy",+ "num-traits",  "zerocopy", ] +[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "foldhash 0.1.5",+]+ [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [- "foldhash",+ "foldhash 0.2.0", ]  [[package]]@@ -1436,7 +1512,7 @@ dependencies = [  "kurbo",  "moxcms",  "phf",- "rustc-hash",+ "rustc-hash 2.1.3",  "siphasher",  "skrifa",  "smallvec",@@ -1479,7 +1555,7 @@ dependencies = [  "hayro-jbig2",  "hayro-jpeg2000",  "memchr",- "rustc-hash",+ "rustc-hash 2.1.3",  "smallvec",  "zune-jpeg", ]@@ -1726,7 +1802,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [  "equivalent",- "hashbrown",+ "hashbrown 0.17.1",  "serde",  "serde_core", ]@@ -2013,6 +2089,12 @@ dependencies = [  "windows-link", ] +[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+ [[package]] name = "linebender_resource_handle" version = "0.1.1"@@ -2052,6 +2134,72 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]]+name = "logos"+version = "0.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff472f899b4ec2d99161c51f60ff7075eeb3097069a36050d8037a6325eb8154"+dependencies = [+ "logos-derive 0.15.1",+]++[[package]]+name = "logos"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f"+dependencies = [+ "logos-derive 0.16.1",+]++[[package]]+name = "logos-codegen"+version = "0.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "192a3a2b90b0c05b27a0b2c43eecdb7c415e29243acc3f89cc8247a5b693045c"+dependencies = [+ "beef",+ "fnv",+ "lazy_static",+ "proc-macro2",+ "quote",+ "regex-syntax",+ "rustc_version",+ "syn 2.0.119",+]++[[package]]+name = "logos-codegen"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970"+dependencies = [+ "fnv",+ "proc-macro2",+ "quote",+ "regex-automata",+ "regex-syntax",+ "syn 2.0.119",+]++[[package]]+name = "logos-derive"+version = "0.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "605d9697bcd5ef3a42d38efc51541aa3d6a4a25f7ab6d1ed0da5ac632a26b470"+dependencies = [+ "logos-codegen 0.15.1",+]++[[package]]+name = "logos-derive"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31"+dependencies = [+ "logos-codegen 0.16.1",+]+ [[package]] name = "lopdf" version = "0.36.0"@@ -2127,6 +2275,28 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]]+name = "miette"+version = "7.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"+dependencies = [+ "cfg-if",+ "miette-derive",+ "unicode-width 0.1.14",+]++[[package]]+name = "miette-derive"+version = "7.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]+ [[package]] name = "minimal-lexical" version = "0.2.1"@@ -2153,6 +2323,17 @@ dependencies = [  "simd-adler32", ] +[[package]]+name = "ml_vulkan"+version = "0.1.0"+dependencies = [+ "anyhow",+ "jni",+ "log",+ "onnx-vulkan",+ "thiserror 2.0.20",+]+ [[package]] name = "moxcms" version = "0.8.1"@@ -2163,6 +2344,50 @@ dependencies = [  "pxfm", ] +[[package]]+name = "multimap"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"++[[package]]+name = "naga"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"+dependencies = [+ "arrayvec",+ "bit-set",+ "bitflags 2.13.1",+ "cfg-if",+ "cfg_aliases",+ "codespan-reporting",+ "half",+ "hashbrown 0.17.1",+ "indexmap",+ "libm",+ "log",+ "naga-types",+ "num-traits",+ "once_cell",+ "rustc-hash 1.1.0",+ "spirv",+ "thiserror 2.0.20",+ "unicode-ident",+]++[[package]]+name = "naga-types"+version = "30.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"+dependencies = [+ "hashbrown 0.17.1",+ "indexmap",+ "rustc-hash 1.1.0",+ "thiserror 2.0.20",+]+ [[package]] name = "network_location_position_estimation_rust" version = "0.1.0"@@ -2280,6 +2505,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [  "autocfg",+ "libm", ]  [[package]]@@ -2322,6 +2548,53 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" 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",+ "onnx-vulkan-frontend",+ "onnx-vulkan-tune",+ "vk-compute",+]++[[package]]+name = "onnx-vulkan-core"+version = "0.0.1"+source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b"+dependencies = [+ "anyhow",+ "log",+ "sha2 0.11.0",+ "vk-compute",+]++[[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",+ "prost 0.14.4",+ "prost-build",+ "protox",+]++[[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",+ "serde",+ "serde_json",+ "sha2 0.11.0",+]+ [[package]] name = "oorandom" version = "11.1.5"@@ -2451,6 +2724,17 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]]+name = "petgraph"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"+dependencies = [+ "fixedbitset",+ "hashbrown 0.15.5",+ "indexmap",+]+ [[package]] name = "phf" version = "0.13.1"@@ -2623,6 +2907,22 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" +[[package]]+name = "presser"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"++[[package]]+name = "prettyplease"+version = "0.2.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+dependencies = [+ "proc-macro2",+ "syn 2.0.119",+]+ [[package]] name = "primeorder" version = "0.13.6"@@ -2660,7 +2960,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" dependencies = [  "bytes",- "prost-derive",+ "prost-derive 0.13.5",+]++[[package]]+name = "prost"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"+dependencies = [+ "bytes",+ "prost-derive 0.14.4",+]++[[package]]+name = "prost-build"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"+dependencies = [+ "heck",+ "itertools 0.10.5",+ "log",+ "multimap",+ "petgraph",+ "prettyplease",+ "prost 0.14.4",+ "prost-types",+ "regex",+ "syn 2.0.119",+ "tempfile", ]  [[package]]@@ -2676,6 +3005,40 @@ dependencies = [  "syn 2.0.119", ] +[[package]]+name = "prost-derive"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"+dependencies = [+ "anyhow",+ "itertools 0.10.5",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "prost-reflect"+version = "0.16.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1"+dependencies = [+ "logos 0.16.1",+ "miette",+ "prost 0.14.4",+ "prost-types",+]++[[package]]+name = "prost-types"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"+dependencies = [+ "prost 0.14.4",+]+ [[package]] name = "protobuf" version = "3.7.2"@@ -2727,6 +3090,33 @@ dependencies = [  "thiserror 1.0.69", ] +[[package]]+name = "protox"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1"+dependencies = [+ "bytes",+ "miette",+ "prost 0.14.4",+ "prost-reflect",+ "prost-types",+ "protox-parse",+ "thiserror 2.0.20",+]++[[package]]+name = "protox-parse"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "072eee358134396a4643dff81cfff1c255c9fbd3fb296be14bdb6a26f9156366"+dependencies = [+ "logos 0.15.1",+ "miette",+ "prost-types",+ "thiserror 2.0.20",+]+ [[package]] name = "psl" version = "2.1.223"@@ -2962,6 +3352,12 @@ dependencies = [  "crossbeam-utils", ] +[[package]]+name = "rustc-hash"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"+ [[package]] name = "rustc-hash" version = "2.1.3"@@ -3168,7 +3564,7 @@ dependencies = [  "jni",  "np_adv",  "p256",- "prost",+ "prost 0.13.5",  "rand_core 0.6.4",  "sha2 0.11.0",  "ukey2_connections",@@ -3237,6 +3633,15 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +[[package]]+name = "spirv"+version = "0.4.0+sdk-1.4.341.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"+dependencies = [+ "bitflags 2.13.1",+]+ [[package]] name = "spki" version = "0.7.3"@@ -3586,6 +3991,18 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +[[package]]+name = "unicode-width"+version = "0.1.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"+ [[package]] name = "universal-hash" version = "0.5.1"@@ -3641,7 +4058,7 @@ dependencies = [  "bytemuck",  "fearless_simd",  "guillotiere",- "hashbrown",+ "hashbrown 0.17.1",  "log",  "peniko",  "png",@@ -3658,7 +4075,7 @@ dependencies = [  "bytemuck",  "fearless_simd",  "guillotiere",- "hashbrown",+ "hashbrown 0.17.1",  "log",  "peniko",  "png",@@ -3674,7 +4091,7 @@ checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0" dependencies = [  "bytemuck",  "glifo",- "hashbrown",+ "hashbrown 0.17.1",  "png",  "vello_common 0.0.8", ]@@ -3692,6 +4109,18 @@ dependencies = [  "jpeg-decoder", ] +[[package]]+name = "vk-compute"+version = "0.0.1"+source = "git+https://github.com/automataIA/onnx-vulkan-rs?rev=c3aa968#c3aa96803575559554089c2f7b2417f2a66f5a0b"+dependencies = [+ "anyhow",+ "ash",+ "gpu-allocator",+ "log",+ "naga",+]+ [[package]] name = "vpn_wireguard" version = "0.1.0"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 0d12779d47..7af0724a7e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -15,6 +15,7 @@ members = [   "library/e2ee-p2p/src/main/rust",   "library/jni-http/src/main/rust",   "library/map/src/main/rust",+  "library/ml/src/main/rust",   "library/vision/src/main/rust",   "measure/src/main/rust",   "communicate/src/main/rust",
camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.ktnew file mode 100644index 0000000000..c8b1dfbd63--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LensModel.kt@@ -0,0 +1,48 @@+package com.vayunmathur.camera.domain++/**+ * Which side of the device a lens sits on.+ *+ * Pure JVM (no CameraX dependency); the platform layer maps these to+ * `CameraSelector.LENS_FACING_*` when building selectors.+ */+enum class LensFacing {+    BACK,+    FRONT,+}++/**+ * Physical role of a lens within its facing family, derived from the HAL focal+ * lengths at enumeration time (smallest = ultra-wide … largest = telephoto).+ */+enum class LensType {+    ULTRA_WIDE,+    WIDE,+    TELEPHOTO,+    MONOCHROME,+    FRONT,+}++/**+ * One physical lens enumerated from the device.+ *+ * @param logicalCameraId the Camera2 logical camera ID backing this lens; used+ *   by the platform selector filter to pin a bind to this module.+ * @param focalLengthMm35Eq 35mm-equivalent focal length when the HAL reports+ *   it; null when unavailable (label falls back to the nominal zoom ratio).+ * @param nominalZoomRatio zoom ratio of this lens relative to the wide (1x)+ *   lens of the same facing, e.g. ~0.5 for UW, 1 for wide, 3+ for tele.+ * @param fallbackPriority lower wins when falling back within the same+ *   facing (wide/front default = 0).+ * @param labelKey stable key for the display label ("ultrawide", "wide",+ *   "tele", "mono", "front"); the UI maps it to `strings.xml`.+ */+data class PhysicalLens(+    val logicalCameraId: String,+    val lensType: LensType,+    val facing: LensFacing,+    val focalLengthMm35Eq: Float?,+    val nominalZoomRatio: Float,+    val fallbackPriority: Int,+    val labelKey: String,+)
camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt b/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.ktnew file mode 100644index 0000000000..7a87cb4e0f--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/domain/LensSelectionLogic.kt@@ -0,0 +1,118 @@+package com.vayunmathur.camera.domain++import kotlin.math.abs+import kotlin.math.roundToInt++/**+ * Pure lens-selection logic with no Android/CameraX dependency, so it stays+ * JVM unit-testable (mirrors `backup/.../CryptoTest.kt`: kotlin.test + JUnit4).+ *+ * The platform layer enumerates [PhysicalLens] entries; everything here only+ * reasons over that model plus per-lens capability snapshots passed in.+ */+object LensSelectionLogic {++    /** Lenses on [facing], ordered by [PhysicalLens.fallbackPriority]. */+    fun filterByFacing(lenses: List<PhysicalLens>, facing: LensFacing): List<PhysicalLens> =+        lenses.filter { it.facing == facing }.sortedBy { it.fallbackPriority }++    /**+     * Fallback ladder for a requested lens: the lens itself, then the rest of+     * the same-facing family in [PhysicalLens.fallbackPriority] order. Never+     * empty when the family is non-empty; null only when no lens of that+     * facing exists.+     */+    fun fallbackFor(requested: PhysicalLens, family: List<PhysicalLens>): PhysicalLens? {+        if (family.isEmpty()) return null+        if (requested in family) return requested+        return family.minByOrNull { it.fallbackPriority }+    }++    /**+     * Zoom-level pills for one lens: the UW floor (e.g. ".5") when the lens+     * can zoom out past 1x, always "1x", then tele stops (2x/5x) that fit in+     * [maxZoom]. Mirrors `updateZoomLevels` in `util/CameraControls.kt`.+     */+    fun buildZoomLevels(minZoom: Float, maxZoom: Float): List<Pair<String, Float>> {+        val levels = mutableListOf<Pair<String, Float>>()+        if (minZoom < 0.95f) {+            levels.add(formatZoomLabel(minZoom) to minZoom)+        }+        levels.add("1x" to 1f)+        for (tele in listOf(2f, 5f)) {+            if (tele <= maxZoom + 0.05f) levels.add(formatZoomLabel(tele) to tele)+        }+        return levels+    }++    /**+     * Display label for a lens: 35mm-equivalent focal length ("24mm") when+     * known, else the nominal zoom ratio ("0.5x"/"1x"/"3x").+     */+    fun displayLabel(lens: PhysicalLens): String {+        val mm = lens.focalLengthMm35Eq+        if (mm != null && mm > 0f) return "${mm.roundToInt()}mm"+        return formatZoomLabel(lens.nominalZoomRatio)+    }++    /**+     * Human focal-length label key for strings: delegates to the lens'+     * [PhysicalLens.labelKey]; kept pure so label mapping stays testable.+     */+    fun labelKey(lens: PhysicalLens): String = lens.labelKey++    /**+     * Filters the canonical ISO stop list to the sensor's [range]+     * (inclusive). Falls back to the range endpoints when nothing canonical+     * fits, and to empty when the range is unknown — mirroring+     * `readManualControlRanges` in `util/CameraManualControls.kt`.+     */+    fun filterIsoStops(range: ClosedRange<Int>?): List<Int> {+        if (range == null) return emptyList()+        val filtered = listOf(50, 100, 200, 400, 800, 1600, 3200, 6400, 12800)+            .filter { it in range }+        return filtered.ifEmpty { listOf(range.start, range.endInclusive) }+    }++    /**+     * Picks the stable fixed fps range for regular video: only fixed ranges+     * (lower == upper) avoid variable-fps sensor-mode flicker; prefer 30fps,+     * then 60fps, then the closest fixed. Null when no fixed range exists so+     * CameraX picks its default. Cinematic sticks to <= 30fps. Mirrors+     * `highestFpsRange` in `util/CameraSessions.kt`.+     */+    fun pickFpsRange(ranges: List<Pair<Int, Int>>, cinematic: Boolean): Pair<Int, Int>? {+        val fixed = ranges.filter { (lower, upper) -> lower == upper }+        if (fixed.isEmpty()) return null+        if (cinematic) {+            return fixed.firstOrNull { it.second == 30 }+                ?: fixed.filter { it.second <= 30 }.maxByOrNull { it.second }+                ?: fixed.minByOrNull { abs(it.second - 30) }+        }+        return fixed.firstOrNull { it.second == 30 }+            ?: fixed.firstOrNull { it.second == 60 }+            ?: fixed.filter { it.second <= 30 }.maxByOrNull { it.second }+            ?: fixed.filter { it.second <= 60 }.maxByOrNull { it.second }+            ?: fixed.minByOrNull { abs(it.second - 30) }+    }++    /**+     * Whether the cached night-extension failure (recorded at [failedAtMs],+     * [nowMs]) is still within the TTL ([ttlMs], default the ViewModel's+     * 7-day `NIGHT_EXT_FAILURE_TTL_MS`). True = don't offer night yet.+     */+    fun nightFailureFresh(failedAtMs: Long?, nowMs: Long, ttlMs: Long): Boolean {+        if (failedAtMs == null) return false+        return nowMs - failedAtMs < ttlMs+    }++    /** Formats a zoom ratio: ".5", "1x", "2x", "1.5x" (mirrors `formatZoomLabel`). */+    fun formatZoomLabel(ratio: Float): String = when {+        ratio < 1f -> ".${(ratio * 10).roundToInt()}"+        else -> {+            val rounded = (ratio * 10f).roundToInt() / 10f+            if (abs(rounded - rounded.roundToInt()) < 0.05f) "${rounded.roundToInt()}x"+            else "%.1fx".format(rounded)+        }+    }+}
camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.ktnew file mode 100644index 0000000000..9554fb1d92--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/CameraCapabilities.kt@@ -0,0 +1,92 @@+package com.vayunmathur.camera.platform++import android.util.Log+import androidx.camera.camera2.interop.ExperimentalCamera2Interop+import androidx.camera.core.Camera+import com.vayunmathur.camera.domain.LensSelectionLogic+import com.vayunmathur.camera.util.CameraViewModel+import com.vayunmathur.camera.util.readManualControlRanges+import com.vayunmathur.camera.util.refreshNightExtensionUsable+import com.vayunmathur.camera.util.restoreZoom+import com.vayunmathur.camera.util.updateZoomLevels+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Per-lens capability snapshot refreshed after every bind, so the UI (zoom+ * pills, flash availability, ISO stops, night/slo-mo affordances) reflects the+ * lens that actually bound rather than the previous one.+ */+data class LensCapabilities(+    val lensId: String?,+    val minZoom: Float,+    val maxZoom: Float,+    val zoomLevels: List<Pair<String, Float>>,+    val hasFlashUnit: Boolean,+    val isoStops: List<Int>,+    val exposureCompRange: ClosedRange<Float>?,+    val nightExtensionUsable: Boolean,+)++/**+ * Re-probes everything the UI derives from the bound camera and publishes it+ * on the ViewModel. Reuses the existing per-bind probes+ * ([updateZoomLevels]/[restoreZoom], [readManualControlRanges],+ * [observeNightModeIndicator], [refreshNightExtensionUsable]) and adds the+ * missing coverage: flash-unit availability per lens.+ *+ * Call on the main thread (LiveData `observeForever` expects it); the heavier+ * extension probe hops to Dispatchers.Default like the UI's launcher effect.+ */+@OptIn(ExperimentalCamera2Interop::class)+suspend fun CameraViewModel.refreshCapabilities(bound: Camera, lensId: String?) {+    val zs = try {+        bound.cameraInfo.zoomState.value+    } catch (e: Exception) {+        Log.w("LensSelector", "Could not read zoom state", e)+        null+    }+    val minZoom = zs?.minZoomRatio ?: 1f+    val maxZoom = zs?.maxZoomRatio ?: 1f+    updateZoomLevels(minZoom, maxZoom)+    restoreZoom(minZoom, maxZoom)++    readManualControlRanges()++    val hasFlash = try {+        bound.cameraInfo.hasFlashUnit()+    } catch (e: Exception) {+        Log.w("LensSelector", "Could not query flash unit", e)+        _hasFlashUnit.value+    }+    _hasFlashUnit.value = hasFlash++    val expRange = try {+        val r = bound.cameraInfo.exposureState.exposureCompensationRange+        r.lower.toFloat()..r.upper.toFloat()+    } catch (e: Exception) {+        Log.w("LensSelector", "Could not query exposure-compensation range", e)+        null+    }+    if (expRange != null) _exposureCompRange.value = expRange++    // Skip the night indicator here: the setup paths own that observation, and+    // re-observing the *extension* camera reports UNKNOWN/NOT_RECOMMENDED, which+    // fights the normal session's RECOMMENDED reading (engage/disengage loop —+    // see the note in setupNightPreviewSession).+    withContext(Dispatchers.Default) {+        refreshNightExtensionUsable(_cameraMode.value)+    }++    _lensCapabilities.value = LensCapabilities(+        lensId = lensId,+        minZoom = minZoom,+        maxZoom = maxZoom,+        zoomLevels = LensSelectionLogic.buildZoomLevels(minZoom, maxZoom),+        hasFlashUnit = hasFlash,+        isoStops = _isoStops.value,+        exposureCompRange = expRange ?: _lensCapabilities.value?.exposureCompRange,+        nightExtensionUsable = _nightExtensionUsable.value,+    )+    Log.d("LensSelector", "Refreshed capabilities lens=$lensId zoom=[$minZoom,$maxZoom] flash=$hasFlash")+}
camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.ktnew file mode 100644index 0000000000..00a823f435--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/platform/LensSelector.kt@@ -0,0 +1,218 @@+package com.vayunmathur.camera.platform++import android.hardware.camera2.CameraCharacteristics+import android.hardware.camera2.CameraMetadata+import android.util.Log+import androidx.camera.camera2.interop.Camera2CameraInfo+import androidx.camera.camera2.interop.ExperimentalCamera2Interop+import androidx.camera.core.Camera+import androidx.camera.core.CameraSelector+import androidx.camera.lifecycle.ProcessCameraProvider+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.domain.LensSelectionLogic+import com.vayunmathur.camera.domain.LensType+import com.vayunmathur.camera.domain.PhysicalLens+import com.vayunmathur.camera.util.CameraViewModel+import kotlin.math.sqrt++/** Maps the pure [LensFacing] to the CameraX selector constant. */+fun LensFacing.toSelectorInt(): Int = when (this) {+    LensFacing.BACK -> CameraSelector.LENS_FACING_BACK+    LensFacing.FRONT -> CameraSelector.LENS_FACING_FRONT+}++/** Maps a CameraX lens-facing constant to [LensFacing]; null for external/unknown. */+fun Int.toLensFacing(): LensFacing? = when (this) {+    CameraSelector.LENS_FACING_BACK -> LensFacing.BACK+    CameraSelector.LENS_FACING_FRONT -> LensFacing.FRONT+    else -> null+}++/**+ * Enumerates every physical/logical lens via [ProcessCameraProvider.availableCameraInfos]+ * plus `Camera2CameraInfo` interop (camera ID, `LENS_FACING`, focal lengths, sensor+ * physical size for the 35mm-equivalent label, mono color-filter detection).+ *+ * Types are assigned per facing family sorted by focal length: the lens whose+ * 35mm-equivalent is closest to ~27mm is the wide reference (1x); shorter is+ * ultra-wide, longer is telephoto; a MONO color-filter arrangement wins over the+ * focal heuristic. Front-facing families mark their reference lens FRONT.+ *+ * Safe to call off the main thread; never throws (returns empty on failure).+ */+@OptIn(ExperimentalCamera2Interop::class)+fun enumerateLenses(provider: ProcessCameraProvider): List<PhysicalLens> {+    data class Raw(+        val id: String,+        val facing: LensFacing,+        val focalMm: Float,+        val eq35Mm: Float?,+        val mono: Boolean,+    )+    val raws = provider.availableCameraInfos.mapNotNull { info ->+        try {+            val cam2 = Camera2CameraInfo.from(info)+            val facing = when (+                cam2.getCameraCharacteristic(CameraCharacteristics.LENS_FACING)+            ) {+                CameraMetadata.LENS_FACING_FRONT -> LensFacing.FRONT+                CameraMetadata.LENS_FACING_BACK -> LensFacing.BACK+                else -> return@mapNotNull null // External / unknown: not a phone lens.+            }+            val focal = cam2.getCameraCharacteristic(+                CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS+            )?.firstOrNull() ?: return@mapNotNull null+            val sensorSize = cam2.getCameraCharacteristic(+                CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE+            )+            val eq35 = if (sensorSize != null && sensorSize.width > 0 && sensorSize.height > 0) {+                val diag = sqrt(sensorSize.width * sensorSize.width + sensorSize.height * sensorSize.height)+                focal * 43.27f / diag+            } else {+                null+            }+            val mono = cam2.getCameraCharacteristic(+                CameraCharacteristics.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT+            ) == CameraMetadata.SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MONO+            Raw(cam2.getCameraId(), facing, focal, eq35, mono)+        } catch (e: Exception) {+            Log.w("LensSelector", "Skipping camera info during lens enumeration", e)+            null+        }+    }++    return LensFacing.entries.flatMap { facing ->+        val family = raws.filter { it.facing == facing }.sortedBy { it.focalMm }+        if (family.isEmpty()) return@flatMap emptyList()+        val nonMono = family.filterNot { it.mono }+        // Wide reference: 35mm-eq closest to ~27mm; fall back to the median focal length.+        val reference = nonMono.minByOrNull { it.eq35Mm?.let { eq -> kotlin.math.abs(eq - 27f) } ?: Float.MAX_VALUE }+            ?: nonMono.getOrNull(nonMono.size / 2)+            ?: family.first()+        family.map { raw ->+            val type = when {+                raw.mono -> LensType.MONOCHROME+                raw == reference && facing == LensFacing.FRONT -> LensType.FRONT+                raw == reference -> LensType.WIDE+                raw.focalMm < reference.focalMm * 0.85f -> LensType.ULTRA_WIDE+                raw.focalMm > reference.focalMm * 1.4f -> LensType.TELEPHOTO+                else -> LensType.WIDE+            }+            PhysicalLens(+                logicalCameraId = raw.id,+                lensType = type,+                facing = facing,+                focalLengthMm35Eq = raw.eq35Mm,+                nominalZoomRatio = raw.focalMm / reference.focalMm,+                fallbackPriority = when (type) {+                    LensType.WIDE, LensType.FRONT -> 0+                    LensType.ULTRA_WIDE -> 1+                    LensType.TELEPHOTO -> 2+                    LensType.MONOCHROME -> 3+                },+                labelKey = when (type) {+                    LensType.ULTRA_WIDE -> "ultrawide"+                    LensType.WIDE -> "wide"+                    LensType.TELEPHOTO -> "tele"+                    LensType.MONOCHROME -> "mono"+                    LensType.FRONT -> "front"+                },+            )+        }+    }+}++/**+ * Fills [_availableLenses][com.vayunmathur.camera.util.CameraViewModel] once per+ * process and anchors the default selection (same-facing wide/front). No-op once+ * populated; call at the top of every session setup after obtaining the provider.+ */+fun CameraViewModel.ensureLensesEnumerated(provider: ProcessCameraProvider) {+    if (_availableLenses.value.isNotEmpty()) return+    val all = try {+        enumerateLenses(provider)+    } catch (e: Exception) {+        Log.w("LensSelector", "Lens enumeration failed; sessions fall back to facing-only selectors", e)+        emptyList()+    }+    _availableLenses.value = all+    if (_selectedLens.value == null) {+        val facing = _lensFacing.value.toLensFacing() ?: LensFacing.BACK+        _selectedLens.value = LensSelectionLogic.filterByFacing(all, facing)+            .minByOrNull { it.fallbackPriority }+    }+    Log.d("LensSelector", "Enumerated ${all.size} lenses; selected=${_selectedLens.value?.labelKey}")+}++/** Lenses of the current facing, ordered by fallback priority. */+fun CameraViewModel.currentLensFamily(): List<PhysicalLens> {+    val facing = _lensFacing.value.toLensFacing() ?: LensFacing.BACK+    return LensSelectionLogic.filterByFacing(_availableLenses.value, facing)+}++/**+ * Builds the selector for [facingInt], pinned to [lens] via a `CameraFilter` on+ * the logical camera ID when non-null. A null lens keeps the legacy facing-only+ * behavior.+ */+@OptIn(ExperimentalCamera2Interop::class)+fun CameraViewModel.lensSelector(facingInt: Int, lens: PhysicalLens?): CameraSelector {+    val builder = CameraSelector.Builder().requireLensFacing(facingInt)+    if (lens != null) {+        val id = lens.logicalCameraId+        builder.addCameraFilter { infos ->+            infos.filter { info ->+                try {+                    Camera2CameraInfo.from(info).getCameraId() == id+                } catch (_: Exception) {+                    false+                }+            }+        }+    }+    return builder.build()+}++/**+ * Binds via [bind], retrying down the lens ladder: requested lens → same-facing+ * wide → any same-facing (priority order). When enumeration produced nothing,+ * the ladder is a single facing-only selector — identical to the legacy path.+ *+ * @return the lens that actually bound (null when facing-only) plus the camera.+ */+fun CameraViewModel.bindWithFallback(+    provider: ProcessCameraProvider,+    requested: PhysicalLens?,+    family: List<PhysicalLens>,+    bind: (CameraSelector) -> Camera,+): Pair<PhysicalLens?, Camera> {+    val facingInt = _lensFacing.value+    val ordered = buildList {+        if (requested != null) add(requested)+        family.sortedBy { it.fallbackPriority }.forEach { if (it != requested) add(it) }+        if (requested == null && family.isEmpty()) add(null)+    }+    var lastError: Exception? = null+    var first = true+    for (candidate in ordered) {+        try {+            // The caller unbinds before the first attempt; unbind between retries only.+            if (!first) {+                try {+                    provider.unbindAll()+                } catch (_: Exception) {+                }+            }+            first = false+            val camera = bind(lensSelector(facingInt, candidate))+            if (candidate != requested) {+                Log.w("LensSelector", "Fell back to lens=${candidate?.labelKey} (requested=${requested?.labelKey})")+            }+            return candidate to camera+        } catch (e: Exception) {+            lastError = e+            Log.w("LensSelector", "Bind failed on lens=${candidate?.labelKey}; trying next", e)+        }+    }+    throw lastError ?: IllegalStateException("Lens bind failed with an empty ladder")+}
camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.ktindex f082ac4880..5955824d7c 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraPreviewBox.kt@@ -54,6 +54,12 @@ import com.vayunmathur.camera.util.setWarmth import com.vayunmathur.camera.util.setZoomRatio import com.vayunmathur.camera.util.toggleNightModeOverride +/** Maps the CameraX selector facing int to the pure lens-facing model. */+private fun currentLensFacing(selectorInt: Int): com.vayunmathur.camera.domain.LensFacing =+    if (selectorInt == androidx.camera.core.CameraSelector.LENS_FACING_FRONT)+        com.vayunmathur.camera.domain.LensFacing.FRONT+    else com.vayunmathur.camera.domain.LensFacing.BACK+ /**  * The letterboxed viewfinder plus its gesture handling, bokeh/color RenderEffects,  * grid/level/night overlays, settings column and panorama overlay. Extracted verbatim@@ -99,6 +105,7 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(                     !it.isRecycled && it.width > 0 && it.height > 0                 }                 val hasBokeh = cameraMode == CameraMode.PORTRAIT && currentMask != null+                android.util.Log.d("BokehDebug", "render mode=$cameraMode hasBokeh=$hasBokeh mask=${currentMask?.width}x${currentMask?.height}")                 if (hasBokeh || hasColorAdj) {                     Modifier.graphicsLayer {                         var effect: RenderEffect? = null@@ -234,6 +241,9 @@ internal fun BoxWithConstraintsScope.CameraPreviewBox(      CameraSettingsColumn(         activeSetting = state.activeSetting,+        availableLenses = state.availableLenses.filter { it.facing == currentLensFacing(state.lensFacing) },+        selectedLens = state.selectedLens,+        onLensSelected = { viewModel.selectLens(it) },         zoomRatio = state.zoomRatio,         availableZoomLevels = state.availableZoomLevels,         onZoomSelected = { viewModel.setZoomRatio(it) },
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.ktindex 5d750805b8..f095b71f6c 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenEffects.kt@@ -53,6 +53,7 @@ internal fun CameraScreenEffects(     val context = LocalContext.current     val cameraMode = state.cameraMode     val lensFacing = state.lensFacing+    val selectedLens = state.selectedLens     val sessionKind = state.sessionKind     val useNightPreview = state.useNightPreview @@ -100,7 +101,7 @@ internal fun CameraScreenEffects(     // Whether to offer the NIGHT extension. Reactive: the ViewModel recomputes it on lens/mode     // change (off-main; support probe + weekly failure cache) AND flips it false immediately if a     // night bind fails, so a broken extender (GrapheneOS/Pixel) stops engaging night after one try.-    LaunchedEffect(lensFacing, cameraMode) {+    LaunchedEffect(lensFacing, selectedLens, cameraMode) {         kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Default) {             viewModel.refreshNightExtensionUsable(cameraMode)         }@@ -124,8 +125,9 @@ internal fun CameraScreenEffects(      // Analyzer selection for the photo modes. Keyed on photoSessionActive so the analyzer is     // re-applied to the freshly-bound ImageAnalysis after every (re)bind (mode switch / flip), and-    // on lensFacing to match the DisposableEffect below, which detaches on a flip.-    LaunchedEffect(cameraMode, state.photoSessionActive, lensFacing) {+    // on lensFacing + selectedLens to match the DisposableEffect below, which detaches on a+    // flip or lens switch.+    LaunchedEffect(cameraMode, state.photoSessionActive, lensFacing, selectedLens) {         when {             cameraMode == CameraMode.SLOW_MO -> {                 state.maskBitmap = null@@ -176,21 +178,26 @@ internal fun CameraScreenEffects(     // Mask callback comes from bokeh thread; post recycle+set to main to avoid racing with     // the RenderEffect reading the previous Bitmap on the UI thread.     val mainHandler = remember { android.os.Handler(android.os.Looper.getMainLooper()) }-    DisposableEffect(cameraMode, state.photoSessionActive, lensFacing) {+    DisposableEffect(cameraMode, state.photoSessionActive, lensFacing, selectedLens) {         val analyzer = if (cameraMode == CameraMode.PORTRAIT) {             BokehAnalyzer(                 context,                 isFrontFacing = lensFacing == CameraSelector.LENS_FACING_FRONT             ) { mask ->+                android.util.Log.d("BokehDebug", "mask arrived ${mask.width}x${mask.height} recycled=${mask.isRecycled}")                 if (mask.isRecycled) return@BokehAnalyzer                 mainHandler.post {                     // If mask was recycled while message queued, drop it-                    if (mask.isRecycled) return@post+                    if (mask.isRecycled) {+                        android.util.Log.d("BokehDebug", "mask recycled before post ran")+                        return@post+                    }                     val prev = state.maskBitmap                     if (prev != null && prev !== mask && !prev.isRecycled) {                         try { prev.recycle() } catch (_: Exception) {}                     }                     state.maskBitmap = mask+                    android.util.Log.d("BokehDebug", "mask stored ${mask.width}x${mask.height}")                 }             }.also {                 viewModel.setBokehAnalyzer(it)@@ -220,8 +227,8 @@ internal fun CameraScreenEffects(     // backgrounded and rebound on resume. Without this the ManualLifecycleOwner stays RESUMED,     // the OS reclaims the camera while we're away, and the preview comes back frozen.     val lifecycleOwner = LocalLifecycleOwner.current-    LaunchedEffect(lensFacing, sessionKind, useNightPreview, lifecycleOwner) {-        Log.d("NightPreview", "CameraScreen session LaunchedEffect START keys lensFacing=$lensFacing sessionKind=$sessionKind useNightPreview=$useNightPreview lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}")+    LaunchedEffect(lensFacing, selectedLens, sessionKind, useNightPreview, lifecycleOwner) {+        Log.d("NightPreview", "CameraScreen session LaunchedEffect START keys lensFacing=$lensFacing selectedLens=${selectedLens?.labelKey} sessionKind=$sessionKind useNightPreview=$useNightPreview lifecycle=${lifecycleOwner.lifecycle.currentState} thread=${Thread.currentThread().name}")         lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {             Log.d("NightPreview", "CameraScreen repeatOnLifecycle STARTED – calling teardownSession()")             viewModel.teardownSession()
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 00e016a959..5462c71ea7 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreenState.kt@@ -26,6 +26,9 @@ import com.vayunmathur.camera.util.TimerDuration internal class CameraScreenState(     val cameraMode: CameraMode,     val lensFacing: Int,+    val selectedLens: com.vayunmathur.camera.domain.PhysicalLens?,+    val availableLenses: List<com.vayunmathur.camera.domain.PhysicalLens>,+    val hasFlashUnit: Boolean,     val flashMode: FlashMode,     val torchEnabled: Boolean,     val isRecording: Boolean,@@ -109,6 +112,9 @@ internal class CameraScreenState( internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreenState {     val cameraMode by viewModel.cameraMode.collectAsState()     val lensFacing by viewModel.lensFacing.collectAsState()+    val selectedLens by viewModel.selectedLens.collectAsState()+    val availableLenses by viewModel.availableLenses.collectAsState()+    val hasFlashUnit by viewModel.hasFlashUnit.collectAsState()     val flashMode by viewModel.flashMode.collectAsState()     val torchEnabled by viewModel.torchEnabled.collectAsState()     val isRecording by viewModel.isRecording.collectAsState()@@ -159,7 +165,7 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen     val panoPitch by viewModel.panoramaEngine.currentPitch.collectAsState()      return remember(-        cameraMode, lensFacing, flashMode, torchEnabled, isRecording, recordingDuration,+        cameraMode, lensFacing, selectedLens, availableLenses, hasFlashUnit, flashMode, torchEnabled, isRecording, recordingDuration,         timerCountdown, qrResult, aspectRatio, zoomRatio, mirrorFront, timerDuration,         isCapturing, burstActive, burstCount, focusLocked, recordingPaused, micMuted,         videoSnapshotSupported, lastCaptureUri, gridEnabled, levelEnabled, roll,@@ -173,6 +179,9 @@ internal fun rememberCameraScreenState(viewModel: CameraViewModel): CameraScreen         CameraScreenState(             cameraMode = cameraMode,             lensFacing = lensFacing,+            selectedLens = selectedLens,+            availableLenses = availableLenses,+            hasFlashUnit = hasFlashUnit,             flashMode = flashMode,             torchEnabled = torchEnabled,             isRecording = isRecording,
camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.ktindex f0b8a3ac4a..6e1e34113d 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraSettingsColumn.kt@@ -20,6 +20,9 @@ import com.vayunmathur.library.ui.IconSunny @Composable internal fun CameraSettingsColumn(     activeSetting: CameraSetting?,+    availableLenses: List<com.vayunmathur.camera.domain.PhysicalLens>,+    selectedLens: com.vayunmathur.camera.domain.PhysicalLens?,+    onLensSelected: (com.vayunmathur.camera.domain.PhysicalLens) -> Unit,     zoomRatio: Float,     availableZoomLevels: List<Pair<String, Float>>,     onZoomSelected: (Float) -> Unit,@@ -48,11 +51,18 @@ internal fun CameraSettingsColumn(         verticalArrangement = Arrangement.spacedBy(8.dp)     ) {         when (activeSetting) {-            null -> ZoomBar(-                currentZoom = zoomRatio,-                zoomLevels = availableZoomLevels,-                onZoomSelected = onZoomSelected-            )+            null -> {+                LensBar(+                    lenses = availableLenses,+                    selected = selectedLens,+                    onSelect = onLensSelected+                )+                ZoomBar(+                    currentZoom = zoomRatio,+                    zoomLevels = availableZoomLevels,+                    onZoomSelected = onZoomSelected+                )+            }             CameraSetting.BRIGHTNESS -> HorizontalSettingSlider(                 value = exposureComp,                 onValueChange = onExposureComp,
camera/src/main/java/com/vayunmathur/camera/ui/LensBar.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/LensBar.kt b/camera/src/main/java/com/vayunmathur/camera/ui/LensBar.ktnew file mode 100644index 0000000000..db92c28abd--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/ui/LensBar.kt@@ -0,0 +1,85 @@+package com.vayunmathur.camera.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.camera.R+import com.vayunmathur.camera.domain.LensSelectionLogic+import com.vayunmathur.camera.domain.PhysicalLens+import com.vayunmathur.library.ui.Text++/**+ * Physical-lens picker: one pill per enumerated lens of the current facing+ * (UW / wide / tele / mono), cloned from [ZoomBar] (row container, 36dp+ * [selectedPill], 13sp labels). Hidden when fewer than two lenses are+ * available. Stateless: the caller passes the family plus the selection.+ */+@Composable+fun LensBar(+    lenses: List<PhysicalLens>,+    selected: PhysicalLens?,+    onSelect: (PhysicalLens) -> Unit,+    modifier: Modifier = Modifier,+) {+    if (lenses.size < 2) return+    val pickerDescription = stringResource(R.string.lens_picker_description)+    Row(+        modifier = modifier+            .semantics { contentDescription = pickerDescription }+            .background(Color(0x99000000), RoundedCornerShape(24.dp))+            .padding(horizontal = 6.dp, vertical = 4.dp),+        horizontalArrangement = Arrangement.spacedBy(2.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        lenses.forEach { lens ->+            val isSelected = lens == selected+            Box(+                modifier = Modifier+                    .size(36.dp)+                    .selectedPill(isSelected, CircleShape)+                    .clip(CircleShape)+                    .clickable { onSelect(lens) },+                contentAlignment = Alignment.Center,+            ) {+                Text(+                    lensPillLabel(lens),+                    color = if (isSelected) Color.White else Color(0xFFBBBBBB),+                    fontSize = 13.sp,+                    fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,+                )+            }+        }+    }+}++/** Pill text for one lens: localized short label plus the focal-length readout. */+@Composable+internal fun lensPillLabel(lens: PhysicalLens): String {+    val short = when (lens.labelKey) {+        "ultrawide" -> stringResource(R.string.lens_ultrawide)+        "tele" -> stringResource(R.string.lens_tele)+        "mono" -> stringResource(R.string.lens_mono)+        "front" -> stringResource(R.string.lens_front)+        else -> stringResource(R.string.lens_wide)+    }+    val focal = LensSelectionLogic.displayLabel(lens)+    return if (focal == short || lens.labelKey == "wide" || lens.labelKey == "front") short+    else "$short · $focal"+}
camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.ktindex 69d804adb0..9e627c6b41 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraNightCapture.kt@@ -6,7 +6,6 @@ import android.net.Uri import android.provider.MediaStore import android.util.Log import androidx.camera.camera2.interop.ExperimentalCamera2Interop-import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.core.ImageProxy@@ -16,6 +15,7 @@ import androidx.camera.lifecycle.awaitInstance import androidx.camera.core.Preview import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.platform.lensSelector import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch@@ -49,9 +49,7 @@ internal suspend fun CameraViewModel.captureNightPhotoExtension() {         imageAnalysis = null         _analysisStreamActive.value = false -        val baseSelector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        val baseSelector = lensSelector(_lensFacing.value, _selectedLens.value)         val nightSelector = mgr.getExtensionEnabledCameraSelector(baseSelector, ExtensionMode.NIGHT)          val preview = Preview.Builder().build()
camera/src/main/java/com/vayunmathur/camera/util/CameraNightMode.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraNightMode.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraNightMode.ktindex 4b98590c4f..c5ac13d7d0 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraNightMode.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraNightMode.kt@@ -9,9 +9,9 @@ import androidx.camera.lifecycle.awaitInstance import androidx.camera.core.Preview import androidx.camera.core.ImageCapture import androidx.camera.extensions.ExtensionSessionConfig-import androidx.camera.core.CameraSelector import androidx.core.content.ContextCompat import androidx.lifecycle.viewModelScope+import com.vayunmathur.camera.platform.lensSelector import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume@@ -28,8 +28,8 @@ internal fun CameraViewModel.recordNightExtensionFailure() {  /**  * Re-evaluates whether night should be offered on the current lens/mode. Cheap checks first- * (mode + the daily failure cache), then the isSessionConfigSupported() probe. Heavy — call off- * the main thread.+ * (mode + the daily failure cache), then the isSessionConfigSupported() probe against the+ * selected lens' selector. Heavy — call off the main thread.  */ suspend fun CameraViewModel.refreshNightExtensionUsable(cameraMode: CameraMode) {     _nightExtensionUsable.value = when {@@ -192,9 +192,7 @@ suspend fun CameraViewModel.isNightExtensionAvailable(): Boolean {             Log.w("NightPreview", "isNightExtensionAvailable() manager NULL after ${System.currentTimeMillis() - startMs}ms, returning false -> moon button may show but useNightPreview false, so no visible transition")             return false         }-        val selector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        val selector = lensSelector(_lensFacing.value, _selectedLens.value)         if (!mgr.isExtensionAvailable(selector, ExtensionMode.NIGHT)) {             Log.d("NightPreview", "isNightExtensionAvailable() isExtensionAvailable(NIGHT)=false lens=${_lensFacing.value}")             return false
camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.ktindex e676e102dc..9430c4e9f4 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraPhotoSessions.kt@@ -14,6 +14,11 @@ import androidx.camera.extensions.ExtensionMode import androidx.camera.extensions.ExtensionsManager import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.lifecycle.awaitInstance+import com.vayunmathur.camera.platform.bindWithFallback+import com.vayunmathur.camera.platform.currentLensFamily+import com.vayunmathur.camera.platform.ensureLensesEnumerated+import com.vayunmathur.camera.platform.lensSelector+import com.vayunmathur.camera.platform.refreshCapabilities  /**  * Binds a manual Preview + ImageCapture + ImageAnalysis session for the photo modes@@ -31,9 +36,9 @@ suspend fun CameraViewModel.setupPhotoSession(): Boolean {         Log.d("NightPreview", "setupPhotoSession() got providerHash=${provider.hashCode()}")         provider.unbindAll() -        val selector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        ensureLensesEnumerated(provider)+        val requestedLens = _selectedLens.value+        val lensFamily = currentLensFamily()          val previewBuilder = Preview.Builder()         // Snapshot auto-converged AE ISO/exposure off the repeating preview requests so a@@ -58,17 +63,19 @@ suspend fun CameraViewModel.setupPhotoSession(): Boolean {          // Ultra HDR (JPEG with a gain map) when the sensor/pipeline supports it. Queried once         // here; the bind ladder falls back to plain JPEG if the Ultra HDR combo can't bind.+        // Probed on the requested lens; a facing-only selector is the fallback probe.         val ultraHdrSupported = try {-            val cameraInfo = provider.getCameraInfo(selector)+            val probeSelector = lensSelector(_lensFacing.value, requestedLens)+            val cameraInfo = provider.getCameraInfo(probeSelector)             val caps = ImageCapture.getImageCaptureCapabilities(cameraInfo).supportedOutputFormats.contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)-            Log.d("NightPreview", "setupPhotoSession() ultraHdrSupported=$caps selector=$selector")+            Log.d("NightPreview", "setupPhotoSession() ultraHdrSupported=$caps lens=${requestedLens?.labelKey}")             caps         } catch (e: Exception) {             Log.e("NightPreview", "setupPhotoSession() Could not query Ultra HDR support (was hidden as Warn)", e)             false         } -        fun bind(maxRes: Boolean, ultraHdr: Boolean): Camera {+        fun bind(lensSelector: CameraSelector, maxRes: Boolean, ultraHdr: Boolean): Camera {             Log.d("NightPreview", "setupPhotoSession() bind(maxRes=$maxRes ultraHdr=$ultraHdr) START thread=${Thread.currentThread().name}")             return try {                 val selectorBuilder = ResolutionSelector.Builder()@@ -111,7 +118,7 @@ suspend fun CameraViewModel.setupPhotoSession(): Boolean {                     )                 val analysis = analysisBuilder.build()                 imageAnalysis = analysis-                bindSession(provider, owner, selector, preview, capture, analysis).also {+                bindSession(provider, owner, lensSelector, preview, capture, analysis).also {                     Log.d("NightPreview", "setupPhotoSession() bind SUCCESS res=${it.cameraInfo} zoom min=${it.cameraInfo.zoomState.value?.minZoomRatio} max=${it.cameraInfo.zoomState.value?.maxZoomRatio}")                 }             } catch (e: Exception) {@@ -120,9 +127,15 @@ suspend fun CameraViewModel.setupPhotoSession(): Boolean {             }         } -        // Fallback ladder: UltraHDR+maxres → UltraHDR+default → JPEG+default.+        // Fallback ladder: UltraHDR+maxres → UltraHDR+default → JPEG+default,+        // each rung tried across the lens ladder (requested → wide → any same-facing).+        var boundLensId: String? = null         boundCamera = try {-            bind(maxRes = true, ultraHdr = ultraHdrSupported)+            val (lens, camera) = bindWithFallback(provider, requestedLens, lensFamily) { lensSel ->+                bind(lensSel, maxRes = true, ultraHdr = ultraHdrSupported)+            }+            boundLensId = lens?.logicalCameraId+            camera         } catch (e: Exception) {             Log.e("NightPreview", "setupPhotoSession() Max-res bind failed (was Warn, hidden); retrying at default resolution. This is where resolution becomes lower and cannot take full quality!", e)             try {@@ -131,7 +144,11 @@ suspend fun CameraViewModel.setupPhotoSession(): Boolean {                 Log.e("NightPreview", "setupPhotoSession() unbindAll on fallback failed (hidden)", e2)             }             try {-                bind(maxRes = false, ultraHdr = ultraHdrSupported)+                val (lens, camera) = bindWithFallback(provider, requestedLens, lensFamily) { lensSel ->+                    bind(lensSel, maxRes = false, ultraHdr = ultraHdrSupported)+                }+                boundLensId = lens?.logicalCameraId+                camera             } catch (e2: Exception) {                 Log.e("NightPreview", "setupPhotoSession() default-res ultraHdr=$ultraHdrSupported bind FAILED (was hidden)", e2)                 if (!ultraHdrSupported) throw e2@@ -141,20 +158,18 @@ suspend fun CameraViewModel.setupPhotoSession(): Boolean {                 } catch (e3: Exception) {                     Log.e("NightPreview", "setupPhotoSession() unbindAll on second fallback failed", e3)                 }-                bind(maxRes = false, ultraHdr = false)+                val (lens, camera) = bindWithFallback(provider, requestedLens, lensFamily) { lensSel ->+                    bind(lensSel, maxRes = false, ultraHdr = false)+                }+                boundLensId = lens?.logicalCameraId+                camera             }         }          val zs = boundCamera?.cameraInfo?.zoomState?.value         Log.d("NightPreview", "setupPhotoSession() bound zoomState min=${zs?.minZoomRatio} max=${zs?.maxZoomRatio} ratio=${zs?.zoomRatio} thread=${Thread.currentThread().name}")-        boundCamera?.cameraInfo?.zoomState?.value?.let {-            Log.d("NightPreview", "setupPhotoSession() calling updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio} – should show .5,1x,2x,5x if >1x else only 1x")-            updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-            restoreZoom(it.minZoomRatio, it.maxZoomRatio)-            Log.d("NightPreview", "setupNightPreviewSession() updated zoomRatio=${_zoomRatio.value} levels=${_availableZoomLevels.value}")-        }-        readManualControlRanges()         applyManualControls()+        boundCamera?.let { refreshCapabilities(it, boundLensId) }         boundCamera?.cameraInfo?.let { observeNightModeIndicator(it) }         onSessionBound()         _photoSessionActive.value = true@@ -187,9 +202,11 @@ suspend fun CameraViewModel.setupNightPreviewSession(): Boolean {             Log.w("NightPreview", "setupNightPreviewSession() manager NULL, falling back to normal photo session")             return setupPhotoSession()         }-        val baseSelector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        // Night extension is wide-only on most vendors; pin to the selected lens so the+        // availability probe reflects it, and fall back to normal photo when it can't bind.+        ensureLensesEnumerated(provider)+        val requestedNightLens = _selectedLens.value+        val baseSelector = lensSelector(_lensFacing.value, requestedNightLens)         val extAvail = try {             mgr.isExtensionAvailable(baseSelector, ExtensionMode.NIGHT)         } catch (e: Exception) {@@ -264,12 +281,6 @@ suspend fun CameraViewModel.setupNightPreviewSession(): Boolean {          val zs = boundCamera?.cameraInfo?.zoomState?.value         Log.d("NightPreview", "setupNightPreviewSession() boundCamera zoomState min=${zs?.minZoomRatio} max=${zs?.maxZoomRatio} current=${zs?.zoomRatio} – vendor NIGHT extension often reports 1x-only; this explains zoom bar disappearing (only 1x). Full-res capture is still max-res? No, extension uses default resolution, lower than max-res photo session, cannot take full quality while in extension preview")-        boundCamera?.cameraInfo?.zoomState?.value?.let {-            Log.d("NightPreview", "setupNightPreviewSession() calling updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}")-            updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-            restoreZoom(it.minZoomRatio, it.maxZoomRatio)-            Log.d("NightPreview", "setupPanoramaSession() levels=${_availableZoomLevels.value}")-        }         // Do NOT observe getNightModeIndicator() on the extension camera: it reports         // UNKNOWN/NOT_RECOMMENDED there, which fights the normal session's RECOMMENDED reading         // and flips _lowLightDetected → an engage/disengage toggle loop. Night stays engaged@@ -280,6 +291,7 @@ suspend fun CameraViewModel.setupNightPreviewSession(): Boolean {             observeExtensionStrength(it)             observeExtensionCameraState(it)         }+        boundCamera?.let { refreshCapabilities(it, requestedNightLens?.logicalCameraId) }         onSessionBound()         _nightPreviewActive.value = true         _photoSessionActive.value = true@@ -317,9 +329,9 @@ suspend fun CameraViewModel.setupPanoramaSession(): Boolean {         cameraProvider = provider         provider.unbindAll() -        val selector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        ensureLensesEnumerated(provider)+        val panoLens = _selectedLens.value+        val panoFamily = currentLensFamily()          val previewBuilder = Preview.Builder()         val preview = previewBuilder.build()@@ -336,7 +348,7 @@ suspend fun CameraViewModel.setupPanoramaSession(): Boolean {         // churn) heavy enough to jank the preview during the sweep. ~3 MP keeps         // it smooth. Falls back to the device-default analysis resolution if         // this bound can't bind.-        fun bind(capped: Boolean): Camera {+        fun bind(lensSelector: CameraSelector, capped: Boolean): Camera {             val analysisBuilder = ImageAnalysis.Builder()                 .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)             if (capped) {@@ -354,12 +366,17 @@ suspend fun CameraViewModel.setupPanoramaSession(): Boolean {             val analysis = analysisBuilder.build()             imageAnalysis = analysis             imageCapture = null // No ImageCapture in this session.-            return bindSession(provider, owner, selector, preview, analysis)+            return bindSession(provider, owner, lensSelector, preview, analysis)         } +        var panoBoundLensId: String? = null         boundCamera = try {             Log.d("NightPreview", "setupPanoramaSession() bind capped=true START")-            bind(capped = true)+            val (lens, camera) = bindWithFallback(provider, panoLens, panoFamily) { lensSel ->+                bind(lensSel, capped = true)+            }+            panoBoundLensId = lens?.logicalCameraId+            camera         } catch (e: Exception) {             Log.e("NightPreview", "setupPanoramaSession() Capped panorama bind FAILED (was hidden as Warn), retrying at default – resolution lower!", e)             try {@@ -369,7 +386,11 @@ suspend fun CameraViewModel.setupPanoramaSession(): Boolean {                 Log.e("NightPreview", "setupPanoramaSession() fallback unbindAll FAILED (swallowed)", e2)             }             try {-                bind(capped = false)+                val (lens, camera) = bindWithFallback(provider, panoLens, panoFamily) { lensSel ->+                    bind(lensSel, capped = false)+                }+                panoBoundLensId = lens?.logicalCameraId+                camera             } catch (e2: Exception) {                 Log.e("NightPreview", "setupPanoramaSession() default bind ALSO FAILED – black root ${e2.javaClass.simpleName} ${e2.message}", e2)                 throw e2@@ -378,12 +399,7 @@ suspend fun CameraViewModel.setupPanoramaSession(): Boolean {          val zsP = boundCamera?.cameraInfo?.zoomState?.value         Log.d("NightPreview", "setupPanoramaSession() bound zoom min=${zsP?.minZoomRatio} max=${zsP?.maxZoomRatio} ratio=${zsP?.zoomRatio}")-        boundCamera?.cameraInfo?.zoomState?.value?.let {-            Log.d("NightPreview", "setupPanoramaSession() updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}")-            updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-            restoreZoom(it.minZoomRatio, it.maxZoomRatio)-            Log.d("NightPreview", "setupPortraitSession() after update levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}")-        }+        boundCamera?.let { refreshCapabilities(it, panoBoundLensId) }         onSessionBound()         _photoSessionActive.value = true         Log.d("NightPreview", "setupPanoramaSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}")@@ -413,9 +429,9 @@ suspend fun CameraViewModel.setupPortraitSession(): Boolean {         Log.d("NightPreview", "setupPortraitSession() providerHash=${provider.hashCode()}")         provider.unbindAll() -        val selector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        ensureLensesEnumerated(provider)+        val portraitLens = _selectedLens.value+        val portraitFamily = currentLensFamily()          val previewBuilder = Preview.Builder()         try {@@ -436,9 +452,9 @@ suspend fun CameraViewModel.setupPortraitSession(): Boolean {         sessionLifecycleOwner = owner          val ultraHdrSupported = try {-            val cameraInfo = provider.getCameraInfo(selector)+            val cameraInfo = provider.getCameraInfo(lensSelector(_lensFacing.value, portraitLens))             val sup = ImageCapture.getImageCaptureCapabilities(cameraInfo).supportedOutputFormats.contains(ImageCapture.OUTPUT_FORMAT_JPEG_ULTRA_HDR)-            Log.d("NightPreview", "setupPortraitSession() ultraHdrSupported=$sup")+            Log.d("NightPreview", "setupPortraitSession() ultraHdrSupported=$sup lens=${portraitLens?.labelKey}")             sup         } catch (e: Exception) {             Log.e("NightPreview", "setupPortraitSession() Could not query Ultra HDR support (hidden)", e)@@ -446,6 +462,7 @@ suspend fun CameraViewModel.setupPortraitSession(): Boolean {         }          fun bind(+            lensSelector: CameraSelector,             cappedAnalysis: Boolean,             maxResCapture: Boolean,             ultraHdr: Boolean@@ -485,7 +502,7 @@ suspend fun CameraViewModel.setupPortraitSession(): Boolean {                 }                 val analysis = analysisBuilder.build()                 imageAnalysis = analysis-                bindSession(provider, owner, selector, preview, capture, analysis).also {+                bindSession(provider, owner, lensSelector, preview, capture, analysis).also {                     Log.d("NightPreview", "setupPortraitSession() bind SUCCESS capped=$cappedAnalysis maxRes=$maxResCapture ultra=$ultraHdr zoom min=${it.cameraInfo.zoomState.value?.minZoomRatio} max=${it.cameraInfo.zoomState.value?.maxZoomRatio}")                 }             } catch (e: Exception) {@@ -511,39 +528,47 @@ suspend fun CameraViewModel.setupPortraitSession(): Boolean {         }          var bound: Camera? = null+        var portraitBoundLensId: String? = null         var lastError: Exception? = null         for ((capped, maxRes, ultra) in attempts) {-            try {-                if (bound != null) {-                    Log.d("NightPreview", "setupPortraitSession() unbindAll before attempt capped=$capped maxRes=$maxRes ultra=$ultra")-                    provider.unbindAll()-                }-                bound = bind(capped, maxRes, ultra)-                Log.d("NightPreview", "setupPortraitSession() bind ladder SUCCESS capped=$capped maxRes=$maxRes ultra=$ultra zoom min=${bound.cameraInfo.zoomState.value?.minZoomRatio} max=${bound.cameraInfo.zoomState.value?.maxZoomRatio}")-                break-            } catch (e: Exception) {-                lastError = e-                Log.e("NightPreview", "setupPortraitSession() Portrait bind failed (capped=$capped maxRes=$maxRes ultra=$ultra) – was Warn with swallowed stack, root of black? ${e.javaClass.simpleName} msg=${e.message}", e)+            // Each resolution rung is tried across the lens ladder (requested → wide → any).+            val lensOrdered = buildList {+                if (portraitLens != null) add(portraitLens)+                portraitFamily.sortedBy { it.fallbackPriority }.forEach { if (it != portraitLens) add(it) }+                if (portraitLens == null && portraitFamily.isEmpty()) add(null)+            }+            var rungBound = false+            for (candidate in lensOrdered) {                 try {                     provider.unbindAll()-                } catch (e2: Exception) {-                    Log.e("NightPreview", "setupPortraitSession() unbindAll in catch FAILED (hidden)", e2)+                    bound = bind(lensSelector(_lensFacing.value, candidate), capped, maxRes, ultra)+                    portraitBoundLensId = candidate?.logicalCameraId+                    if (candidate != portraitLens) {+                        Log.w("LensSelector", "Portrait fell back to lens=${candidate?.labelKey}")+                    }+                    Log.d("NightPreview", "setupPortraitSession() bind ladder SUCCESS capped=$capped maxRes=$maxRes ultra=$ultra lens=${candidate?.labelKey} zoom min=${bound.cameraInfo.zoomState.value?.minZoomRatio} max=${bound.cameraInfo.zoomState.value?.maxZoomRatio}")+                    rungBound = true+                    break+                } catch (e: Exception) {+                    lastError = e+                    Log.e("NightPreview", "setupPortraitSession() Portrait bind failed (capped=$capped maxRes=$maxRes ultra=$ultra lens=${candidate?.labelKey}) – was Warn with swallowed stack, root of black? ${e.javaClass.simpleName} msg=${e.message}", e)+                    try {+                        provider.unbindAll()+                    } catch (e2: Exception) {+                        Log.e("NightPreview", "setupPortraitSession() unbindAll in catch FAILED (hidden)", e2)+                    }                 }             }+            if (rungBound) break         }         if (bound == null) Log.e("NightPreview", "setupPortraitSession() ALL attempts FAILED! lastError=${lastError?.javaClass?.simpleName} ${lastError?.message} – produces black preview?", lastError ?: Exception("none"))         boundCamera = bound ?: throw (lastError ?: IllegalStateException("Portrait session bind failed"))          val zsPor = boundCamera?.cameraInfo?.zoomState?.value         Log.d("NightPreview", "setupPortraitSession() final zoom min=${zsPor?.minZoomRatio} max=${zsPor?.maxZoomRatio} ratio=${zsPor?.zoomRatio} – if max=1, zoom bar will show only 1x")-        boundCamera?.cameraInfo?.zoomState?.value?.let {-            Log.d("NightPreview", "setupPortraitSession() updateZoomLevels min=${it.minZoomRatio} max=${it.maxZoomRatio}")-            updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-            restoreZoom(it.minZoomRatio, it.maxZoomRatio)-        }         _sloMoSupported.value = true-        readManualControlRanges()         applyManualControls()+        boundCamera?.let { refreshCapabilities(it, portraitBoundLensId) }         onSessionBound()         _photoSessionActive.value = true         Log.d("NightPreview", "setupPortraitSession() SUCCESS photoActive=true surface=${_surfaceRequest.value?.resolution}")
camera/src/main/java/com/vayunmathur/camera/util/CameraSloMoSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraSloMoSession.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraSloMoSession.ktindex 79dbfcd288..1be689c1a2 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraSloMoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraSloMoSession.kt@@ -12,6 +12,11 @@ import androidx.camera.video.Quality import androidx.camera.video.QualitySelector import androidx.camera.video.Recorder import androidx.camera.video.VideoCapture+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.domain.LensSelectionLogic+import com.vayunmathur.camera.platform.ensureLensesEnumerated+import com.vayunmathur.camera.platform.lensSelector+import com.vayunmathur.camera.platform.refreshCapabilities  /**  * Sets up a true high-speed (HFR) session for Slo-Mo.@@ -35,9 +40,12 @@ suspend fun CameraViewModel.setupHighSpeedSession(): Boolean {         if (_lensFacing.value != CameraSelector.LENS_FACING_BACK) {             _lensFacing.value = CameraSelector.LENS_FACING_BACK         }-        val selector = CameraSelector.Builder()-            .requireLensFacing(CameraSelector.LENS_FACING_BACK)-            .build()+        ensureLensesEnumerated(provider)+        // Slo-Mo binds the requested back lens when possible (HFR is often wide-only);+        // each HFR range attempt below retries across the back family.+        val requestedSloMoLens = _selectedLens.value?.takeIf { it.facing == LensFacing.BACK }+        val sloMoFamily = LensSelectionLogic.filterByFacing(_availableLenses.value, LensFacing.BACK)+        val selector = lensSelector(CameraSelector.LENS_FACING_BACK, requestedSloMoLens)          val cameraInfo = provider.getCameraInfo(selector)         val capabilities = Recorder.getHighSpeedVideoCapabilities(cameraInfo)@@ -112,34 +120,48 @@ suspend fun CameraViewModel.setupHighSpeedSession(): Boolean {         }          var bound = false+        var boundSloMoLensId: String? = null         var lastError: Exception? = null-        for (range in hfrRanges) {-            try {-                provider.unbindAll()-                // Re-attach surface provider after unbindAll for preview to re-emit request-                preview.setSurfaceProvider { request -> _surfaceRequest.value = request }--                val configBuilder = HighSpeedVideoSessionConfig.Builder(videoCapture)-                    .setPreview(preview)-                    .setSlowMotionEnabled(true)-                    .setFrameRateRange(range)-                    .setAutoRotationEnabled(true)--                val owner = ManualLifecycleOwner()-                owner.start()-                sessionLifecycleOwner?.destroy()-                sessionLifecycleOwner = owner--                boundCamera = provider.bindToLifecycle(owner, selector, configBuilder.build())-                sloMoFps = range.upper-                Log.d("SloMo", "High-speed session bound at ${range.upper}fps (range=$range), quality=$orderedQualities")-                bound = true-                break-            } catch (e: Exception) {-                lastError = e-                Log.w("SloMo", "Failed to bind HFR at $range, trying next", e)-                sessionLifecycleOwner?.destroy()-                sessionLifecycleOwner = null+        // Try HFR ranges from highest fps downwards, each across the back lens ladder.+        val lensOrdered = buildList {+            if (requestedSloMoLens != null) add(requestedSloMoLens)+            sloMoFamily.sortedBy { it.fallbackPriority }.forEach { if (it != requestedSloMoLens) add(it) }+            if (requestedSloMoLens == null && sloMoFamily.isEmpty()) add(null)+        }+        outer@ for (range in hfrRanges) {+            for (candidate in lensOrdered) {+                try {+                    provider.unbindAll()+                    // Re-attach surface provider after unbindAll for preview to re-emit request+                    preview.setSurfaceProvider { request -> _surfaceRequest.value = request }++                    val configBuilder = HighSpeedVideoSessionConfig.Builder(videoCapture)+                        .setPreview(preview)+                        .setSlowMotionEnabled(true)+                        .setFrameRateRange(range)+                        .setAutoRotationEnabled(true)++                    val owner = ManualLifecycleOwner()+                    owner.start()+                    sessionLifecycleOwner?.destroy()+                    sessionLifecycleOwner = owner++                    boundCamera = provider.bindToLifecycle(+                        owner,+                        lensSelector(CameraSelector.LENS_FACING_BACK, candidate),+                        configBuilder.build()+                    )+                    sloMoFps = range.upper+                    boundSloMoLensId = candidate?.logicalCameraId+                    Log.d("SloMo", "High-speed session bound at ${range.upper}fps (range=$range) lens=${candidate?.labelKey}, quality=$orderedQualities")+                    bound = true+                    break@outer+                } catch (e: Exception) {+                    lastError = e+                    Log.w("SloMo", "Failed to bind HFR at $range lens=${candidate?.labelKey}, trying next", e)+                    sessionLifecycleOwner?.destroy()+                    sessionLifecycleOwner = null+                }             }         } @@ -166,11 +188,9 @@ suspend fun CameraViewModel.setupHighSpeedSession(): Boolean {             Log.w("SloMo", "Could not set anti-banding", e)         } -        boundCamera?.cameraInfo?.zoomState?.value?.let {-            updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-            restoreZoom(it.minZoomRatio, it.maxZoomRatio)-            Log.d("NightPreview", "setupPhotoSession() after levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value}")-        }+        val zoomAfter = boundCamera?.cameraInfo?.zoomState?.value+        Log.d("NightPreview", "setupHighSpeedSession() after levels=${_availableZoomLevels.value} ratio=${_zoomRatio.value} min=${zoomAfter?.minZoomRatio} max=${zoomAfter?.maxZoomRatio}")+        boundCamera?.let { refreshCapabilities(it, boundSloMoLensId) }         _sloMoSupported.value = true         _highSpeedActive.value = true         true
camera/src/main/java/com/vayunmathur/camera/util/CameraStartup.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraStartup.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraStartup.ktindex 0724aa3519..f9ef35ebc6 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraStartup.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraStartup.kt@@ -14,6 +14,9 @@ import androidx.camera.video.Quality import androidx.camera.video.QualitySelector import androidx.camera.video.Recorder import androidx.camera.video.VideoCapture+import com.vayunmathur.camera.domain.LensFacing+import com.vayunmathur.camera.platform.ensureLensesEnumerated+import com.vayunmathur.camera.platform.lensSelector import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -24,9 +27,11 @@ import kotlinx.coroutines.withContext internal suspend fun CameraViewModel.probeSloMoSupport(): Boolean {     return try {         val provider = ProcessCameraProvider.awaitInstance(app)-        val selector = CameraSelector.Builder()-            .requireLensFacing(CameraSelector.LENS_FACING_BACK)-            .build()+        ensureLensesEnumerated(provider)+        val selector = lensSelector(+            CameraSelector.LENS_FACING_BACK,+            _selectedLens.value?.takeIf { it.facing == LensFacing.BACK }+        )         val cameraInfo = provider.getCameraInfo(selector)         val caps = Recorder.getHighSpeedVideoCapabilities(cameraInfo) ?: return false         val quals = caps.getSupportedQualities(androidx.camera.core.DynamicRange.SDR)
camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.ktindex fcd975d559..f6f8ef71ab 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraVideoSession.kt@@ -14,6 +14,10 @@ import androidx.camera.video.Quality import androidx.camera.video.QualitySelector import androidx.camera.video.Recorder import androidx.camera.video.VideoCapture+import com.vayunmathur.camera.platform.currentLensFamily+import com.vayunmathur.camera.platform.ensureLensesEnumerated+import com.vayunmathur.camera.platform.lensSelector+import com.vayunmathur.camera.platform.refreshCapabilities  suspend fun CameraViewModel.setupVideoSession(): Boolean {     return try {@@ -21,9 +25,10 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean {         cameraProvider = provider         provider.unbindAll() -        val selector = CameraSelector.Builder()-            .requireLensFacing(_lensFacing.value)-            .build()+        ensureLensesEnumerated(provider)+        val videoLens = _selectedLens.value+        val videoFamily = currentLensFamily()+        val selector = lensSelector(_lensFacing.value, videoLens)         val cameraInfo = provider.getCameraInfo(selector)          val selectedCodec = _videoCodec.value@@ -57,7 +62,14 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean {         owner.start()         sessionLifecycleOwner = owner -        fun bind(av1: Boolean, hevc: Boolean, opus: Boolean, hlg: Boolean, snapshot: Boolean): Camera {+        fun bind(+            lensSelector: CameraSelector,+            av1: Boolean,+            hevc: Boolean,+            opus: Boolean,+            hlg: Boolean,+            snapshot: Boolean+        ): Camera {             val dynamicRange = if (hlg) androidx.camera.core.DynamicRange.HLG_10_BIT                 else androidx.camera.core.DynamicRange.SDR             val previewBuilder = Preview.Builder()@@ -88,14 +100,15 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean {                     .setFlashMode(ImageCapture.FLASH_MODE_OFF)                     .build()                 imageCapture = still-                bindSession(provider, owner, selector, preview, capture, still)+                bindSession(provider, owner, lensSelector, preview, capture, still)             } else {                 imageCapture = null-                bindSession(provider, owner, selector, preview, capture)+                bindSession(provider, owner, lensSelector, preview, capture)             }         }          // Bind ladder: prefer HDR + snapshot, then drop the snapshot use case, then drop HDR.+        // Each rung is tried across the lens ladder (requested → wide → any same-facing).         val attempts = buildList {             add(hlgSupported to true)             add(hlgSupported to false)@@ -105,24 +118,33 @@ suspend fun CameraViewModel.setupVideoSession(): Boolean {             }         }         var bound: Camera? = null+        var videoBoundLensId: String? = null         var lastError: Exception? = null         for ((hlg, snapshot) in attempts) {-            try {-                provider.unbindAll()-                bound = bind(useAv1, useHevc, useOpus, hlg, snapshot)-                break-            } catch (e: Exception) {-                lastError = e-                Log.w("VideoSession", "Video bind failed (hlg=$hlg, snapshot=$snapshot); trying next", e)+            val lensOrdered = buildList {+                if (videoLens != null) add(videoLens)+                videoFamily.sortedBy { it.fallbackPriority }.forEach { if (it != videoLens) add(it) }+                if (videoLens == null && videoFamily.isEmpty()) add(null)             }+            var rungBound = false+            for (candidate in lensOrdered) {+                try {+                    provider.unbindAll()+                    bound = bind(lensSelector(_lensFacing.value, candidate), useAv1, useHevc, useOpus, hlg, snapshot)+                    videoBoundLensId = candidate?.logicalCameraId+                    rungBound = true+                    break+                } catch (e: Exception) {+                    lastError = e+                    Log.w("VideoSession", "Video bind failed (hlg=$hlg, snapshot=$snapshot, lens=${candidate?.labelKey}); trying next", e)+                }+            }+            if (rungBound) break         }         boundCamera = bound ?: throw (lastError ?: IllegalStateException("Video session bind failed"))         _videoSnapshotSupported.value = imageCapture != null -        boundCamera?.cameraInfo?.zoomState?.value?.let {-            updateZoomLevels(it.minZoomRatio, it.maxZoomRatio)-            restoreZoom(it.minZoomRatio, it.maxZoomRatio)-        }+        boundCamera?.let { refreshCapabilities(it, videoBoundLensId) }         _videoSessionActive.value = true         true     } catch (e: Exception) {
camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.ktindex 15d672d187..214298b07c 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -224,6 +224,22 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {     internal val _lensFacing = MutableStateFlow(CameraSelector.LENS_FACING_BACK)     val lensFacing = _lensFacing.asStateFlow() +    internal val _availableLenses = MutableStateFlow<List<com.vayunmathur.camera.domain.PhysicalLens>>(emptyList())+    val availableLenses = _availableLenses.asStateFlow()++    internal val _selectedLens = MutableStateFlow<com.vayunmathur.camera.domain.PhysicalLens?>(null)+    val selectedLens = _selectedLens.asStateFlow()++    internal val _lensCapabilities =+        MutableStateFlow<com.vayunmathur.camera.platform.LensCapabilities?>(null)+    val lensCapabilities = _lensCapabilities.asStateFlow()++    internal val _hasFlashUnit = MutableStateFlow(true)+    val hasFlashUnit = _hasFlashUnit.asStateFlow()++    internal val _exposureCompRange = MutableStateFlow<ClosedRange<Float>?>(null)+    val exposureCompRange = _exposureCompRange.asStateFlow()+     internal val _flashMode = MutableStateFlow(FlashMode.OFF)     val flashMode = _flashMode.asStateFlow() @@ -660,6 +676,35 @@ class CameraViewModel(internal val app: Application) : AndroidViewModel(app) {         if (_cameraMode.value == CameraMode.SLOW_MO) return         _lensFacing.value = if (_lensFacing.value == CameraSelector.LENS_FACING_BACK)             CameraSelector.LENS_FACING_FRONT else CameraSelector.LENS_FACING_BACK+        // Preserve the lens family across the flip: e.g. UW back -> front lens,+        // tele back -> front lens (front has a single family, anchored at its default).+        val facing = if (_lensFacing.value == CameraSelector.LENS_FACING_BACK)+            com.vayunmathur.camera.domain.LensFacing.BACK+        else com.vayunmathur.camera.domain.LensFacing.FRONT+        _selectedLens.value =+            com.vayunmathur.camera.domain.LensSelectionLogic.filterByFacing(+                _availableLenses.value, facing+            ).minByOrNull { it.fallbackPriority }+        resetNightModeDetection()+    }++    /**+     * Selects a physical lens within the current facing family. The session+     * rebind effect is keyed on [selectedLens], so this triggers a rebind with+     * the filtered selector plus a capability refresh. Unknown lenses are+     * ignored so a stale UI entry can never crash a bind.+     */+    fun selectLens(lens: com.vayunmathur.camera.domain.PhysicalLens) {+        if (lens.facing != (+            if (_lensFacing.value == CameraSelector.LENS_FACING_BACK)+                com.vayunmathur.camera.domain.LensFacing.BACK+            else com.vayunmathur.camera.domain.LensFacing.FRONT+            )+        ) {+            return+        }+        if (lens !in _availableLenses.value) return+        _selectedLens.value = lens         resetNightModeDetection()     } 
camera/src/main/res/values/strings.xml
diff --git a/camera/src/main/res/values/strings.xml b/camera/src/main/res/values/strings.xmlindex 13033b6dca..a2a5bcb333 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -110,4 +110,18 @@     <string name="brightness">Brightness</string>     <string name="shadows">Shadows</string>     <string name="warmth">Warmth</string>++    <!-- LensBar: physical-lens picker above the zoom bar -->+    <!-- LensBar: label for the ultra-wide (0.5x) physical lens. Short pill label -->+    <string name="lens_ultrawide">UW</string>+    <!-- LensBar: label for the default wide (1x) physical lens. Short pill label -->+    <string name="lens_wide">1x</string>+    <!-- LensBar: label for the telephoto physical lens. Short pill label -->+    <string name="lens_tele">Tele</string>+    <!-- LensBar: label for the monochrome physical lens. Short pill label -->+    <string name="lens_mono">Mono</string>+    <!-- LensBar: label for the front-facing lens. Short pill label -->+    <string name="lens_front">Front</string>+    <!-- LensBar: content description for the physical-lens picker row -->+    <string name="lens_picker_description">Camera lens</string> </resources>
camera/src/test/java/com/vayunmathur/camera/domain/LensSelectionLogicTest.kt
diff --git a/camera/src/test/java/com/vayunmathur/camera/domain/LensSelectionLogicTest.kt b/camera/src/test/java/com/vayunmathur/camera/domain/LensSelectionLogicTest.ktnew file mode 100644index 0000000000..e3bbd2b68d--- /dev/null+++ b/camera/src/test/java/com/vayunmathur/camera/domain/LensSelectionLogicTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.camera.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pure-domain checks for [LensSelectionLogic]: no Android/CameraX needed. */+class LensSelectionLogicTest {++    private fun lens(+        id: String,+        type: LensType,+        facing: LensFacing = LensFacing.BACK,+        priority: Int = 0,+        ratio: Float = 1f,+    ) = PhysicalLens(+        logicalCameraId = id,+        lensType = type,+        facing = facing,+        focalLengthMm35Eq = null,+        nominalZoomRatio = ratio,+        fallbackPriority = priority,+        labelKey = type.name.lowercase(),+    )++    @Test+    fun filterByFacingOrdersByPriority() {+        val lenses = listOf(+            lens("tele", LensType.TELEPHOTO, priority = 2, ratio = 3f),+            lens("uw", LensType.ULTRA_WIDE, priority = 1, ratio = 0.5f),+            lens("wide", LensType.WIDE, priority = 0),+            lens("front", LensType.FRONT, facing = LensFacing.FRONT),+        )+        val back = LensSelectionLogic.filterByFacing(lenses, LensFacing.BACK)+        assertEquals(listOf("wide", "uw", "tele"), back.map { it.logicalCameraId })+    }++    @Test+    fun fallbackPrefersRequestedThenWide() {+        val wide = lens("wide", LensType.WIDE, priority = 0)+        val uw = lens("uw", LensType.ULTRA_WIDE, priority = 1, ratio = 0.5f)+        val family = listOf(wide, uw)+        // Requested lens present → itself.+        assertEquals("uw", LensSelectionLogic.fallbackFor(uw, family)?.logicalCameraId)+        // Unknown request → same-facing default (wide, lowest fallbackPriority).+        val tele = lens("tele", LensType.TELEPHOTO, priority = 2, ratio = 3f)+        assertEquals("wide", LensSelectionLogic.fallbackFor(tele, family)?.logicalCameraId)+        assertNull(LensSelectionLogic.fallbackFor(tele, emptyList()))+    }++    @Test+    fun zoomBuilderMirrorsUpdateZoomLevels() {+        assertEquals(+            listOf(".5" to 0.5f, "1x" to 1f, "2x" to 2f, "5x" to 5f),+            LensSelectionLogic.buildZoomLevels(0.5f, 10f),+        )+        assertEquals(listOf("1x" to 1f), LensSelectionLogic.buildZoomLevels(1f, 1f))+        assertEquals(+            listOf("1x" to 1f, "2x" to 2f),+            LensSelectionLogic.buildZoomLevels(1f, 2f),+        )+    }++    @Test+    fun isoFilterKeepsCanonicalStopsInRange() {+        assertEquals(+            listOf(100, 200, 400, 800, 1600, 3200),+            LensSelectionLogic.filterIsoStops(100..3200),+        )+        assertEquals(listOf(50, 100), LensSelectionLogic.filterIsoStops(50..100))+        // Nothing canonical fits → range endpoints.+        assertEquals(listOf(75, 90), LensSelectionLogic.filterIsoStops(75..90))+        assertTrue(LensSelectionLogic.filterIsoStops(null).isEmpty())+    }++    @Test+    fun fpsPickerPrefersFixed30() {+        val ranges = listOf(30 to 60, 30 to 30, 60 to 60)+        assertEquals(30 to 30, LensSelectionLogic.pickFpsRange(ranges, cinematic = false))+        assertEquals(30 to 30, LensSelectionLogic.pickFpsRange(ranges, cinematic = true))+        // No fixed ranges → null so CameraX picks its default.+        assertNull(LensSelectionLogic.pickFpsRange(listOf(15 to 30, 30 to 60), cinematic = false))+        // Cinematic sticks to <= 30fps.+        assertEquals(30 to 30, LensSelectionLogic.pickFpsRange(listOf(30 to 30, 60 to 60), cinematic = true))+    }++    @Test+    fun nightFailureTtl() {+        val ttl = 7L * 24 * 60 * 60 * 1000+        val now = 1_000_000_000L+        assertTrue(LensSelectionLogic.nightFailureFresh(now - 1000, now, ttl))+        assertTrue(!LensSelectionLogic.nightFailureFresh(now - ttl - 1, now, ttl))+        assertTrue(!LensSelectionLogic.nightFailureFresh(null, now, ttl))+    }++    @Test+    fun displayLabelUsesFocalLengthWhenKnown() {+        val withMm = lens("wide", LensType.WIDE).copy(focalLengthMm35Eq = 24f)+        assertEquals("24mm", LensSelectionLogic.displayLabel(withMm))+        assertEquals("1x", LensSelectionLogic.displayLabel(lens("wide", LensType.WIDE)))+        assertEquals(".5", LensSelectionLogic.displayLabel(lens("uw", LensType.ULTRA_WIDE, ratio = 0.5f)))+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.ktindex 92ec3da4f2..2135bacde8 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FFDatabase.kt@@ -154,13 +154,14 @@ interface TemporaryLinkDao {     suspend fun delete(value: TemporaryLink): Int } -@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class], version = 12, exportSchema = false)+@Database(entities = [User::class, Waypoint::class, LocationValue::class, TemporaryLink::class, NoShowAlert::class], version = 13, exportSchema = false) @ColumnTypeConverters(DefaultConverters::class) abstract class FFDatabase : RoomDatabase() {     abstract fun userDao(): UserDao     abstract fun waypointDao(): WaypointDao     abstract fun locationValueDao(): LocationValueDao     abstract fun temporaryLinkDao(): TemporaryLinkDao+    abstract fun noShowAlertDao(): NoShowAlertDao      companion object : com.vayunmathur.library.util.DatabaseMigrations {         override val migrations: List<androidx.room3.migration.Migration> = listOf(@@ -270,6 +271,26 @@ abstract class FFDatabase : RoomDatabase() {                     "CREATE INDEX IF NOT EXISTS `index_LocationValue_userid_reportedAt` " +                         "ON `LocationValue` (`userid`, `reportedAt`)"                 )+            },+            // No-show alerts: a new table watching for expected arrivals.+            // Fresh table, so the CREATE must match what Room generates from+            // NoShowAlert exactly (Instant as epoch-seconds INTEGER, Duration as+            // millisecond INTEGER, booleans as 0/1 INTEGER).+            androidx.room3.migration.Migration(12, 13) {+                it.execSQL(+                    "CREATE TABLE IF NOT EXISTS `NoShowAlert` (" ++                        "`watchedUserId` INTEGER NOT NULL, " ++                        "`waypointId` INTEGER, " ++                        "`expectedAt` INTEGER NOT NULL, " ++                        "`grace` INTEGER NOT NULL, " ++                        "`fired` INTEGER NOT NULL, " ++                        "`oneShot` INTEGER NOT NULL, " ++                        "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)"+                )+                it.execSQL(+                    "CREATE INDEX IF NOT EXISTS `index_NoShowAlert_watchedUserId` " ++                        "ON `NoShowAlert` (`watchedUserId`)"+                )             }         )     }
findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.ktindex 63eb50eb7b..48a8af3236 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/FindFamilyRepository.kt@@ -27,6 +27,7 @@ class FindFamilyRepository private constructor(context: Context) :     private val waypointDao: WaypointDao get() = db.waypointDao()     private val locationValueDao: LocationValueDao get() = db.locationValueDao()     private val temporaryLinkDao: TemporaryLinkDao get() = db.temporaryLinkDao()+    private val noShowAlertDao: NoShowAlertDao get() = db.noShowAlertDao()      // ------------------------------------------------------------------     // Read flows (cold)@@ -35,6 +36,7 @@ class FindFamilyRepository private constructor(context: Context) :     val users: Flow<List<User>> get() = userDao.getAllFlow()     val waypoints: Flow<List<Waypoint>> get() = waypointDao.getAllFlow()     val temporaryLinks: Flow<List<TemporaryLink>> get() = temporaryLinkDao.getAllFlow()+    val noShowAlerts: Flow<List<NoShowAlert>> get() = noShowAlertDao.getAllFlow()      /** Latest [LocationValue] per user id (the "present" position of everyone). */     val latestLocationByUser: Flow<Map<Long, LocationValue>>@@ -113,6 +115,19 @@ class FindFamilyRepository private constructor(context: Context) :     suspend fun upsertTemporaryLink(link: TemporaryLink): Long = temporaryLinkDao.upsert(link)     suspend fun deleteTemporaryLink(link: TemporaryLink): Int = temporaryLinkDao.delete(link) +    // ------------------------------------------------------------------+    // NoShowAlert reads / writes+    // ------------------------------------------------------------------++    suspend fun getNoShowAlert(id: Long): NoShowAlert? = noShowAlertDao.get(id)+    suspend fun getAllNoShowAlerts(): List<NoShowAlert> = noShowAlertDao.getAll()+    suspend fun getDueNoShowAlerts(nowEpochSeconds: Long): List<NoShowAlert> =+        noShowAlertDao.getDue(nowEpochSeconds)+    suspend fun upsertNoShowAlert(alert: NoShowAlert): Long = noShowAlertDao.upsert(alert)+    suspend fun deleteNoShowAlert(alert: NoShowAlert): Int = noShowAlertDao.delete(alert)+    suspend fun markNoShowAlertFired(id: Long): Int = noShowAlertDao.markFired(id)+    suspend fun rearmNoShowAlert(id: Long): Int = noShowAlertDao.rearm(id)+     companion object {         @Volatile         private var instance: FindFamilyRepository? = null
findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlert.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlert.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlert.ktnew file mode 100644index 0000000000..9f6eaf4c3d--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlert.kt@@ -0,0 +1,36 @@+package com.vayunmathur.findfamily.data++import androidx.room3.Entity+import androidx.room3.Index+import androidx.room3.PrimaryKey+import com.vayunmathur.library.util.DatabaseItem+import kotlinx.serialization.Serializable+import kotlin.time.Duration+import kotlin.time.Instant++/**+ * A watch for an expected arrival that never happened (no-show alert).+ *+ * The scheduler (a later step) periodically asks for rows whose deadline —+ * [expectedAt] plus [grace] — has passed without the watched user appearing,+ * then notifies and marks them fired. Time columns reuse the database-wide+ * converters: [Instant] is stored as epoch seconds, [Duration] as whole+ * milliseconds, booleans as 0/1 integers.+ */+@Serializable+@Entity(indices = [Index("watchedUserId")])+data class NoShowAlert(+    /** Row id of the watched [User]. */+    val watchedUserId: Long,+    /** Waypoint the user was expected at. Null means any location update counts as arrival. */+    val waypointId: Long?,+    /** When the user was expected. */+    val expectedAt: Instant,+    /** Extra wait after [expectedAt] before the alert becomes due. */+    val grace: Duration,+    /** Whether this alert has already fired. Set atomically via `markFired`. */+    val fired: Boolean = false,+    /** When true the row is deleted after firing; when false it stays and can be re-armed. */+    val oneShot: Boolean = true,+    @PrimaryKey(autoGenerate = true) override val id: Long = 0,+) : DatabaseItem
findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.ktnew file mode 100644index 0000000000..7fdab0b144--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/data/NoShowAlertDao.kt@@ -0,0 +1,49 @@+package com.vayunmathur.findfamily.data++import androidx.room3.Dao+import androidx.room3.Delete+import androidx.room3.Query+import androidx.room3.Upsert+import kotlinx.coroutines.flow.Flow++@Dao+interface NoShowAlertDao {+    @Query("SELECT * FROM NoShowAlert")+    fun getAllFlow(): Flow<List<NoShowAlert>>++    @Query("SELECT * FROM NoShowAlert WHERE id = :id")+    fun getByIdFlow(id: Long): Flow<NoShowAlert?>++    @Query("SELECT * FROM NoShowAlert")+    suspend fun getAll(): List<NoShowAlert>++    @Query("SELECT * FROM NoShowAlert WHERE id = :id")+    suspend fun get(id: Long): NoShowAlert?++    /**+     * Alerts whose deadline ([expectedAt] + [grace]) has passed and which have+     * not fired yet. Cutoffs are epoch seconds / whole milliseconds, matching+     * the database-wide column converters.+     */+    @Query(+        "SELECT * FROM NoShowAlert WHERE fired = 0 " ++            "AND (expectedAt + (grace / 1000)) <= :nowEpochSeconds"+    )+    suspend fun getDue(nowEpochSeconds: Long): List<NoShowAlert>++    @Upsert+    suspend fun upsert(value: NoShowAlert): Long++    @Delete+    suspend fun delete(value: NoShowAlert): Int++    /**+     * Mark fired only if the row has not fired yet, so two concurrent+     * scheduler runs cannot both claim it. Returns rows updated (0 or 1).+     */+    @Query("UPDATE NoShowAlert SET fired = 1 WHERE id = :id AND fired = 0")+    suspend fun markFired(id: Long): Int++    @Query("UPDATE NoShowAlert SET fired = 0 WHERE id = :id")+    suspend fun rearm(id: Long): Int+}
findfamily/src/main/java/com/vayunmathur/findfamily/domain/NoShowPolicy.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/domain/NoShowPolicy.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/NoShowPolicy.ktnew file mode 100644index 0000000000..a607529d9b--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/domain/NoShowPolicy.kt@@ -0,0 +1,131 @@+package com.vayunmathur.findfamily.domain++import kotlin.math.asin+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.time.Duration+import kotlin.time.Instant++/**+ * Pure due/containment policy for no-show alerts (issue 702).+ *+ * Unit-testable by construction: every input is a primitive, [Instant], or+ * [Duration]. No Android, no Compose, no database types — the scheduler maps+ * rows to these parameters at its own boundary.+ *+ * Containment mirrors the live geofence path+ * (`data/Coord.kt:havershine` + `util/LocationTrackingInbound.kt`):+ * entering needs the whole error circle inside the radius, leaving needs it+ * wholly outside a hysteresis margin, and fixes worse than+ * [NO_SHOW_MAX_ACCURACY_METERS] cannot move the answer. The distance itself is+ * a pure haversine here rather than the platform geodesic, so values agree to+ * within the sub-meter noise the strict inequalities already tolerate.+ */+object NoShowPolicy {++    /** Mirror of the inbound geofence accuracy gate: worse fixes decide nothing. */+    const val NO_SHOW_MAX_ACCURACY_METERS = 100.0++    /** Mirror of the inbound exit hysteresis: leaving needs a clear margin. */+    const val NO_SHOW_EXIT_HYSTERESIS = 1.2++    /** Mean Earth radius in meters, matching the platform geodesic scale. */+    const val EARTH_RADIUS_METERS = 6_371_000.0++    /** The alert deadline: the moment [grace] after [expectedAt] it becomes due. */+    fun deadline(expectedAt: Instant, grace: Duration): Instant = expectedAt + grace++    /** True once [now] has reached [expectedAt] plus [grace] (inclusive). */+    fun isDue(expectedAt: Instant, grace: Duration, now: Instant): Boolean =+        now >= deadline(expectedAt, grace)++    /** True when a fix is precise enough to decide geofence membership. */+    fun isAccurateEnough(accuracyMeters: Double): Boolean =+        accuracyMeters.isFinite() && accuracyMeters >= 0.0 &&+            accuracyMeters <= NO_SHOW_MAX_ACCURACY_METERS++    /**+     * Pure haversine distance in meters. Same contract as the data-layer+     * geodesic (meters between WGS84 points); the spherical approximation+     * differs by far less than a typical fix accuracy.+     */+    fun haversineMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {+        val halfDLat = (lat2 - lat1) * Math.PI / 360.0+        val halfDLon = (lon2 - lon1) * Math.PI / 360.0+        val lat1Rad = lat1 * Math.PI / 180.0+        val lat2Rad = lat2 * Math.PI / 180.0+        val a = sin(halfDLat) * sin(halfDLat) ++            cos(lat1Rad) * cos(lat2Rad) * sin(halfDLon) * sin(halfDLon)+        return 2.0 * EARTH_RADIUS_METERS * asin(sqrt(a.coerceIn(0.0, 1.0)))+    }++    /**+     * Enter semantics: the whole error circle must fit inside [rangeMeters].+     * Strict `<`, mirroring inbound — a circle exactly touching the boundary+     * stays where it was.+     */+    fun isEnterInside(distanceMeters: Double, accuracyMeters: Double, rangeMeters: Double): Boolean =+        distanceMeters + accuracyMeters < rangeMeters++    /**+     * Exit semantics: still inside while any part of the error circle (plus+     * the hysteresis margin) overlaps the radius. Strict `<`, mirroring+     * inbound.+     */+    fun isStillInside(distanceMeters: Double, accuracyMeters: Double, rangeMeters: Double): Boolean =+        distanceMeters - accuracyMeters < rangeMeters * NO_SHOW_EXIT_HYSTERESIS++    /**+     * A fix only proves arrival when it was *measured* at or after the+     * expectation. Shutdown and low-battery reports deliberately republish a+     * stale last-known position, so ranking them by send time would let a+     * parting shot from long before [expectedAt] suppress an alert it says+     * nothing about.+     */+    fun isFixFreshForArrival(fixTimestamp: Instant, expectedAt: Instant): Boolean =+        fixTimestamp >= expectedAt++    /**+     * Arrival at a waypoint: a fresh, accurate fix whose whole error circle+     * is inside the radius. Any failed gate reads as "not arrived" — a fix+     * that cannot say which side of the boundary it is on must not suppress+     * the alert.+     */+    fun hasArrivedAtWaypoint(+        fixLat: Double,+        fixLon: Double,+        fixAccuracyMeters: Double,+        fixTimestamp: Instant,+        expectedAt: Instant,+        waypointLat: Double,+        waypointLon: Double,+        waypointRangeMeters: Double,+    ): Boolean {+        if (!isFixFreshForArrival(fixTimestamp, expectedAt)) return false+        if (!isAccurateEnough(fixAccuracyMeters)) return false+        val distance = haversineMeters(fixLat, fixLon, waypointLat, waypointLon)+        return isEnterInside(distance, fixAccuracyMeters, waypointRangeMeters)+    }++    /**+     * Arrival when the alert watches no waypoint: any fresh-enough location+     * update counts, regardless of position or accuracy.+     */+    fun hasAnyFreshFix(fixTimestamp: Instant, expectedAt: Instant): Boolean =+        isFixFreshForArrival(fixTimestamp, expectedAt)++    /**+     * Fire-once guard for the scheduler: fires only for an unfired alert whose+     * deadline has passed and whose arrival was not observed. Persistence+     * (claim-then-notify, delete vs re-arm) stays with the scheduler; this is+     * the in-memory half that keeps a second pass from double-firing.+     */+    fun shouldFire(+        fired: Boolean,+        expectedAt: Instant,+        grace: Duration,+        now: Instant,+        arrived: Boolean,+    ): Boolean = !fired && !arrived && isDue(expectedAt, grace, now)+}
findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.ktnew file mode 100644index 0000000000..488fb9c462--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/platform/NoShowCheckScheduler.kt@@ -0,0 +1,169 @@+package com.vayunmathur.findfamily.platform++import android.content.Context+import android.util.Log+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.workDataOf+import com.vayunmathur.findfamily.data.FindFamilyRepository+import com.vayunmathur.findfamily.data.NoShowAlert+import com.vayunmathur.findfamily.domain.NoShowPolicy+import java.util.concurrent.TimeUnit+import kotlin.time.Clock+import kotlin.time.Duration++/**+ * Scheduler + worker for no-show alerts (issue 702).+ *+ * Each alert gets one inexact [androidx.work.OneTimeWorkRequest] firing at its+ * deadline ([NoShowAlert.expectedAt] + [NoShowAlert.grace]), enqueued as unique+ * work per alert id so re-arming replaces rather than duplicates. Deliberately+ * inexact WorkManager only — no `SCHEDULE_EXACT_ALARM` / `USE_EXACT_ALARM`.+ *+ * The actual due/arrival decision lives in [NoShowPolicy] (pure, unit-tested);+ * this file is only the Android glue: enqueue at the deadline, sweep when the+ * work runs, and re-enqueue everything after reboot / process init.+ *+ * User-visible notification delivery is NOT here — that is wired separately+ * (NO_SHOW channel step), consuming the claimed alerts [sweepNow] returns.+ */+class NoShowCheckWorker(+    appContext: Context,+    workerParams: androidx.work.WorkerParameters,+) : CoroutineWorker(appContext, workerParams) {++    override suspend fun doWork(): Result = try {+        val fired = NoShowCheckScheduler.sweepNow(applicationContext)+        if (fired.isNotEmpty()) {+            Log.i(TAG, "sweep fired ${fired.size} alert(s): ${fired.map { it.id }}")+        }+        Result.success()+    } catch (_: Exception) {+        Result.retry()+    }++    companion object {+        private const val TAG = "FF-NoShow"+        internal const val KEY_ALERT_ID = "alert_id"+    }+}++object NoShowCheckScheduler {++    private const val TAG = "FF-NoShow"++    private fun workName(alertId: Long) = "noshow-$alertId"++    /**+     * Enqueue (or replace) the one-shot check for [alert] at its deadline.+     * Past-due deadlines enqueue with zero delay so they sweep immediately.+     */+    fun schedule(context: Context, alert: NoShowAlert) {+        val deadline = NoShowPolicy.deadline(alert.expectedAt, alert.grace)+        val delayMs = (deadline - Clock.System.now()).inWholeMilliseconds.coerceAtLeast(0)+        val request = OneTimeWorkRequestBuilder<NoShowCheckWorker>()+            .setInitialDelay(delayMs, TimeUnit.MILLISECONDS)+            .setInputData(workDataOf(NoShowCheckWorker.KEY_ALERT_ID to alert.id))+            .build()+        WorkManager.getInstance(context.applicationContext)+            .enqueueUniqueWork(workName(alert.id), ExistingWorkPolicy.REPLACE, request)+    }++    /** Drop the pending check for [alertId], if any (e.g. alert deleted). */+    fun cancel(context: Context, alertId: Long) {+        WorkManager.getInstance(context.applicationContext).cancelUniqueWork(workName(alertId))+    }++    /**+     * Check every due alert against the latest fixes and claim the ones that+     * fire. Callable from the heartbeat / service loop as well as the worker.+     *+     * Claiming is atomic via `markFired` (0/1 rows), so concurrent sweeps+     * cannot double-fire. One-shot rows are deleted after claiming; recurring+     * rows stay with `fired = true` until re-armed. Returns the claimed+     * alerts for the notification step to deliver.+     */+    suspend fun sweepNow(context: Context): List<NoShowAlert> {+        val repository = FindFamilyRepository.get(context.applicationContext)+        val now = Clock.System.now()+        val due = repository.getDueNoShowAlerts(now.epochSeconds)+        if (due.isEmpty()) return emptyList()+        val latestByUser = repository.latestLocationsOnce().associateBy { it.userid }+        val fired = mutableListOf<NoShowAlert>()+        for (alert in due) {+            val fix = latestByUser[alert.watchedUserId]+            val arrived = isArrived(repository, alert, fix)+            if (!NoShowPolicy.shouldFire(+                    fired = alert.fired,+                    expectedAt = alert.expectedAt,+                    grace = alert.grace,+                    now = now,+                    arrived = arrived,+                )+            ) continue+            // Claim first: only the sweep whose UPDATE matches notifies.+            if (repository.markNoShowAlertFired(alert.id) != 1) continue+            if (alert.oneShot) runCatching { repository.deleteNoShowAlert(alert) }+            fired.add(alert.copy(fired = true))+        }+        return fired+    }++    private suspend fun isArrived(+        repository: FindFamilyRepository,+        alert: NoShowAlert,+        fix: com.vayunmathur.findfamily.data.LocationValue?,+    ): Boolean {+        if (fix == null) return false+        val waypointId = alert.waypointId+        if (waypointId == null) {+            return NoShowPolicy.hasAnyFreshFix(fix.timestamp, alert.expectedAt)+        }+        val waypoint = runCatching { repository.getWaypoint(waypointId) }.getOrNull()+            ?: return false+        return NoShowPolicy.hasArrivedAtWaypoint(+            fixLat = fix.coord.lat,+            fixLon = fix.coord.lon,+            fixAccuracyMeters = fix.acc.toDouble(),+            fixTimestamp = fix.timestamp,+            expectedAt = alert.expectedAt,+            waypointLat = waypoint.coord.lat,+            waypointLon = waypoint.coord.lon,+            waypointRangeMeters = waypoint.range,+        )+    }++    /**+     * Re-enqueue checks for every unfired alert. Call from `BootReceiver` and+     * VM / process init — the mirror of `applyDueAutoToggles`, which the+     * heartbeat re-applies the same way rather than trusting settled state.+     */+    suspend fun rescheduleAll(context: Context) {+        val repository = FindFamilyRepository.get(context.applicationContext)+        val pending = repository.getAllNoShowAlerts().filter { !it.fired }+        for (alert in pending) {+            runCatching { schedule(context, alert) }+                .onFailure { e -> Log.w(TAG, "reschedule alert ${alert.id} failed", e) }+        }+        Log.i(TAG, "rescheduled ${pending.size} no-show alert(s)")+    }++    /** Convenience: schedule exactly at the deadline computed from these parts. */+    fun scheduleAt(+        context: Context,+        alertId: Long,+        expectedAt: kotlin.time.Instant,+        grace: Duration,+    ) {+        val now = Clock.System.now()+        val delayMs = ((expectedAt + grace) - now).inWholeMilliseconds.coerceAtLeast(0)+        val request = OneTimeWorkRequestBuilder<NoShowCheckWorker>()+            .setInitialDelay(delayMs, TimeUnit.MILLISECONDS)+            .setInputData(workDataOf(NoShowCheckWorker.KEY_ALERT_ID to alertId))+            .build()+        WorkManager.getInstance(context.applicationContext)+            .enqueueUniqueWork(workName(alertId), ExistingWorkPolicy.REPLACE, request)+    }+}
findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.ktindex de836ccf2b..b67283e37c 100644--- a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/PersonDetailSheet.kt@@ -17,8 +17,13 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import com.vayunmathur.findfamily.R import androidx.compose.runtime.Composable+import com.vayunmathur.findfamily.ui.dialogs.NoShowAlertDialog import com.vayunmathur.findfamily.util.FindFamilyNotificationChannels import com.vayunmathur.findfamily.util.Networking import com.vayunmathur.findfamily.util.PersonActions@@ -27,6 +32,7 @@ import com.vayunmathur.findfamily.util.PersonUiState @Composable fun PersonDetailSheet(state: PersonUiState, actions: PersonActions) {     val user = state.user+    var showNoShowDialog by remember { mutableStateOf(false) }     Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 12.dp, vertical = 4.dp)) {         UserCard(user, state.location, true) {}         Spacer(Modifier.height(8.dp))@@ -90,6 +96,14 @@ fun PersonDetailSheet(state: PersonUiState, actions: PersonActions) {                 }             }             Spacer(Modifier.height(4.dp))+            // No-show watch (issue 702): expected arrival that never happens.+            OutlinedButton(+                { showNoShowDialog = true },+                Modifier.fillMaxWidth(),+            ) {+                Text(stringResource(R.string.noshow_watch_button))+            }+            Spacer(Modifier.height(4.dp))         }         OutlinedButton(             { actions.changeConnectedContact() },@@ -98,4 +112,12 @@ fun PersonDetailSheet(state: PersonUiState, actions: PersonActions) {             Text(stringResource(R.string.change_connected_contact))         }     }+    if (showNoShowDialog) {+        NoShowAlertDialog(+            user = user,+            waypoints = state.waypoints,+            actions = actions,+            onDismiss = { showNoShowDialog = false },+        )+    } }
findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/NoShowAlertDialog.kt
diff --git a/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/NoShowAlertDialog.kt b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/NoShowAlertDialog.ktnew file mode 100644index 0000000000..9cbe4a179b--- /dev/null+++ b/findfamily/src/main/java/com/vayunmathur/findfamily/ui/dialogs/NoShowAlertDialog.kt@@ -0,0 +1,288 @@+package com.vayunmathur.findfamily.ui.dialogs++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogProperties+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.DatePicker+import com.vayunmathur.library.ui.DatePickerDialog+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.ExposedDropdownMenuDefaults+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.SelectableDropdownMenuItem+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TimePicker+import com.vayunmathur.library.ui.rememberDatePickerState+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.ui.rememberTimePickerState+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.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.findfamily.R+import com.vayunmathur.findfamily.data.User+import com.vayunmathur.findfamily.data.Waypoint+import com.vayunmathur.findfamily.util.PersonActions+import java.time.Instant as JavaInstant+import java.time.LocalDate+import java.time.LocalTime+import java.time.ZoneId+import kotlin.time.Instant+import com.vayunmathur.library.ui.R as UiR++/**+ * No-show watch dialog for one person (issue 702): pick the expected place+ * (a saved waypoint, or any location update), the expected date/time, and a+ * grace period. Saving calls [PersonActions.setNoShowAlert], which persists+ * the row and schedules its one-shot check.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun NoShowAlertDialog(+    user: User,+    waypoints: List<Waypoint>,+    actions: PersonActions,+    onDismiss: () -> Unit,+) {+    val namedWaypoints = remember(waypoints) { waypoints.filter { it.name.isNotBlank() } }+    var waypointId: Long? by remember { mutableStateOf(null) }+    var placeExpanded by remember { mutableStateOf(false) }+    var dateMillis: Long? by remember { mutableStateOf(null) }+    var hour: Int? by remember { mutableStateOf(null) }+    var minute: Int? by remember { mutableStateOf(null) }+    var showDatePicker by remember { mutableStateOf(false) }+    var showTimePicker by remember { mutableStateOf(false) }+    var graceExpanded by remember { mutableStateOf(false) }+    var graceMinutes by remember { mutableStateOf(30) }+    val messenger = rememberMessenger()++    val anyPlaceLabel = stringResource(R.string.noshow_place_any)+    val selectedPlaceLabel = waypointId+        ?.let { id -> namedWaypoints.firstOrNull { it.id == id }?.name }+        ?: anyPlaceLabel+    // Date/time assembly below uses java.time with the device zone; the dialog+    // only stores raw millis/hour/minute until both halves are chosen.+    val dateLabel = dateMillis?.let { millis ->+        JavaInstant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate().toString()+    } ?: stringResource(R.string.noshow_pick_date)+    val timeLabel = if (hour != null && minute != null) {+        String.format("%02d:%02d", hour, minute)+    } else {+        stringResource(R.string.noshow_pick_time)+    }+    val expectedAt: Instant? = remember(dateMillis, hour, minute) {+        val millis = dateMillis+        val h = hour+        val m = minute+        if (millis == null || h == null || m == null) {+            null+        } else {+            val date = JavaInstant.ofEpochMilli(millis)+                .atZone(ZoneId.systemDefault()).toLocalDate()+            val zoned = LocalDate.of(date.year, date.month, date.dayOfMonth)+                .atTime(LocalTime.of(h, m))+                .atZone(ZoneId.systemDefault())+            Instant.fromEpochMilliseconds(zoned.toInstant().toEpochMilli())+        }+    }+    val graceOptions = remember { listOf(0, 15, 30, 60, 120) }+    val scheduledMessage = stringResource(R.string.noshow_scheduled)+    val context = LocalContext.current+    fun graceLabel(minutesValue: Int): String =+        context.resources.getQuantityString(R.plurals.noshow_grace_minutes, minutesValue, minutesValue)++    Dialog(onDismissRequest = onDismiss) {+        Card {+            Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {+                Text(+                    stringResource(R.string.noshow_title, user.name),+                    style = MaterialTheme.typography.headlineMedium,+                )++                // Expected place: "Anywhere" plus one entry per named saved place,+                // mirroring the arrival-trigger 

Diff truncated.