Modern Apps git

← Modern-Apps.git

various fixes

Commit
d9020e6e85d10138804395d8a7ab4ebd7d4d6f21
Author
Vayun Mathur <[email protected]>
When
2026-07-24 21:24 UTC (4 months ago)
Parents
ae280e3

Diff

SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdnew file mode 100644index 0000000000..dddc513e66--- /dev/null+++ b/SUPPLY_CHAIN_RISKS.md@@ -0,0 +1,111 @@+# Supply Chain Risks++This document enumerates critical external dependencies for the Modern-Apps monorepo (27 apps + `library/`, `sdk/`, `third_party/`). It covers runtime server dependencies and build-time library dependencies that could break apps if abandoned, shut down, or changed.++## Assumptions++- **Self-hosted infrastructure is assumed indefinite**: `api.vayunmathur.com`, `data.vayunmathur.com`, `findfamily.cc` and any subdomains are excluded from the risk list. These services host self-owned data (e.g. the `health` food/nutrition DB behind `/api/food`, the `openassistant`/`photos` ML models permanently hosted at `data.vayunmathur.com/models`, map pmtiles/zone downloads on `data.vayunmathur.com`, E2EE relays) and proxy a few third-party secrets (Duffel, Google Places/Ratings) to keep F-Droid builds reproducible. Only the *transitive third-party* upstreams (Duffel, Google Maps Platform) are listed — the proxy/DB itself is not a supply-chain risk.+- Offline apps require only Maven Central / Google Maven at build time.++---++## Server Dependencies++### A. Purpose-Aligned Dependencies (server IS the feature)++These services are the raison d'être of the feature. If the service itself ceases to exist, the feature's purpose also ceases. The risk is existential to the product category, not an avoidable implementation choice. Most are also reverse-engineered/unofficial, so breakage from API changes is expected.++| App | External Service | Endpoints / Evidence | Why Inherent | Impact if Gone | Source Files |+|---|---|---|---|---|---|+| `youpipe`, `education` | **YouTube** | `https://www.youtube.com/watch?v=`, `*.googlevideo.com`, SABR streaming, `sabr_po_token.js` | Product is a YouTube client; YouTube is the content source | No playback. Breaks on anti-bot changes (common, requires extractor updates) | `youpipe/src/main/java/com/vayunmathur/youpipe/util/Extractor.kt`, `MyDownloader.kt`, `youpipe/extractor/src/main/java/org/schabi/newpipe/extractor/` (vendored NewPipe Extractor) |+| `messages` (gmessages) | **Google Messages for Web** | `https://messages.google.com/web/authentication`, `https://instantmessaging-pa.googleapis.com`, `https://instantmessaging-pa.clients6.google.com`, API key `AIzaSyCA...`, UA `Chrome/146.0.0.0` | Purpose is aggregating user's Google Messages account | QR pairing / long-poll fails; requires UA / PbLite RPC bump | `messages/src/main/java/com/vayunmathur/messages/gmessages/Constants.kt`, `RpcClient.kt`, `PairFlow.kt` |+| `messages` (gvoice) | **Google Voice (unofficial web API)** | `clients6.google.com/voice/v1/...`, `signaler-pa.clients6.google.com`, `waa-pa.clients6.google.com`, Origin `https://voice.google.com` | Purpose is aggregating Google Voice | SMS/calls/history stops on Voice web change | `messages/src/main/java/com/vayunmathur/messages/gvoice/Constants.kt`, `GVoiceRpcClient.kt` |+| `messages` (whatsapp) | **WhatsApp Web + media CDN** | `wss://web.whatsapp.com/ws/chat`, `s.whatsapp.net`, `*.whatsapp.net`, `mmg.whatsapp.net` | Purpose is aggregating WhatsApp | Noise `XX_25519_AESGCM_SHA256` handshake breaks, media upload fails | `messages/src/main/java/com/vayunmathur/messages/whatsapp/WhatsAppProtocol.kt`, `WhatsAppWebSocket.kt` |+| `messages` (signal) | **Signal** | `wss://chat.signal.org/v1/websocket/`, `chat.signal.org/v1/devices/capabilities`, Signal CDN attachments, `signal-root.crt.der` | Purpose is aggregating Signal | Sealed sender / ratchet / attachment upload breaks | `messages/src/main/java/com/vayunmathur/messages/signal/SignalClient.kt` |+| `messages` (meta) | **Messenger / Instagram (Lightspeed/MQTT)** | Facebook MQTT, `www.messenger.com`, Mercury upload, `LS_RESP`, `ORCA_TYPING` | Purpose is aggregating Messenger/IG | MQTT `versionId` mismatch rejected, login token expiry | `messages/src/main/java/com/vayunmathur/messages/meta/MetaClient.kt`, `MetaMqttClient.kt`, `MetaBootstrap.kt` |+| `messages` (telegram) | **Telegram MTProto DCs** | Telegram data centers, MTProto | Purpose is aggregating Telegram | DC migration / flood wait / auth key invalidation | `messages/src/main/java/com/vayunmathur/messages/telegram/TelegramClient.kt`, `mtproto/` |+| `email` | **Per-provider IMAP/SMTP + OAuth** | Gmail `imap.gmail.com:993` / `smtp.gmail.com:465`, Outlook `outlook.office365.com:993` / `smtp-mail.outlook.com:587` + `https://login.microsoftonline.com/common/oauth2/v2.0/authorize`, Yahoo, iCloud `imap.mail.me.com`, Fastmail, generic custom | Purpose is connecting to user's own email provider; provider IS the mailbox | That provider's account stops syncing. Microsoft identity outage blocks Outlook token refresh | `email/src/main/java/com/vayunmathur/email/data/ProviderPresets.kt`, `OutlookOAuth.kt` |+| `everysync` | **Google Contacts/Calendar, Google Health, iCloud CalDAV/CardDAV, Generic DAV** | `https://accounts.google.com/o/oauth2/v2/auth`, `oauth2.googleapis.com/token`, `www.googleapis.com/carddav/v1`, `apidata.googleusercontent.com/caldav/v2`, `health.googleapis.com/v4/.../dataPoints`, `caldav.icloud.com`, `contacts.icloud.com`, generic `/.well-known/caldav` discovery via `DavClient.kt` PROPFIND/REPORT | Purpose is syncing user's external calendars/contacts/health from those providers. Generic DAV servers are user-provided (not third-party) | Google/iCloud sync stops; Health backfill (steps, HR, sleep etc) halts | `everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt`, `provider/impl/GoogleProvider.kt`, `remote/GoogleHealthClient.kt`, `provider/impl/DavProviders.kt`, `remote/DavClient.kt` |+| `travel` | **Duffel (Flights + Stays) via self-hosted proxy** | `https://api.vayunmathur.com/api/travel/*` proxying Duffel token server-side: `/places`, `/flights`, `/flights-async`, `/offers`, `/airlines`, `/aircraft`, `/orders`, `/orders/{id}/pay`, etc. Stays: `https://api.vayunmathur.com/api/stays/*` `/search`, `/rates`, `/quote`, `/bookings` | Purpose is flight + hotel search/booking; Duffel is the inventory aggregator. Proxy itself is assumed indefinite, but upstream Duffel is third-party | Flight/hotel search, pricing, seat maps, booking, trips hub fails. Reference data (airlines/cities) cached partially | `travel/src/main/java/com/vayunmathur/travel/network/TravelApi.kt`, `StaysApi.kt` |++Mitigation for purpose-aligned: pin UA versions (`Chrome/146`, Sec-CH-UA), isolate per-bridge circuit breaker, implement extractor/protocol version checks in CI, surface degraded state per account.++### B. Replaceable / Infrastructure Dependencies (implementation choice, could be self-hosted or swapped)++These servers provide data/functionality that is NOT intrinsically tied to a single vendor. We currently depend on a community/FOSS provider or CDN, but could mirror, self-host, or swap with modest engineering.++| App | External Service | Endpoints / Evidence | Why Replaceable | Impact if Gone | Alternative |+|---|---|---|---|---|---|+| `weather` | **Open-Meteo Stack (FOSS, keyless)** | `https://api.open-meteo.com/v1/forecast`, `geocoding-api.open-meteo.com/v1/search`, `air-quality-api.open-meteo.com/v1/air-quality`, `map-tiles.open-meteo.com/data_spatial/<model>/latest.json` + `.om` tiles `.../YYYY/MM/DD/HHMMZ/...om` decoded by `libweather_om.so` (vendored C/Rust in `third_party/om-file-format-sys`) | Weather data is commodity; Open-Meteo is one FOSS provider among many. API is keyless and opensource, self-hostable | Forecast, city search, air-quality, weather map shading fails. `WeatherCacheStore` mitigates partially | Self-host Open-Meteo `om-file-format` + DWD ICON model, or swap to PirateWeather, OpenWeather, NOAA GFS direct |+| `maps` ratings + live traffic | **Google Places + traffic via self-hosted proxy (transitive)** | `https://api.vayunmathur.com/maps/traffic` (live traffic tiles, `OfflineRouter.kt`), `place_match`, `place_rating` wrapping Google Places (`Reviews.kt`) | Ratings/traffic proxy holds secret; Google is upstream. **Routing is fully offline** via `offlinerouter.so` (C++ `maps/src/main/cpp/`, `OfflineRouter.findRouteNative`) + bundled pmtiles `world_z0-6.pmtiles` + `admin0.fgb/admin1.fgb` + GTFS — no online routing endpoint is called | Place ratings + live-traffic overlay fail; turn-by-turn routing continues fully offline with pre-downloaded zones | Ratings could be OSM/Wikidata; self-host a traffic source. (Online routing already removed in favor of the offline router) |+| `youpipe` extras | **SponsorBlock / DeArrow (community)** | `https://sponsor.ajay.app/api/skipSegments?videoID=`, `/api/branding?videoID=`, `https://dearrow-thumb.ajay.app/api/v1/getThumbnail?videoID=` | Crowdsourced, best-effort extras, not core YouTube | Sponsor skips + DeArrow thumbnails/branding missing, degrades gracefully | Self-host SponsorBlock mirror, or disable feature flag |+| `maps` / `travel` / `photos` / `weather` | **MapLibre rendering + Wikidata enrichment** | `org.maplibre.compose:maplibre-compose:0.13.0` → `libmaplibre.so`, `https://www.wikidata.org/w/rest.php/wikibase/v1/entities/items/{id}` | Map renderer is FOSS community project (vs Mapbox), Wikidata is enrichment only | Map rendering would need fork/mirror if MapLibre artifacts gone; Wikidata fail is graceful null | Vendor MapLibre AAR, or switch to OpenGL self-render; Wikidata can be removed |++`health` food search hits `api.vayunmathur.com/api/food` — a **self-hosted nutrition DB** (not a third-party proxy), so it is excluded from the risk list per Assumptions.++Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `contacts` (only `libphonenumber` locally), `files`, `notes` (Room + Ink), `things`, `camera` (on-device `tasks-vision:0.10.14` BlazeFace), `pdf` (Rust `libpdf_render.so`), `music` (Media3 ExoPlayer + local scan), `games/*`, `passwords` (biometric + KeePass), `library/*`, `health` core.++---++## Library / Build Dependencies++### Build Infrastructure++- **Maven repositories**: `google()` (filtered), `mavenCentral()`, `gradlePluginPortal()` in `build-logic/settings`, plus **`https://jitpack.io`** in root `settings.gradle.kts`. JitPack now builds only `Stockfish-Library` (games:chess) — `nanojson` was vendored to `:third_party:nanojson` (✅ mitigation #2). JitPack remains a reproducible-build SPOF for Stockfish only.+- **Launch icon generator**: `build-logic/src/main/kotlin/LauncherIconGen.kt` downloads `https://raw.githubusercontent.com/google/material-design-icons/819d786.../symbols/android/{icon}/...24px.xml` at build time, cached under `~/.gradle/material-symbols-cache`. Build needs GitHub availability on first (uncached) build. ⚠️ Not yet mitigated.+- **Alpha toolchain**: `agp = 9.4.0-alpha04`, `composeBom = 2026.06.01` (future-dated), `navigation3 = 1.2.0-alpha05`, `material3 = 1.5.0-alpha23`, `biometric = 1.4.0-alpha07`, `camerax = 1.7.0-alpha02`, `datastore = 1.3.0-alpha09`. ⚠️ Stable release branch should pin stable versions (not yet done).+- **Version drift**: `okhttp 4.12.0` (2y old, 5.x exists) ⚠️ still pinned. `ktor` now unified at catalog `3.5.1` (messages inline `3.2.3` removed ✅) and `mediapipe tasks-vision` unified at `0.10.35` (camera inline `0.10.14` removed ✅).+- **Vendored third_party**: `third_party/nanojson/` (vendored `TeamNewPipe/nanojson`, was JitPack — ✅ mitigation #2), `third_party/om-file-format-sys/` (C + Rust bindings for `open-meteo/om-file-format` GPL-2.0-only) patched for reproducible `readdir` sort, `maps/src/main/cpp/sqlite3.c` amalgamation (SQLite NDK workaround), `youpipe/extractor/` full NewPipe Extractor GPLv3, `library/ocr/assets/det.onnx, rec.onnx` from `RapidAI/RapidOCR` Apache-2.0.++All versions in `gradle/libs.versions.toml`.++### High-Risk External Libraries (single maintainer, abandoned, or proprietary CDN)++| Library | Version | Used By | Why High Risk | File |+|---|---|---|---|---|+| `com.github.vayun-mathur:Stockfish-Library` via JitPack | `1.1.0` | `games/chess` | Personal fork on JitPack, if GitHub repo deleted build breaks. Only remaining JitPack dep | `games/chess/build.gradle.kts` |+| `jitpack.io` itself | — | above | Supply chain SPOF | `settings.gradle.kts` |+| `io.github.dokar3:quickjs-kt` | `1.0.5` | `youpipe` | Single maintainer (dokar3), JS eval for YouTube signature decipher — critical path | `youpipe/build.gradle.kts`, `libs.versions.toml:8` |+| `org.whispersystems:signal-protocol-java` shaded via ShadowJar | `2.8.1` + `com.gradleup.shadow:9.0.0` | `whatsapp-signal` (`configuration = shaded`) → `messages` | Abandoned, replaced by `libsignal-android`; needed only because `libsignal-android:0.86.5` removed X3DH needed for WhatsApp bridge. Protobuf relocation `com.google.protobuf -> com.vayunmathur.messages.shadedproto` hack | `whatsapp-signal/build.gradle.kts` |+| `dev.whyoleg.cryptography:cryptography-core` + `cryptography-provider-jdk` | `0.6.0` | `library:e2ee-p2p` → `office` E2EE | Single person (whyoleg), crypto-critical for PQC KEM | `library/e2ee-p2p/build.gradle.kts`, `libs.versions.toml:75` |+| `org.linguafranca.pwdb:KeePassJava2-dom` | `2.2.4` | `passwords` | Single maintainer, last release 2021, security-sensitive KDBX parsing | `passwords/build.gradle.kts`, `libs.versions.toml:82` |+| `org.wololo:flatgeobuf` | `3.29.0` | `maps` | Niche geo format, single maintainer | `maps/build.gradle.kts`, `libs.versions.toml:13` |+| `com.google.code.findbugs:jsr305` + `javax.annotation-api:1.3.2` | `3.0.2` / `1.3.2` | `extractor` | Deprecated 7+ years, replaced by JetBrains annotations | `libs.versions.toml:5,114` |+| `org.mozilla:rhino` + `rhino-engine` | `1.8.1` pinned | `extractor` | Pinned old because `1.9.0` requires minSdk 26 comment in `libs.versions.toml:2`; Mozilla but old | `libs.versions.toml:3,107` |++### Medium-Risk (small org / community, but active)++| Library | Version | Used By | Notes | File |+|---|---|---|---|---|+| `org.jsoup:jsoup` | `1.22.2` | `youpipe/extractor` | Single but very active, critical for HTML parsing | `libs.versions.toml:54` |+| `org.brotli:dec` | `0.1.2` | `extractor` | Google JVM port, low activity | `libs.versions.toml:9` |+| `org.maplibre.compose:maplibre-compose` | `0.13.0` → `libmaplibre.so` native | `maps`, `weather`, `findfamily`, `photos` | Community-maintained FOSS renderer, better than Mapbox but smaller than Google Maps | `libs.versions.toml:78` |+| `com.google.mediapipe:tasks-vision` | `0.10.35` (unified) | `camera` (face), vision segmentation | Native lib size; inline `0.10.14` drift resolved | `camera/build.gradle.kts:124`, `libs.versions.toml` |+| `com.microsoft.onnxruntime:onnxruntime-android` | `1.27.0` | `library:ocr` (det/rec), `openassistant` (SigLIP), `photos`, `pdf` | MIT, Microsoft-maintained, low risk but native `.so` | `library/ocr/build.gradle.kts`, `libs.versions.toml:85` |+| `net.zetetic:sqlcipher-android` | `4.17.0` | `library:room` → `passwords`, `notes` | Small company, adds ~2MB `.so`, encrypted DB | `library/room/build.gradle.kts`, `libs.versions.toml:31` |+| `io.coil-kt:coil-compose` + `coil-svg` + `coil-video` | `2.7.0` | `photos`, `maps`, `email`, `travel`, `education`, `pdf` | <3 maintainers, but widely adopted image loader | `libs.versions.toml:50` |+| `org.bouncycastle:bcprov-jdk18on` + `bcpkix-jdk18on` | `1.85` | `pdf`, `passwords`, `messages`, `e2ee-p2p` | Small org, long-lived, well-audited PQC ML-KEM/ML-DSA; resource conflicts handled in `common-conventions-app` | `libs.versions.toml:84,226` |+| `com.google.zxing:core` | `3.5.4` | `messages` (QR), `library:ocr`, `pdf` | Old, community fork `zxing-cpp` preferred | `libs.versions.toml:83` |+| `com.google.ai.edge.litertlm:litertlm-android` | `0.14.0` experimental | `openassistant` | Google AI Edge experimental, GPU backend `libLiteRtTopKOpenClSampler.so`, requires `kotlinx-coroutines 1.11.0` conflict win | `openassistant/build.gradle.kts`, `libs.versions.toml:30` |+| `com.gradleup.shadow` | `9.0.0` | `whatsapp-signal` shaded jar | Single org (gradleup), medium risk | `whatsapp-signal/build.gradle.kts` |++### Low Risk / Platform (Google/JetBrains) — Not Critical++Well-maintained: `androidx.*` (`core-ktx 1.19.0`, `lifecycle 2.11.0`, `room 2.8.4`, `sqlite 2.7.0`, `work 2.11.2`, `datastore`, `camera`, `webkit`, `browser 1.9.0`, `biometric`, `glance`, `exifinterface`, `credentials`, `autofill`), `composeBom 2026.06.01`, `material3 1.5.0-alpha23`, `material 1.14.0`, `foundation 1.12.0-beta02`, `ink 1.1.0-alpha04`, `navigation3`, `media3-exoplayer 1.11.0-beta01`, `ktor 3.5.1` + `okhttp 4.12.0` + `okio 3.17.0`, `kotlin 2.4.0` + `coroutines 1.11.0` + `serialization-json 1.11.0` + `datetime 0.8.0`, `ksp 2.3.10`, `protobuf 4.36.0-RC1` / `protobuf-javalite 4.35.0`, `libphonenumber 9.0.34`, `fhir-model 1.0.0-beta02`, `health/connect-client 1.2.0-alpha04`, etc.++---++## Transitive Dependencies Behind Self-Hosted Proxy (for awareness)++Even assuming `api.vayunmathur.com` stays up, its upstreams are third-party:++- **Duffel API** (flights + stays) — proxied token held server-side, no secret in APK. See `travel/network/TravelApi.kt`, `StaysApi.kt`.+- **Google Maps Platform** (Place Details/Ratings only) — proxied via `place_match`, `place_rating`. See `Reviews.kt`. Live traffic tiles come via `api.vayunmathur.com/maps/traffic` (`OfflineRouter.kt`). **Routing is no longer proxied** — it runs entirely on-device via `offlinerouter.so` (`OfflineRouter.findRouteNative`), so there is no Google Routes dependency.++If those upstreams shut, our proxy returns errors — same UX as purpose-aligned but fixable by swapping provider behind same proxy endpoint.++---++## Offline-First Guarantee++After initial model download (openassistant/photos) and map zone downloads (maps), these apps work airplane-mode: `astronomy`, `calendar`, `clock`, `contacts`, `files`, `notes`, `things`, `camera`, `pdf`, `music`, `games`, `passwords`, `health` core (Health Connect), `library` modules (`ocr` det/rec, `ink`, `biometric`, `room`).
astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.ktindex fc869246b4..6314a541c1 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt@@ -1,5 +1,7 @@ package com.vayunmathur.astronomy.data.model +import androidx.annotation.StringRes+import com.vayunmathur.astronomy.R import kotlinx.serialization.Serializable  @Serializable@@ -83,14 +85,14 @@ data class DeepSkyCatalog(val objects: List<DeepSkyObject>) @Serializable data class OrbitalElementsCatalog(val planets: List<OrbitalElements>) -enum class PlanetId(val displayName: String) {-    SUN("Sun"),-    MOON("Moon"),-    MERCURY("Mercury"),-    VENUS("Venus"),-    MARS("Mars"),-    JUPITER("Jupiter"),-    SATURN("Saturn"),-    URANUS("Uranus"),-    NEPTUNE("Neptune")+enum class PlanetId(@StringRes val displayNameRes: Int) {+    SUN(R.string.planet_sun),+    MOON(R.string.planet_moon),+    MERCURY(R.string.planet_mercury),+    VENUS(R.string.planet_venus),+    MARS(R.string.planet_mars),+    JUPITER(R.string.planet_jupiter),+    SATURN(R.string.planet_saturn),+    URANUS(R.string.planet_uranus),+    NEPTUNE(R.string.planet_neptune) }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.ktindex 692d960307..72f4129708 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt@@ -4,6 +4,8 @@ import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.astronomy.data.CatalogRepository+import com.vayunmathur.astronomy.data.model.PlanetId+import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.domain.engine.* import com.vayunmathur.astronomy.domain.sensor.DeviceOrientation import com.vayunmathur.astronomy.domain.sensor.LocationProvider@@ -368,17 +370,22 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app) {         val q = query.lowercase()         val results = mutableListOf<SearchResult>()         catalog.stars.filter { (it.name?.lowercase()?.contains(q) == true) || (it.properName?.lowercase()?.contains(q) == true) }.take(20).forEach {-            results.add(SearchResult("STAR_${it.id}", it.properName ?: it.name ?: "Star ${it.id}", "Star mag ${it.mag}", it.ra to it.dec))-        }-        listOf("Sun","Moon","Mercury","Venus","Mars","Jupiter","Saturn","Uranus","Neptune").filter { it.lowercase().contains(q) }.forEach {-            val pid = if (it=="Sun") "SUN" else if (it=="Moon") "MOON" else "PLANET_${it.uppercase()}"-            results.add(SearchResult(pid, it, "Planet", null))+            results.add(SearchResult("STAR_${it.id}", it.properName ?: it.name ?: context.getString(R.string.search_result_star_fallback, it.id.toString()), context.getString(R.string.search_result_star_mag, it.mag.toString()), it.ra to it.dec))         }+        PlanetId.entries.map { it to context.getString(it.displayNameRes) }+            .filter { (_, name) -> name.lowercase().contains(q) }+            .forEach { (planet, name) ->+                val pid = when (planet) {+                    PlanetId.SUN, PlanetId.MOON -> planet.name+                    else -> "PLANET_${planet.name}"+                }+                results.add(SearchResult(pid, name, context.getString(R.string.search_result_planet), null))+            }         catalog.deepSky.filter { it.id.lowercase().contains(q) || it.name.lowercase().contains(q) }.take(20).forEach {             results.add(SearchResult(it.id, "${it.id} ${it.name}", it.type, it.ra to it.dec))         }         catalog.constellations.filter { it.abbr.lowercase().contains(q) || it.name.lowercase().contains(q) }.forEach {-            results.add(SearchResult("CONST_${it.abbr}", it.name, "Constellation ${it.abbr}", null))+            results.add(SearchResult("CONST_${it.abbr}", it.name, context.getString(R.string.search_result_constellation, it.abbr), null))         }         return results     }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/ObjectDetailPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/ObjectDetailPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/ObjectDetailPage.ktindex 5927a2c545..d48e717123 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/ObjectDetailPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/ObjectDetailPage.kt@@ -13,6 +13,7 @@ import com.vayunmathur.astronomy.ui.AstronomyViewModel import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.NavBackStack import kotlin.time.ExperimentalTime+import androidx.compose.ui.res.stringResource  @OptIn(ExperimentalTime::class) @Composable@@ -28,7 +29,7 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod     }) { padding ->         Column(Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {             if (detail == null) {-                Text("Object not found: $objectId")+                Text(stringResource(R.string.object_not_found, objectId))                 return@Column             }             Text(detail.title, style = MaterialTheme.typography.headlineSmall)@@ -36,36 +37,36 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod              Card(Modifier.fillMaxWidth()) {                 Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {-                    Text("RA: ${detail.raDeg.format(2)}° Dec: ${detail.decDeg.format(2)}°")-                    Text("RA h: ${(detail.raDeg/15.0).format(2)}h")-                    detail.altAz?.let { Text("Alt: ${it.first.format(1)}° Az: ${it.second.format(1)}°") }-                    detail.mag?.let { Text("Mag: ${it.format(1)}") }+                    Text(stringResource(R.string.ra_dec, detail.raDeg.format(2), detail.decDeg.format(2)))+                    Text(stringResource(R.string.ra_h_h, (detail.raDeg/15.0).format(2)))+                    detail.altAz?.let { Text(stringResource(R.string.alt_az, it.first.format(1), it.second.format(1))) }+                    detail.mag?.let { Text(stringResource(R.string.mag, it.format(1))) }                     detail.extra?.let { Text(it) }                 }             }              Card(Modifier.fillMaxWidth()) {                 Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {-                    Text("Rise / Transit / Set", style = MaterialTheme.typography.titleSmall)+                    Text(stringResource(R.string.rise_transit_set), style = MaterialTheme.typography.titleSmall)                     val rs = riseSet-                    if (rs == null) Text("Calculating...")-                    else if (rs.isNeverUp) Text("Never rises at this location")-                    else if (rs.isCircumpolar) Text("Circumpolar - never sets")+                    if (rs == null) Text(stringResource(R.string.calculating))+                    else if (rs.isNeverUp) Text(stringResource(R.string.never_rises_at_this_location))+                    else if (rs.isCircumpolar) Text(stringResource(R.string.circumpolar_never_sets))                     else {-                        Text("Rise: ${rs.riseJd?.let { jdToLocal(it) } ?: "--"}")-                        Text("Transit: ${rs.transitJd?.let { jdToLocal(it) } ?: "--"}")-                        Text("Set: ${rs.setJd?.let { jdToLocal(it) } ?: "--"}")+                        Text(stringResource(R.string.rise_1, rs.riseJd?.let { jdToLocal(it))--"}")+                        Text(stringResource(R.string.transit_1, rs.transitJd?.let { jdToLocal(it))--"}")+                        Text(stringResource(R.string.set_1, rs.setJd?.let { jdToLocal(it))--"}")                     }                 }             }              // No center button per request – detail only, view always follows phone             Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                OutlinedButton(onClick = { backStack.pop() }) { Text("Close") }+                OutlinedButton(onClick = { backStack.pop() }) { Text(stringResource(R.string.close)) }             }              if (trajectory.isNotEmpty()) {-                Text("Trajectory 24h (15m steps) - yellow line on map", style = MaterialTheme.typography.labelSmall)+                Text(stringResource(R.string.trajectory_24h_15m_steps_yellow_line_on), style = MaterialTheme.typography.labelSmall)             }         }     }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SearchPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SearchPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SearchPage.ktindex 33d4932d79..124a9b8fb6 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SearchPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SearchPage.kt@@ -11,6 +11,7 @@ import com.vayunmathur.astronomy.Route import com.vayunmathur.astronomy.ui.AstronomyViewModel import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.NavBackStack+import androidx.compose.ui.res.stringResource  @Composable fun SearchPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) {@@ -18,10 +19,10 @@ fun SearchPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) {     var results by remember { mutableStateOf(viewModel.search("")) }      Scaffold(topBar = {-        TopAppBar(title = { Text("Search") }, navigationIcon = { IconNavigation(backStack) })+        TopAppBar(title = { Text(stringResource(R.string.search_1)) }, navigationIcon = { IconNavigation(backStack) })     }) { padding ->         Column(Modifier.padding(padding).fillMaxSize().padding(12.dp)) {-            OutlinedTextField(value = query, onValueChange = { query = it; results = viewModel.search(it) }, label = { Text("Search stars, planets, Messier") }, modifier = Modifier.fillMaxWidth())+            OutlinedTextField(value = query, onValueChange = { query = it; results = viewModel.search(it) }, label = { Text(stringResource(R.string.search_stars_planets_messier)) }, modifier = Modifier.fillMaxWidth())             Spacer(Modifier.height(8.dp))             LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {                 items(results) { r ->
astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SettingsPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SettingsPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SettingsPage.ktindex 544ac88d08..c572d43ac3 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SettingsPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SettingsPage.kt@@ -11,6 +11,7 @@ import com.vayunmathur.astronomy.ui.AstronomyViewModel import com.vayunmathur.astronomy.ui.ConstellationMode import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.NavBackStack+import androidx.compose.ui.res.stringResource  @Composable fun SettingsPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) {@@ -28,57 +29,57 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel)     var lonText by remember(observer) { mutableStateOf(observer?.lonDeg?.toString() ?: "") }      Scaffold(topBar = {-        TopAppBar(title = { Text("Settings") }, navigationIcon = { IconNavigation(backStack) })+        TopAppBar(title = { Text(stringResource(R.string.settings)) }, navigationIcon = { IconNavigation(backStack) })     }) { padding ->         Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {-            Text("Display", style = MaterialTheme.typography.titleMedium)+            Text(stringResource(R.string.display), style = MaterialTheme.typography.titleMedium)             Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {-                Text("Constellations")+                Text(stringResource(R.string.constellations))                 var expanded by remember { mutableStateOf(false) }                 Box {                     TextButton(onClick = { expanded = true }) {                         Text(                             when (showConst) {-                                ConstellationMode.OFF -> "Off"-                                ConstellationMode.LINES -> "Lines only"-                                ConstellationMode.LINES_AND_ART -> "Lines + art"+                                ConstellationMode.OFF -> stringResource(R.string.off)+                                ConstellationMode.LINES -> stringResource(R.string.lines_only)+                                ConstellationMode.LINES_AND_ART -> stringResource(R.string.lines_art)                             }                         )                     }                     DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {-                        DropdownMenuItem(text = { Text("Off") }, onClick = { viewModel.setShowConstellations(ConstellationMode.OFF); expanded = false })-                        DropdownMenuItem(text = { Text("Lines only") }, onClick = { viewModel.setShowConstellations(ConstellationMode.LINES); expanded = false })-                        DropdownMenuItem(text = { Text("Lines + art") }, onClick = { viewModel.setShowConstellations(ConstellationMode.LINES_AND_ART); expanded = false })+                        DropdownMenuItem(text = { Text(stringResource(R.string.off)) }, onClick = { viewModel.setShowConstellations(ConstellationMode.OFF); expanded = false })+                        DropdownMenuItem(text = { Text(stringResource(R.string.lines_only)) }, onClick = { viewModel.setShowConstellations(ConstellationMode.LINES); expanded = false })+                        DropdownMenuItem(text = { Text(stringResource(R.string.lines_art)) }, onClick = { viewModel.setShowConstellations(ConstellationMode.LINES_AND_ART); expanded = false })                     }                 }             }-            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Coordinate grid (whole sphere)"); Switch(checked = showGrid, onCheckedChange = { viewModel.setShowGrid(it) }) }-            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Deep sky (Messier)"); Switch(checked = showDeep, onCheckedChange = { viewModel.setShowDeepSky(it) }) }-            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Planets / Sun / Moon"); Switch(checked = showPlanets, onCheckedChange = { viewModel.setShowPlanets(it) }) }-            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Show below horizon (all sky)"); Switch(checked = showBelow, onCheckedChange = { viewModel.setShowBelowHorizon(it) }) }-            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("Night mode (red)"); Switch(checked = nightMode, onCheckedChange = { viewModel.setNightMode(it) }) }+            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(stringResource(R.string.coordinate_grid_whole_sphere)); Switch(checked = showGrid, onCheckedChange = { viewModel.setShowGrid(it) }) }+            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(stringResource(R.string.show_deep_sky)); Switch(checked = showDeep, onCheckedChange = { viewModel.setShowDeepSky(it) }) }+            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(stringResource(R.string.planets_sun_moon)); Switch(checked = showPlanets, onCheckedChange = { viewModel.setShowPlanets(it) }) }+            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(stringResource(R.string.show_below_horizon_all_sky)); Switch(checked = showBelow, onCheckedChange = { viewModel.setShowBelowHorizon(it) }) }+            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text(stringResource(R.string.night_mode)); Switch(checked = nightMode, onCheckedChange = { viewModel.setNightMode(it) }) }              HorizontalDivider() -            Text("Magnitude limit: ${magLimit.format(1)}", style = MaterialTheme.typography.bodyMedium)+            Text(stringResource(R.string.magnitude_limit, magLimit.format(1)), style = MaterialTheme.typography.bodyMedium)             Slider(value = magLimit, onValueChange = { viewModel.setMagLimit(it) }, valueRange = 1f..7f) -            Text("FOV: ${fov.toInt()}°", style = MaterialTheme.typography.bodyMedium)+            Text(stringResource(R.string.fov, fov.toInt()), style = MaterialTheme.typography.bodyMedium)             Slider(value = fov, onValueChange = { viewModel.setFov(it) }, valueRange = 10f..120f)              HorizontalDivider()-            Text("Location", style = MaterialTheme.typography.titleMedium)-            OutlinedTextField(value = latText, onValueChange = { latText = it }, label = { Text("Latitude deg") }, modifier = Modifier.fillMaxWidth())-            OutlinedTextField(value = lonText, onValueChange = { lonText = it }, label = { Text("Longitude deg") }, modifier = Modifier.fillMaxWidth())+            Text(stringResource(R.string.location), style = MaterialTheme.typography.titleMedium)+            OutlinedTextField(value = latText, onValueChange = { latText = it }, label = { Text(stringResource(R.string.latitude_deg)) }, modifier = Modifier.fillMaxWidth())+            OutlinedTextField(value = lonText, onValueChange = { lonText = it }, label = { Text(stringResource(R.string.longitude_deg)) }, modifier = Modifier.fillMaxWidth())             Button(onClick = {                 val lat = latText.toDoubleOrNull(); val lon = lonText.toDoubleOrNull()                 if (lat != null && lon != null) viewModel.setManualLocation(lat, lon)-            }) { Text("Save location") }-            Button(onClick = { viewModel.refreshLocation() }) { Text("Use current location") }+            }) { Text(stringResource(R.string.save_location)) }+            Button(onClick = { viewModel.refreshLocation() }) { Text(stringResource(R.string.use_current_location)) }              HorizontalDivider()-            Text("Notes: True north correction via geomagnetic declination. AR uses CameraX + rotation vector fusion.", style = MaterialTheme.typography.labelSmall)-            Text("Catalog: ${viewModel.getCatalog().stars.size} stars, ${viewModel.getCatalog().constellations.size} constellations, ${viewModel.getCatalog().deepSky.size} DSO.", style = MaterialTheme.typography.labelSmall)+            Text(stringResource(R.string.notes_true_north_correction_via_geomagne), style = MaterialTheme.typography.labelSmall)+            Text(stringResource(R.string.catalog_stars_constellations_dso, viewModel.getCatalog().stars.size, viewModel.getCatalog().constellations.size, viewModel.getCatalog().deepSky.size), style = MaterialTheme.typography.labelSmall)         }     } }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyMapPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyMapPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyMapPage.ktindex 916a9b176f..9e7db8a8c7 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyMapPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyMapPage.kt@@ -15,6 +15,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.ResultEffect import kotlinx.datetime.LocalDate import kotlin.time.ExperimentalTime+import androidx.compose.ui.res.stringResource  // Astronomy scrubs across a wide time range, so the relative jumps are hours/days // rather than the minutes/seconds FindFamily uses.@@ -62,7 +63,7 @@ fun SkyMapPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) {     Scaffold(         topBar = {             TopAppBar(-                title = { Text("Astronomy") },+                title = { Text(stringResource(R.string.app_name)) },                 actions = {                     IconButton(onClick = { backStack.add(Route.Search) }) { IconSearch() }                     IconButton(onClick = { cameraOn = !cameraOn }) {
astronomy/src/main/res/values/strings.xml
diff --git a/astronomy/src/main/res/values/strings.xml b/astronomy/src/main/res/values/strings.xmlindex 51623f39b9..03e392de8e 100644--- a/astronomy/src/main/res/values/strings.xml+++ b/astronomy/src/main/res/values/strings.xml@@ -24,4 +24,57 @@     <string name="center_on_object">Center</string>     <string name="azimuth">Az</string>     <string name="altitude">Alt</string>++    <!-- Migrated hardcoded UI strings (auto) -->+    <!-- ObjectDetailPage -->+    <string name="close">Close</string>+    <string name="object_not_found">Object not found: %1$s</string>+    <string name="circumpolar_never_sets">Circumpolar - never sets</string>+    <string name="alt_az">Alt: %1$s° Az: %2$s°</string>+    <string name="mag">Mag: %1$s</string>+    <string name="rise_transit_set">Rise / Transit / Set</string>+    <string name="trajectory_24h_15m_steps_yellow_line_on">Trajectory 24h (15m steps) - yellow line on map</string>+    <string name="transit_1">Transit: %1$s ?: </string>+    <string name="calculating">Calculating...</string>+    <string name="ra_dec">RA: %1$s° Dec: %2$s°</string>+    <string name="never_rises_at_this_location">Never rises at this location</string>+    <string name="rise_1">Rise: %1$s ?: </string>+    <string name="set_1">Set: %1$s ?: </string>+    <string name="ra_h_h">RA h: %1$sh</string>+    <!-- SearchPage -->+    <string name="search_1">Search</string>+    <string name="search_stars_planets_messier">Search stars, planets, Messier</string>+    <!-- SettingsPage -->+    <string name="magnitude_limit">Magnitude limit: %1$s</string>+    <string name="longitude_deg">Longitude deg</string>+    <string name="save_location">Save location</string>+    <string name="catalog_stars_constellations_dso">Catalog: %1$s stars, %2$s constellations, %3$s DSO.</string>+    <string name="off">Off</string>+    <string name="display">Display</string>+    <string name="constellations">Constellations</string>+    <string name="lines_only">Lines only</string>+    <string name="show_below_horizon_all_sky">Show below horizon (all sky)</string>+    <string name="notes_true_north_correction_via_geomagne">Notes: True north correction via geomagnetic declination. AR uses CameraX + rotation vector fusion.</string>+    <string name="lines_art">Lines + art</string>+    <string name="location">Location</string>+    <string name="coordinate_grid_whole_sphere">Coordinate grid (whole sphere)</string>+    <string name="latitude_deg">Latitude deg</string>+    <string name="use_current_location">Use current location</string>+    <string name="planets_sun_moon">Planets / Sun / Moon</string>+    <string name="fov">FOV: %1$s°</string>+    <!-- Planet names -->+    <string name="planet_sun">Sun</string>+    <string name="planet_moon">Moon</string>+    <string name="planet_mercury">Mercury</string>+    <string name="planet_venus">Venus</string>+    <string name="planet_mars">Mars</string>+    <string name="planet_jupiter">Jupiter</string>+    <string name="planet_saturn">Saturn</string>+    <string name="planet_uranus">Uranus</string>+    <string name="planet_neptune">Neptune</string>+    <!-- Search result labels -->+    <string name="search_result_planet">Planet</string>+    <string name="search_result_star_fallback">Star %1$s</string>+    <string name="search_result_star_mag">Star mag %1$s</string>+    <string name="search_result_constellation">Constellation %1$s</string> </resources>
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex af4861380c..41cdf9d862 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -11,7 +11,7 @@ configure<com.android.build.api.dsl.LibraryExtension> {         compose = true     } -    namespace = "com.vayunmathur.${name.replace("-", "")}"+    namespace = "com.vayunmathur${path.replace(":", ".").replace("-", "")}"     compileSdk {         version = release(37)     }
calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.ktindex b24e8f99e0..5678c979a6 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt@@ -20,8 +20,10 @@ import com.vayunmathur.library.ui.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import androidx.core.content.ContextCompat import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.calendar.R import com.vayunmathur.calendar.data.Instance import com.vayunmathur.calendar.glance.CalendarGlanceWidgetReceiver import com.vayunmathur.calendar.ui.*@@ -141,7 +143,7 @@ fun NoPermissionsScreen(permissions: Array<String>, setHasPermissions: (Boolean)                     permissionRequestor.launch(permissions)                 }, Modifier.align(Alignment.Center)             ) {-                Text(text = "Please grant calendar permission")+                Text(text = stringResource(R.string.please_grant_calendar_permission))             }         }     }
calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt b/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.ktindex 811ae3d303..25c922ee1a 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/glance/CalendarGlanceWidget.kt@@ -53,6 +53,8 @@ import kotlinx.datetime.format.MonthNames import kotlinx.datetime.format.Padding import kotlinx.datetime.plus import kotlinx.datetime.toLocalDateTime+import com.vayunmathur.library.util.localizedDayOfWeekNames+import com.vayunmathur.library.util.localizedMonthNames import kotlinx.serialization.json.Json import kotlin.time.Clock @@ -96,9 +98,9 @@ class CalendarGlanceWidget : GlanceAppWidget() { @Composable private fun CalendarPreviewContent() {     val dateFormatS = LocalDate.Format {-        dayOfWeek(DayOfWeekNames.ENGLISH_ABBREVIATED)+        dayOfWeek(DayOfWeekNames(localizedDayOfWeekNames(java.time.format.TextStyle.SHORT)))         chars(", ")-        monthName(MonthNames.ENGLISH_ABBREVIATED)+        monthName(MonthNames(localizedMonthNames(java.time.format.TextStyle.SHORT)))         chars(" ")         day(Padding.NONE)     }@@ -132,9 +134,9 @@ private fun CalendarPreviewEvent(title: String, time: String, color: Int) { @Composable fun Content(context: Context, positionedEvents: Map<LocalDate, List<Instance>>) {     val dateFormatS = LocalDate.Format {-        dayOfWeek(DayOfWeekNames.ENGLISH_ABBREVIATED)+        dayOfWeek(DayOfWeekNames(localizedDayOfWeekNames(java.time.format.TextStyle.SHORT)))         chars(", ")-        monthName(MonthNames.ENGLISH_ABBREVIATED)+        monthName(MonthNames(localizedMonthNames(java.time.format.TextStyle.SHORT)))         chars(" ")         day(Padding.NONE)     }
calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.ktindex e3f493a31f..09f40f0dcd 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/CalendarScreen.kt@@ -78,7 +78,9 @@ import kotlinx.datetime.DatePeriod import kotlinx.datetime.LocalDate import kotlinx.datetime.TimeZone import kotlinx.datetime.atStartOfDayIn-import kotlinx.datetime.format.MonthNames+import com.vayunmathur.library.util.localizedMonthNames+import com.vayunmathur.library.util.localizedDayOfWeekNames+import java.time.format.TextStyle import kotlinx.datetime.isoDayNumber import kotlinx.datetime.minus import kotlinx.datetime.number@@ -142,7 +144,7 @@ fun CalendarScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>)             TopAppBar(                 {                     // show month/year of the currently visible date-                    val mon = MonthNames.ENGLISH_ABBREVIATED.names[dateViewing.month.number - 1]+                    val mon = localizedMonthNames(TextStyle.SHORT)[dateViewing.month.number - 1]                     Row(                         Modifier.clickable { backStack.add(Route.Calendar.GotoDialog(dateViewing)) },                         verticalAlignment = Alignment.CenterVertically@@ -155,14 +157,14 @@ fun CalendarScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>)                     Box {                         TextButton(onClick = { showLayoutMenu = true }) {                             Row(verticalAlignment = Alignment.CenterVertically) {-                                Text(currentLayout.shortName, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)+                                Text(stringResource(currentLayout.shortNameRes), fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)                                 IconArrowDropDown(tint = MaterialTheme.colorScheme.primary)                             }                         }                         DropdownMenu(expanded = showLayoutMenu, onDismissRequest = { showLayoutMenu = false }) {                             CalendarViewModel.CalendarLayout.entries.forEach { layout ->                                 DropdownMenuItem(-                                    text = { Text(layout.prettyName) },+                                    text = { Text(stringResource(layout.prettyNameRes)) },                                     onClick = {                                         viewModel.setLayout(layout)                                         showLayoutMenu = false@@ -695,7 +697,7 @@ private fun WeekHeader(weekDays: List<LocalDate>) {                 horizontalAlignment = Alignment.CenterHorizontally             ) {                 Text(-                    d.dayOfWeek.name.take(3),+                    localizedDayOfWeekNames(TextStyle.SHORT)[d.dayOfWeek.isoDayNumber - 1],                     Modifier,                     if (isToday) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurfaceVariant,                     fontSize = 12.sp
calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.ktindex 8d37c4a663..80d2af86cf 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScreen.kt@@ -68,6 +68,9 @@ import kotlinx.datetime.format import kotlinx.datetime.format.DayOfWeekNames import kotlinx.datetime.format.MonthNames import kotlinx.datetime.format.Padding+import com.vayunmathur.library.util.localizedDayOfWeekNames+import com.vayunmathur.library.util.localizedMonthNames+import java.time.format.TextStyle import kotlinx.datetime.minus import kotlinx.datetime.plus import kotlinx.datetime.toInstant@@ -145,7 +148,7 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba     var endTime by remember { mutableStateOf(event?.endDateTimeDisplay?.time ?: initialEndLdt?.time ?: startTime) }     var timezone by remember { mutableStateOf(event?.timezone ?: TimeZone.currentSystemDefault().id) }     var rruleObj by remember { mutableStateOf(event?.rrule) }-    val rruleString by remember { derivedStateOf {rruleObj?.toString() ?: ""} }+    val rruleString by remember { derivedStateOf {rruleObj?.describe(context) ?: ""} }     var reminders by remember { mutableStateOf(event?.reminders ?: emptyList()) }      // Shift the end date/time to preserve the current event duration when the start moves.@@ -322,7 +325,7 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba             reminders.forEach { minutes ->                 Item(                     { IconSchedule() },-                    { Text(reminderLabel(minutes)) },+                    { Text(reminderLabel(context, minutes)) },                     { Text(stringResource(R.string.remove), Modifier.clickable { reminders = reminders - minutes }) },                 )             }@@ -337,7 +340,7 @@ fun EditEventScreen(viewModel: CalendarViewModel, editRoute: Route.EditEvent, ba                             DropdownMenu(addReminderExpanded, { addReminderExpanded = false }) {                                 available.forEach { m ->                                     DropdownMenuItem(-                                        text = { Text(reminderLabel(m)) },+                                        text = { Text(reminderLabel(context, m)) },                                         onClick = {                                             addReminderExpanded = false                                             reminders = (reminders + m).sorted()@@ -373,9 +376,9 @@ fun Item(icon: @Composable () -> Unit = {}, left: @Composable () -> Unit, right: }  val dateFormat = LocalDate.Format {-    dayOfWeek(DayOfWeekNames.ENGLISH_ABBREVIATED)+    dayOfWeek(DayOfWeekNames(localizedDayOfWeekNames(TextStyle.SHORT)))     chars(", ")-    monthName(MonthNames.ENGLISH_ABBREVIATED)+    monthName(MonthNames(localizedMonthNames(TextStyle.SHORT)))     chars(" ")     day(Padding.NONE)     chars(", ")@@ -399,9 +402,9 @@ val timeFormat24 = LocalTime.Format { /** Common reminder offsets, in minutes before the event start. */ val REMINDER_PRESETS = listOf(0, 5, 10, 15, 30, 60, 120, 1440) -fun reminderLabel(minutes: Int): String = when {-    minutes <= 0 -> "At time of event"-    minutes % 1440 == 0 -> "${minutes / 1440} day${if (minutes / 1440 > 1) "s" else ""} before"-    minutes % 60 == 0 -> "${minutes / 60} hour${if (minutes / 60 > 1) "s" else ""} before"-    else -> "$minutes minutes before"+fun reminderLabel(context: android.content.Context, minutes: Int): String = when {+    minutes <= 0 -> context.getString(R.string.reminder_at_time_of_event)+    minutes % 1440 == 0 -> context.resources.getQuantityString(R.plurals.reminder_days_before, minutes / 1440, minutes / 1440)+    minutes % 60 == 0 -> context.resources.getQuantityString(R.plurals.reminder_hours_before, minutes / 60, minutes / 60)+    else -> context.resources.getQuantityString(R.plurals.reminder_minutes_before, minutes, minutes) }\ No newline at end of file
calendar/src/main/java/com/vayunmathur/calendar/ui/EventScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EventScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EventScreen.ktindex 6a34ea2f43..68d5fc22d6 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/EventScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EventScreen.kt@@ -122,7 +122,7 @@ fun EventScreen(viewModel: CalendarViewModel, instance: Instance, backStack: Nav                 Column {                     Text(calendar.displayName)                     Text(dateRangeString(context,instance.startDateTimeDisplay.date, instance.endDateTimeDisplay.date, instance.startDateTimeDisplay.time, instance.endDateTimeDisplay.time, instance.allDay))-                    instance.rrule?.let { Text(it.toString()) }+                    instance.rrule?.let { Text(it.describe(context)) }                 }             }, leadingContent = {                 Box(Modifier.size(24.dp).background(Color(calendar.color), RoundedCornerShape(4.dp)))
calendar/src/main/java/com/vayunmathur/calendar/ui/HolidayCalendarsScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/HolidayCalendarsScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/HolidayCalendarsScreen.ktindex 0c1c90436e..c34ccad5e5 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/HolidayCalendarsScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/HolidayCalendarsScreen.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items+import com.vayunmathur.calendar.R import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.CircularProgressIndicator@@ -41,6 +42,7 @@ import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import androidx.compose.ui.res.stringResource  @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -104,7 +106,7 @@ fun HolidayCalendarsScreen(viewModel: CalendarViewModel, backStack: NavBackStack      Scaffold(topBar = {         TopAppBar(-            title = { Text("Holiday calendars") },+            title = { Text(stringResource(R.string.holiday_calendars)) },             navigationIcon = { IconNavigation(backStack) },         )     }) { paddingValues ->@@ -113,7 +115,7 @@ fun HolidayCalendarsScreen(viewModel: CalendarViewModel, backStack: NavBackStack                 value = query,                 onValueChange = { query = it },                 modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),-                placeholder = { Text("Search countries") },+                placeholder = { Text(stringResource(R.string.search_countries)) },                 singleLine = true,             )             LazyColumn(Modifier.fillMaxSize()) {@@ -136,7 +138,7 @@ fun HolidayCalendarsScreen(viewModel: CalendarViewModel, backStack: NavBackStack                             } else if (isAdded) {                                 Switch(checked = true, onCheckedChange = { removeCountry(country.code) })                             } else {-                                TextButton(onClick = { showLangPickerFor = country.code }) { Text("Add") }+                                TextButton(onClick = { showLangPickerFor = country.code }) { Text(stringResource(R.string.add)) }                             }                         },                     )@@ -158,14 +160,14 @@ fun HolidayCalendarsScreen(viewModel: CalendarViewModel, backStack: NavBackStack          AlertDialog(             onDismissRequest = { showLangPickerFor = null },-            title = { Text("Choose language") },+            title = { Text(stringResource(R.string.choose_language)) },             text = {                 Column {                     OutlinedTextField(                         value = langQuery,                         onValueChange = { langQuery = it },                         modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),-                        label = { Text("Search") },+                        label = { Text(stringResource(R.string.search)) },                         singleLine = true,                     )                     LazyColumn(modifier = Modifier.height(360.dp)) {@@ -191,7 +193,7 @@ fun HolidayCalendarsScreen(viewModel: CalendarViewModel, backStack: NavBackStack                 }             },             confirmButton = {-                Button(onClick = { showLangPickerFor = null }) { Text("Close") }+                Button(onClick = { showLangPickerFor = null }) { Text(stringResource(R.string.close)) }             }         )     }
calendar/src/main/java/com/vayunmathur/calendar/ui/ImportActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/ImportActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/ImportActivity.ktindex a73e24d9b5..d106f141d7 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/ImportActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/ImportActivity.kt@@ -133,7 +133,7 @@ fun EventCard(event: Event) {                 // Format date range using the shared helper                 Text(dateRangeString(context, event.startDateTimeDisplay.date, event.endDateTimeDisplay.date, event.startDateTimeDisplay.time, event.endDateTimeDisplay.time, event.allDay))                 // RRULE text-                event.rrule?.let { Text(it.toString()) }+                event.rrule?.let { Text(it.describe(context)) }                  if (event.description.isNotBlank()) {                     Text(event.description)
calendar/src/main/java/com/vayunmathur/calendar/ui/SettingsScreen.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/SettingsScreen.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/SettingsScreen.ktindex 6236f044d8..263697cec4 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/SettingsScreen.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/SettingsScreen.kt@@ -118,19 +118,19 @@ fun SettingsScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>)                     var showDefaultLayoutMenu by remember { mutableStateOf(false) }                      ListItem(-                        content = { Text("Default Layout") },+                        content = { Text(stringResource(R.string.default_layout)) },                         trailingContent = {                             Box {                                 TextButton(onClick = { showDefaultLayoutMenu = true }) {                                     Row(verticalAlignment = Alignment.CenterVertically) {-                                        Text(currentLayout.prettyName)+                                        Text(stringResource(currentLayout.prettyNameRes))                                         IconArrowDropDown()                                     }                                 }                                 DropdownMenu(expanded = showDefaultLayoutMenu, onDismissRequest = { showDefaultLayoutMenu = false }) {                                     CalendarViewModel.CalendarLayout.entries.forEach { layout ->                                         DropdownMenuItem(-                                            text = { Text(layout.prettyName) },+                                            text = { Text(stringResource(layout.prettyNameRes)) },                                             onClick = {                                                 viewModel.setLayout(layout)                                                 showDefaultLayoutMenu = false@@ -149,19 +149,19 @@ fun SettingsScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>)                     var showThemeMenu by remember { mutableStateOf(false) }                      ListItem(-                        content = { Text("Theme") },+                        content = { Text(stringResource(R.string.theme)) },                         trailingContent = {                             Box {                                 TextButton(onClick = { showThemeMenu = true }) {                                     Row(verticalAlignment = Alignment.CenterVertically) {-                                        Text(currentTheme.prettyName)+                                        Text(stringResource(currentTheme.prettyNameRes))                                         IconArrowDropDown()                                     }                                 }                                 DropdownMenu(expanded = showThemeMenu, onDismissRequest = { showThemeMenu = false }) {                                     CalendarViewModel.ThemeMode.entries.forEach { mode ->                                         DropdownMenuItem(-                                            text = { Text(mode.prettyName) },+                                            text = { Text(stringResource(mode.prettyNameRes)) },                                             onClick = {                                                 viewModel.setThemeMode(mode)                                                 showThemeMenu = false@@ -177,8 +177,8 @@ fun SettingsScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>)                  item {                     ListItem(-                        content = { Text("Holiday calendars") },-                        supportingContent = { Text("Add public holidays for countries") },+                        content = { Text(stringResource(R.string.holiday_calendars)) },+                        supportingContent = { Text(stringResource(R.string.add_public_holidays_for_countries)) },                         modifier = Modifier.clickable { backStack.add(Route.Settings.HolidayCalendars) },                         trailingContent = {                             IconArrowDropDown()@@ -190,7 +190,7 @@ fun SettingsScreen(viewModel: CalendarViewModel, backStack: NavBackStack<Route>)                 item {                     ListItem(                         content = { Text(stringResource(R.string.import_ics_file)) },-                        supportingContent = { Text("Import events from .ics files") },+                        supportingContent = { Text(stringResource(R.string.import_events_from_ics_files)) },                         modifier = Modifier.clickable {                             importLauncher.launch(arrayOf(                                 "text/calendar",
calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.ktindex da34011413..f3c8d7b02a 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDialog.kt@@ -46,7 +46,9 @@ import kotlinx.coroutines.launch import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.format-import kotlinx.datetime.format.MonthNames+import com.vayunmathur.library.util.localizedMonthNames+import com.vayunmathur.library.util.localizedDayOfWeekNames+import java.time.format.TextStyle import kotlinx.datetime.isoDayNumber import kotlinx.datetime.number @@ -84,9 +86,9 @@ fun RecurrenceDialog(backStack: NavBackStack<Route>, resultKey: String, startDat     }      // Values derived from the chosen start date, used to label the preset options.-    val weekdayFull = startDate.dayOfWeek.name.lowercase().replaceFirstChar { it.titlecase() }+    val weekdayFull = localizedDayOfWeekNames(TextStyle.FULL)[startDate.dayOfWeek.isoDayNumber - 1]     val nthOfMonth = ordinal((startDate.day - 1) / 7 + 1)-    val monthName = MonthNames.ENGLISH_FULL.names[startDate.month.number - 1]+    val monthName = localizedMonthNames(TextStyle.FULL)[startDate.month.number - 1]      AlertDialog(         onDismissRequest = { backStack.pop() },@@ -165,7 +167,7 @@ fun RecurrenceDialog(backStack: NavBackStack<Route>, resultKey: String, startDat                         }, color = if(d in daysOfWeek) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.secondaryContainer,                             shape = CircleShape) {                             Box(Modifier.size(50.dp), contentAlignment = Alignment.Center) {-                                Text(d.name.take(3).lowercase().replaceFirstChar { it.titlecase() })+                                Text(localizedDayOfWeekNames(TextStyle.SHORT)[d.isoDayNumber - 1])                             }                         }                     }
calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.ktindex 83dbd93633..ed91e0921c 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt@@ -4,9 +4,11 @@ import android.content.ContentValues import android.net.Uri import android.provider.CalendarContract import android.util.Log+import androidx.annotation.StringRes import androidx.glance.appwidget.updateAll import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.calendar.R import com.vayunmathur.calendar.glance.CalendarGlanceWidget import com.vayunmathur.calendar.ui.parseICSFile import kotlinx.coroutines.Dispatchers@@ -42,14 +44,14 @@ class CalendarViewModel(application: Application) : AndroidViewModel(application     private val _lastViewedDate = MutableStateFlow<LocalDate?>(null)     val lastViewedDate: StateFlow<LocalDate?> = _lastViewedDate.asStateFlow() -    enum class CalendarLayout(val shortName: String, val prettyName: String) {-        Agenda("A", "Agenda"),-        Day("D", "Day"),-        WorkWeek("W5", "Work Week"),-        FullWeek("W7", "Full Week"),-        Month("M", "Month"),-        WorkWeekSummary("W5S", "Work Week Summary"),-        FullWeekSummary("W7S", "Full Week Summary")+    enum class CalendarLayout(@StringRes val shortNameRes: Int, @StringRes val prettyNameRes: Int) {+        Agenda(R.string.layout_short_agenda, R.string.layout_agenda),+        Day(R.string.layout_short_day, R.string.layout_day),+        WorkWeek(R.string.layout_short_work_week, R.string.layout_work_week),+        FullWeek(R.string.layout_short_full_week, R.string.layout_full_week),+        Month(R.string.layout_short_month, R.string.layout_month),+        WorkWeekSummary(R.string.layout_short_work_week_summary, R.string.layout_work_week_summary),+        FullWeekSummary(R.string.layout_short_full_week_summary, R.string.layout_full_week_summary)     }      private val _currentLayout = MutableStateFlow(@@ -66,10 +68,10 @@ class CalendarViewModel(application: Application) : AndroidViewModel(application         }     } -    enum class ThemeMode(val prettyName: String) {-        System("System default"),-        Light("Light"),-        Dark("Dark"),+    enum class ThemeMode(@StringRes val prettyNameRes: Int) {+        System(R.string.theme_system_default),+        Light(R.string.theme_light),+        Dark(R.string.theme_dark),     }      private val _themeMode = MutableStateFlow(
calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.ktindex b05bfb0674..42419fe78b 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/RRule.kt@@ -1,11 +1,16 @@ package com.vayunmathur.calendar.util+import android.content.Context+import com.vayunmathur.calendar.R import com.vayunmathur.calendar.ui.dateFormat+import com.vayunmathur.library.util.localizedDayOfWeekNames+import java.time.format.TextStyle import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone import kotlinx.datetime.atTime import kotlinx.datetime.format+import kotlinx.datetime.isoDayNumber import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlinx.serialization.Serializable@@ -37,10 +42,10 @@ private fun RRule.EndCondition.toRRuleSuffix(timeZone: TimeZone): String = when     is RRule.EndCondition.Until -> ";UNTIL=${date.toIcalString(timeZone)}" } -private fun RRule.EndCondition.toStringSuffix(): String = when (this) {+private fun RRule.EndCondition.describeSuffix(context: Context): String = when (this) {     is RRule.EndCondition.Never -> ""-    is RRule.EndCondition.Count -> ", $count times"-    is RRule.EndCondition.Until -> ", Until ${date.format(dateFormat)}"+    is RRule.EndCondition.Count -> context.resources.getQuantityString(R.plurals.rrule_count_suffix, count.toInt(), count)+    is RRule.EndCondition.Until -> context.getString(R.string.rrule_until_suffix, date.format(dateFormat)) }  @Serializable@@ -54,10 +59,10 @@ sealed class RRule {     abstract val wkst: DayOfWeek?     abstract val byDay: List<DayOfWeek>?     abstract fun asString(firstDay: LocalDate, timeZone: TimeZone): String-    final override fun toString(): String {-        return toStringImpl() + endCondition.toStringSuffix()+    fun describe(context: Context): String {+        return describeImpl(context) + endCondition.describeSuffix(context)     }-    protected abstract fun toStringImpl(): String+    protected abstract fun describeImpl(context: Context): String      companion object {         fun parse(content: String, timeZone: TimeZone): RRule? {@@ -183,7 +188,9 @@ sealed class RRule {             val base = "FREQ=YEARLY;INTERVAL=$years"             return buildRRuleString(base, timeZone)         }-        override fun toStringImpl(): String = if (years == 1) "Yearly" else "Every $years years"+        override fun describeImpl(context: Context): String =+            if (years == 1) context.getString(R.string.rrule_yearly)+            else context.resources.getQuantityString(R.plurals.rrule_every_years, years, years)     }      @Serializable@@ -212,7 +219,9 @@ sealed class RRule {             }             return buildRRuleString(base + byDayPart, timeZone)         }-        override fun toStringImpl(): String = if (months == 1) "Monthly" else "Every $months months"+        override fun describeImpl(context: Context): String =+            if (months == 1) context.getString(R.string.rrule_monthly)+            else context.resources.getQuantityString(R.plurals.rrule_every_months, months, months)     }      @Serializable@@ -233,13 +242,14 @@ sealed class RRule {             val base = "FREQ=WEEKLY;INTERVAL=$weeks;BYDAY=$days"             return buildRRuleString(base, timeZone)         }-        override fun toStringImpl(): String {-            val prefix = if (weeks == 1) "Weekly" else "Every $weeks weeks"+        override fun describeImpl(context: Context): String {+            val prefix = if (weeks == 1) context.getString(R.string.rrule_weekly)+            else context.resources.getQuantityString(R.plurals.rrule_every_weeks, weeks, weeks)             if (daysOfWeek.isEmpty()) return prefix             val days = daysOfWeek.sorted().joinToString(", ") {-                it.name.take(3).lowercase().replaceFirstChar { c -> c.titlecase() }+                localizedDayOfWeekNames(TextStyle.SHORT)[it.isoDayNumber - 1]             }-            return "$prefix on $days"+            return context.getString(R.string.rrule_on_days, prefix, days)         }     } @@ -259,6 +269,8 @@ sealed class RRule {             val base = "FREQ=DAILY;INTERVAL=$days"             return buildRRuleString(base, timeZone)         }-        override fun toStringImpl(): String = if (days == 1) "Daily" else "Every $days days"+        override fun describeImpl(context: Context): String =+            if (days == 1) context.getString(R.string.rrule_daily)+            else context.resources.getQuantityString(R.plurals.rrule_every_days, days, days)     } }\ No newline at end of file
calendar/src/main/res/values/strings.xml
diff --git a/calendar/src/main/res/values/strings.xml b/calendar/src/main/res/values/strings.xmlindex 9150bc0d24..856a1ac57b 100644--- a/calendar/src/main/res/values/strings.xml+++ b/calendar/src/main/res/values/strings.xml@@ -1,5 +1,26 @@ <resources>     <string name="app_name">Calendar</string>++    <!-- Calendar layout labels (CalendarLayout enum) -->+    <string name="layout_agenda">Agenda</string>+    <string name="layout_day">Day</string>+    <string name="layout_work_week">Work Week</string>+    <string name="layout_full_week">Full Week</string>+    <string name="layout_month">Month</string>+    <string name="layout_work_week_summary">Work Week Summary</string>+    <string name="layout_full_week_summary">Full Week Summary</string>+    <string name="layout_short_agenda">A</string>+    <string name="layout_short_day">D</string>+    <string name="layout_short_work_week">W5</string>+    <string name="layout_short_full_week">W7</string>+    <string name="layout_short_month">M</string>+    <string name="layout_short_work_week_summary">W5S</string>+    <string name="layout_short_full_week_summary">W7S</string>++    <!-- Theme mode labels (ThemeMode enum) -->+    <string name="theme_system_default">System default</string>+    <string name="theme_light">Light</string>+    <string name="theme_dark">Dark</string>     <string name="calendar_widget_description">Upcoming events at a glance — tap to open Calendar</string>      <!-- Common actions -->@@ -112,4 +133,60 @@      <!-- Settings screen -->     <string name="default_layout">Default Layout</string>++    <!-- Migrated hardcoded UI strings (auto) -->+    <!-- HolidayCalendarsScreen -->+    <string name="search_countries">Search countries</string>+    <string name="choose_language">Choose language</string>+    <string name="add">Add</string>+    <string name="holiday_calendars">Holiday calendars</string>+    <!-- MainActivity -->+    <string name="please_grant_calendar_permission">Please grant calendar permission</string>+    <!-- SettingsScreen -->+    <string name="import_events_from_ics_files">Import events from .ics files</string>+    <string name="theme">Theme</string>+    <string name="add_public_holidays_for_countries">Add public holidays for countries</string>++    <!-- Reminder labels (EditEventScreen.reminderLabel) -->+    <string name="reminder_at_time_of_event">At time of event</string>+    <plurals name="reminder_days_before">+        <item quantity="one">%1$d day before</item>+        <item quantity="other">%1$d days before</item>+    </plurals>+    <plurals name="reminder_hours_before">+        <item quantity="one">%1$d hour before</item>+        <item quantity="other">%1$d hours before</item>+    </plurals>+    <plurals name="reminder_minutes_before">+        <item quantity="one">%1$d minute before</item>+        <item quantity="other">%1$d minutes before</item>+    </plurals>++    <!-- Recurrence summary (RRule.describe) -->+    <string name="rrule_daily">Daily</string>+    <plurals name="rrule_every_days">+        <item quantity="one">Every %1$d day</item>+        <item quantity="other">Every %1$d days</item>+    </plurals>+    <string name="rrule_weekly">Weekly</string>+    <plurals name="rrule_every_weeks">+        <item quantity="one">Every %1$d week</item>+        <item quantity="other">Every %1$d weeks</item>+    </plurals>+    <string name="rrule_monthly">Monthly</string>+    <plurals name="rrule_every_months">+        <item quantity="one">Every %1$d month</item>+        <item quantity="other">Every %1$d months</item>+    </plurals>+    <string name="rrule_yearly">Yearly</string>+    <plurals name="rrule_every_years">+        <item quantity="one">Every %1$d year</item>+        <item quantity="other">Every %1$d years</item>+    </plurals>+    <string name="rrule_on_days">%1$s on %2$s</string>+    <plurals name="rrule_count_suffix">+        <item quantity="one">, %1$d time</item>+        <item quantity="other">, %1$d times</item>+    </plurals>+    <string name="rrule_until_suffix">, Until %1$s</string> </resources>\ No newline at end of file
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex dbc76dcba6..73c305f0c3 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -119,7 +119,8 @@ dependencies {     implementation(libs.androidx.camera.view)     implementation(libs.androidx.camera.video)     implementation(libs.androidx.camera.compose)+    implementation(libs.androidx.camera.extensions)     implementation(libs.androidx.exifinterface)     implementation(libs.zxing.core)-    implementation("com.google.mediapipe:tasks-vision:0.10.14")+    implementation(libs.mediapipe.tasks.vision) }
camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.ktindex 336c0fac88..2679a1954d 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -1076,7 +1076,7 @@ private fun NightModeButton(     ) {         IconBedtime(Modifier.size(20.dp).rotate(iconRotation), if (active) Color.White else Color(0xFFBBBBBB))         Text(-            "Night",+            text = stringResource(R.string.night),             color = if (active) Color.White else Color(0xFFBBBBBB),             fontSize = 13.sp,             fontWeight = if (active) FontWeight.Bold else FontWeight.Normal@@ -1635,7 +1635,7 @@ private fun IsoBar(             )         }         Text(-            text = if (selectedIndex == 0) "Auto" else "${isoStops.getOrNull(selectedIndex - 1) ?: ""}",+            text = if (selectedIndex == 0) stringResource(R.string.auto) else "${isoStops.getOrNull(selectedIndex - 1) ?: ""}",             color = Color.White,             fontSize = 13.sp,             fontWeight = FontWeight.Medium,@@ -1660,7 +1660,7 @@ private fun PanoramaOverlay(             Column(horizontalAlignment = Alignment.CenterHorizontally) {                 CircularProgressIndicator(color = Color.White, strokeWidth = 2.dp)                 Spacer(Modifier.height(8.dp))-                Text("Processing panorama\u2026", color = Color.White, fontSize = 16.sp)+                Text(text = stringResource(R.string.processing_panorama_u2026), color = Color.White, fontSize = 16.sp)             }         }         return
camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.ktindex 28c2fe9585..0777052ec1 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/SettingsPage.kt@@ -88,7 +88,7 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                         onExpandedChange = { expanded = it }                     ) {                         OutlinedTextField(-                            value = "${videoCodec.label} — ${videoCodec.description}",+                            value = "${stringResource(videoCodec.labelRes)} — ${stringResource(videoCodec.descriptionRes)}",                             onValueChange = {},                             readOnly = true,                             trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },@@ -106,9 +106,9 @@ fun <T : NavKey> SettingsPage(backStack: NavBackStack<T>, viewModel: CameraViewM                                 DropdownMenuItem(                                     text = {                                         Column {-                                            Text(codec.label)+                                            Text(stringResource(codec.labelRes))                                             Text(-                                                codec.description,+                                                stringResource(codec.descriptionRes),                                                 style = MaterialTheme.typography.bodySmall,                                                 color = MaterialTheme.colorScheme.onSurfaceVariant                                             )
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 248e6fbcd6..b01ce44bed 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -18,6 +18,8 @@ import android.location.LocationManager import android.media.MediaFormat import android.net.Uri import android.provider.MediaStore+import androidx.annotation.StringRes+import com.vayunmathur.camera.R import android.util.Log import android.util.Size import android.view.Surface@@ -34,6 +36,8 @@ import androidx.camera.core.SurfaceRequest import androidx.camera.core.resolutionselector.ResolutionSelector import androidx.camera.core.resolutionselector.ResolutionStrategy import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.extensions.ExtensionMode+import androidx.camera.extensions.ExtensionsManager import androidx.camera.video.FileOutputOptions import androidx.camera.video.HighSpeedVideoSessionConfig import androidx.camera.video.MediaStoreOutputOptions@@ -59,6 +63,8 @@ import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlin.coroutines.resume import kotlinx.coroutines.withContext import androidx.camera.lifecycle.awaitInstance import java.io.ByteArrayInputStream@@ -69,10 +75,10 @@ enum class CameraMode { PHOTO, PORTRAIT, PANORAMA, PHOTOSPHERE, VIDEO, SLOW_MO, enum class FlashMode { ON, OFF, AUTO } enum class TimerDuration(val seconds: Int) { NONE(0), THREE(3), FIVE(5), TEN(10) } enum class AspectRatioOption(val label: String) { RATIO_16_9("16:9"), RATIO_4_3("4:3"), RATIO_1_1("1:1") }-enum class VideoCodec(val label: String, val description: String) {-    AVC("H.264 / AVC", "Most compatible"),-    HEVC("H.265 / HEVC", "More efficient"),-    AV1("AV1", "Most efficient"),+enum class VideoCodec(@StringRes val labelRes: Int, @StringRes val descriptionRes: Int) {+    AVC(R.string.codec_avc_label, R.string.codec_avc_description),+    HEVC(R.string.codec_hevc_label, R.string.codec_hevc_description),+    AV1(R.string.codec_av1_label, R.string.codec_av1_description), }  /** Formats a zoom ratio for the zoom bar: ".5", "1x", "2x", or "1.5x". */@@ -356,6 +362,8 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     val surfaceRequest = _surfaceRequest.asStateFlow()      private var cameraProvider: ProcessCameraProvider? = null+    // Cached per ProcessCameraProvider instance; ExtensionsManager must be tied to the same provider.+    private var extensionsManager: ExtensionsManager? = null     private var sessionLifecycleOwner: ManualLifecycleOwner? = null     private var boundCamera: Camera? = null     private var imageCapture: ImageCapture? = null@@ -1866,13 +1874,145 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         }     } +    /**+     * Routes the night shutter: prefer CameraX Extensions NIGHT (vendor multi-frame processing)+     * when available on the current lens, otherwise fall back to the custom burst + Rust merge.+     */+    private fun captureNightPhoto() {+        viewModelScope.launch {+            if (isNightExtensionAvailable()) {+                captureNightPhotoExtension()+            } else {+                captureNightPhotoCustom()+            }+        }+    }++    /** Obtains (and caches) the ExtensionsManager bound to [provider]. Null if unavailable. */+    private suspend fun getExtensionsManager(provider: ProcessCameraProvider): ExtensionsManager? {+        extensionsManager?.let { return it }+        return try {+            val mgr = suspendCancellableCoroutine<ExtensionsManager> { cont ->+                val future = ExtensionsManager.getInstanceAsync(app, provider)+                future.addListener({+                    try {+                        cont.resume(future.get())+                    } catch (e: Exception) {+                        cont.cancel(e)+                    }+                }, ContextCompat.getMainExecutor(app))+            }+            extensionsManager = mgr+            mgr+        } catch (e: Exception) {+            Log.w("CameraViewModel", "ExtensionsManager unavailable", e)+            null+        }+    }++    /** Whether the CameraX NIGHT extension is available on the current lens. */+    suspend fun isNightExtensionAvailable(): Boolean {+        return try {+            val provider = ProcessCameraProvider.awaitInstance(app)+            val mgr = getExtensionsManager(provider) ?: return false+            val selector = CameraSelector.Builder()+                .requireLensFacing(_lensFacing.value)+                .build()+            mgr.isExtensionAvailable(selector, ExtensionMode.NIGHT)+        } catch (e: Exception) {+            Log.w("CameraViewModel", "Night extension availability check failed", e)+            false+        }+    }++    /**+     * On-demand NIGHT-extension capture: briefly rebinds a Preview + ImageCapture session with the+     * extension-enabled selector, takes one standard shot (the vendor handles the multi-frame night+     * merge internally), saves it, then restores the normal analysis-backed photo session so the+     * moon button keeps tracking brightness. The extension does its own timing, so no manual+     * long-exposure countdown here.+     */+    private suspend fun captureNightPhotoExtension() {+        _isCapturing.value = true+        // Drop the photo session so the UI's analyzer effect re-attaches PhotoAnalyzer once we restore.+        _photoSessionActive.value = false+        try {+            val provider = ProcessCameraProvider.awaitInstance(app)+            cameraProvider = provider+            val mgr = getExtensionsManager(provider)+            if (mgr == null) {+                // Unreachable in practice: entry is gated by isNightExtensionAvailable(), which+                // already resolved the manager. Bail out; finally restores the normal session.+                Log.w("CameraViewModel", "ExtensionsManager missing at night capture; skipping")+                return+            }+            provider.unbindAll()+            imageAnalysis = null+            currentAnalyzer = null++            val baseSelector = CameraSelector.Builder()+                .requireLensFacing(_lensFacing.value)+                .build()+            val nightSelector = mgr.getExtensionEnabledCameraSelector(baseSelector, ExtensionMode.NIGHT)++            val preview = Preview.Builder().build()+            preview.setSurfaceProvider { request -> _surfaceRequest.value = request }++            val owner = ManualLifecycleOwner()+            owner.start()+            sessionLifecycleOwner = owner++            val capture = ImageCapture.Builder()+                .setFlashMode(getImageCaptureFlashMode())+                .setTargetRotation(targetRotation)+                .build()+            imageCapture = capture+            boundCamera = provider.bindToLifecycle(owner, nightSelector, preview, capture)++            val contentValues = MediaStoreSaver.imageValues("IMG_${MediaStoreSaver.timestamp()}.jpg")+            val metadata = ImageCapture.Metadata().apply {+                if (_locationEnabled.value) location = lastLocation+                isReversedHorizontal = mirrorCaptures+            }+            val outputOptions = ImageCapture.OutputFileOptions.Builder(+                app.contentResolver,+                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,+                contentValues+            ).setMetadata(metadata).build()++            val savedUri = suspendCancellableCoroutine<Uri?> { cont ->+                capture.takePicture(+                    outputOptions,+                    ContextCompat.getMainExecutor(app),+                    object : ImageCapture.OnImageSavedCallback {+                        override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {+                            cont.resume(outputFileResults.savedUri)+                        }+                        override fun onError(exception: ImageCaptureException) {+                            Log.e("CameraViewModel", "Night extension capture failed", exception)+                            cont.resume(null)+                        }+                    }+                )+            }+            if (savedUri != null) setLastCaptureUri(savedUri)+        } catch (e: Exception) {+            Log.e("CameraViewModel", "Night extension capture path failed", e)+        } finally {+            // Rebind the normal 3-stream session; sets _photoSessionActive=true so the UI re-attaches+            // PhotoAnalyzer. If teardown interrupted us, this is superseded by the lifecycle rebind.+            setupPhotoSession()+            _isCapturing.value = false+        }+    }+     /**      * Multi-frame night capture: locks the sensor to a per-frame night exposure/ISO, collects a      * burst off the ImageAnalysis stream, then aligns + merges + brightens it (via      * [NightCaptureEngine]) and saves. Falls back to the single long-exposure capture if the burst      * is empty or the merge fails, so the user always gets a shot.      */-    private fun captureNightPhoto() {+    private fun captureNightPhotoCustom() {         _isCapturing.value = true         val perFrame = computeNightExposure(NIGHT_BURST_PER_FRAME_NANOS)         // The countdown overlay shows the total burst duration.@@ -1911,13 +2051,17 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     }      /**-     * Locks 3A to [exposure], temporarily swaps the analyzer for a frame collector that gathers the-     * next [NightCaptureEngine.NIGHT_BURST_COUNT] frames as upright (front-mirrored) bitmaps, then-     * restores auto 3A and the previous analyzer and invokes [onDone] with the collected frames-     * (empty if the analysis stream is unavailable).+     * Proper night burst: full-res capture via [ImageCapture] instead of low-res+     * [ImageAnalysis]. Locks 3A to [exposure], then fires [NightCaptureEngine.NIGHT_BURST_COUNT]+     * full-resolution in-memory captures, each converted to upright/consistent bitmap.+     * This avoids the previous path's analysis-resolution limitation and double JPEG+     * loss (now passed lossless RGBA to Rust via [StitchNative.newNightSession]).+     *+     * Falls back to empty list if [imageCapture] is unavailable, which makes+     * [captureNightPhotoCustom] fall back to single-frame long-exposure.      */     private fun captureNightBurst(exposure: NightExposure, onDone: (List<Bitmap>) -> Unit) {-        if (imageAnalysis == null) {+        val capture = imageCapture ?: run {             onDone(emptyList())             return         }@@ -1925,14 +2069,15 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             boundCamera?.cameraControl?.let {                 androidx.camera.camera2.interop.Camera2CameraControl.from(it)             }-        } catch (e: Exception) { Log.w("CameraViewModel", "Camera2 control unavailable", e); null }--        val previousAnalyzer = currentAnalyzer+        } catch (e: Exception) {+            Log.w("CameraViewModel", "Camera2 control unavailable", e)+            null+        }         val mirror = mirrorCaptures         val collected = mutableListOf<Bitmap>()-        var finished = false+        var alreadyDone = false -        fun restore() {+        fun restore3A() {             if (cam2Control != null) {                 try {                     cam2Control.setCaptureRequestOptions(@@ -1947,35 +2092,62 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                     Log.w("CameraViewModel", "Failed to restore auto 3A after night burst", e)                 }             }-            setImageAnalyzer(previousAnalyzer)         } -        val collector = ImageAnalysis.Analyzer { imageProxy ->-            if (!finished && collected.size < NightCaptureEngine.NIGHT_BURST_COUNT) {-                try {-                    val raw = imageProxy.toBitmap()-                    val matrix = Matrix().apply {-                        postRotate(imageProxy.imageInfo.rotationDegrees.toFloat())-                        if (mirror) postScale(-1f, 1f)-                    }-                    val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)-                    if (upright !== raw) raw.recycle()-                    collected.add(upright)-                } catch (e: Exception) {-                    Log.w("CameraViewModel", "Failed to collect night burst frame", e)-                }+        fun finish() {+            if (alreadyDone) return+            alreadyDone = true+            restore3A()+            // Re-assert (auto) manual-control state to fully undo night override.+            try {+                applyManualControls()+            } catch (_: Exception) {}+            onDone(collected.toList())+        }++        fun takeNext() {+            if (collected.size >= NightCaptureEngine.NIGHT_BURST_COUNT) {+                finish()+                return             }-            imageProxy.close()-            if (!finished && collected.size >= NightCaptureEngine.NIGHT_BURST_COUNT) {-                finished = true-                restore()-                onDone(collected.toList())+            val cap = imageCapture ?: run {+                finish()+                return             }+            cap.takePicture(+                ContextCompat.getMainExecutor(app),+                object : ImageCapture.OnImageCapturedCallback() {+                    override fun onCaptureSuccess(image: ImageProxy) {+                        try {+                            // toBitmap() is provided by CameraX (used also in BokehAnalyzer)+                            val raw = image.toBitmap()+                            val matrix = Matrix().apply {+                                postRotate(image.imageInfo.rotationDegrees.toFloat())+                                if (mirror) postScale(-1f, 1f)+                            }+                            val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)+                            if (upright !== raw) raw.recycle()+                            collected.add(upright)+                        } catch (e: Exception) {+                            Log.w("CameraViewModel", "Failed to convert night frame", e)+                        } finally {+                            image.close()+                        }+                        takeNext()+                    }++                    override fun onError(exception: ImageCaptureException) {+                        Log.w("CameraViewModel", "Night frame capture failed, continuing", exception)+                        takeNext()+                    }+                }+            )         } +        // Lock AE off + set per-frame night exposure/ISO + lock AWB to avoid color drift, then start burst.         if (cam2Control != null) {             try {-                val options = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()+                val optsBuilder = androidx.camera.camera2.interop.CaptureRequestOptions.Builder()                     .setCaptureRequestOption(                         android.hardware.camera2.CaptureRequest.CONTROL_AE_MODE,                         android.hardware.camera2.CameraMetadata.CONTROL_AE_MODE_OFF@@ -1984,23 +2156,22 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                         android.hardware.camera2.CaptureRequest.SENSOR_EXPOSURE_TIME,                         exposure.nanos                     )-                    // Lock white balance so frames merge without color drift across the burst.                     .setCaptureRequestOption(                         android.hardware.camera2.CaptureRequest.CONTROL_AWB_LOCK, true                     )                 exposure.iso?.let {-                    options.setCaptureRequestOption(+                    optsBuilder.setCaptureRequestOption(                         android.hardware.camera2.CaptureRequest.SENSOR_SENSITIVITY, it                     )                 }-                cam2Control.setCaptureRequestOptions(options.build())-                    .addListener({ setImageAnalyzer(collector) }, ContextCompat.getMainExecutor(app))+                cam2Control.setCaptureRequestOptions(optsBuilder.build())+                    .addListener({ takeNext() }, ContextCompat.getMainExecutor(app))             } catch (e: Exception) {                 Log.w("CameraViewModel", "Failed to set night exposure for burst", e)-                setImageAnalyzer(collector)+                takeNext()             }         } else {-            setImageAnalyzer(collector)+            takeNext()         }     } 
camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt b/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.ktindex fad5b817b5..de91e345a8 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/NightCaptureEngine.kt@@ -8,32 +8,50 @@ import kotlin.math.roundToInt  /**  * Multi-frame computational night capture. Takes a burst of upright/consistent- * (uncompressed) frames, aligns + merges them via the native [StitchNative] Rust- * library to cut noise (~√N read/shot-noise reduction), then brightens the- * result so it reads as a bright night shot.+ * frames, aligns + merges them via the native [StitchNative] Rust library to cut+ * noise (~√N read/shot-noise reduction), then brightens the result with a+ * highlight-preserving curve so it reads as a bright night shot without clipping.  *- * Source-agnostic: it only sees a [List]<[Bitmap]>. Alignment (feature-based- * homography + temporal average) now lives in Rust, replacing the old OpenCV- * SIFT path.+ * This is currently the *primary* night path — the app does not depend on+ * camera-extensions / ExtensionMode.NIGHT, so vendor Night extension (Pixel/Samsung ISP)+ * is unavailable. This custom path is used when auto low-light detection fires.+ *+ * Improvements vs old path:+ * - Burst is still collected from ImageAnalysis but at HIGHEST_AVAILABLE resolution,+ *   and fed to Rust as lossless RGBA via newNightSession/addNightRgbaFrame/mergeNight,+ *   avoiding the old Bitmap -> JPEG 95 -> decode double loss.+ * - Rust runs ORB registration at ~0.8 MP, rescales homography to full res, + deghosting+ *   against reference to avoid moving-object ghosts.+ * - Tone mapping preserves highlights with a soft knee instead of linear *1.6+18 clip.+ * - Full-res ImageCapture burst variant captures via ImageCapture repeated+ *   onImageCaptured (higher IQ than analysis stream).  */ object NightCaptureEngine {     /** How many frames to stack. Higher = less noise but longer capture + more work. */     const val NIGHT_BURST_COUNT = 6 -    // Brightening baked into the merged result.+    // Brightening baked into the merged result (shadow lift + gain, highlight compressed).     private const val NIGHT_GAIN = 1.6f     private const val NIGHT_SHADOW_LIFT = 18f+    private const val HIGHLIGHT_COMPRESS_START = 220f+    private const val HIGHLIGHT_COMPRESS_FACTOR = 0.38f      /**-     * Aligns and merges [burst] into a single brightened bitmap. Returns null only when [burst] is-     * empty. Falls back to the middle frame if native align/merge is unavailable. Runs off the main-     * thread; the caller owns recycling of the input bitmaps.+     * Aligns and merges [burst] into a single brightened bitmap. Falls back to the+     * middle frame if native align/merge is unavailable. Runs off the main thread.      */     suspend fun merge(burst: List<Bitmap>): Bitmap? = withContext(Dispatchers.Default) {         if (burst.isEmpty()) return@withContext null+        val sized = burst.filter { it.width > 0 && it.height > 0 }.let { list ->+            if (list.isEmpty()) return@withContext null+            val w = list[0].width+            val h = list[0].height+            val same = list.filter { it.width == w && it.height == h }+            if (same.size >= 2) same else list.take(1)+        } -        val merged = alignAndMergeNative(burst)-        val source = merged ?: burst[burst.size / 2]+        val merged = alignAndMergeNative(sized)+        val source = merged ?: sized[sized.size / 2]          val w = source.width         val h = source.height@@ -42,35 +60,97 @@ object NightCaptureEngine {         source.getPixels(px, 0, w, 0, 0, w, h)         for (i in 0 until n) {             val p = px[i]-            val r = brighten(((p shr 16) and 0xFF).toFloat())-            val g = brighten(((p shr 8) and 0xFF).toFloat())-            val b = brighten((p and 0xFF).toFloat())-            px[i] = (0xFF shl 24) or (r shl 16) or (g shl 8) or b+            val a = (p ushr 24) and 0xFF+            val r = (p shr 16) and 0xFF+            val g = (p shr 8) and 0xFF+            val b = p and 0xFF+            // Alpha preserved from source, RGB via highlight-preserving curve+            val rr = brightenChannel(r.toFloat())+            val gg = brightenChannel(g.toFloat())+            val bb = brightenChannel(b.toFloat())+            px[i] = (a shl 24) or (rr shl 16) or (gg shl 8) or bb+        }+        if (merged != null && merged !== source) {+            merged.recycle()         }-        merged?.recycle()         Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply {             setPixels(px, 0, w, 0, 0, w, h)         }     } -    /** Runs the native feature-based align + temporal-average merge; null on failure. */+    /** Lossless RGBA path -> Rust (no double JPEG), fallback to old JPEG path. */     private fun alignAndMergeNative(burst: List<Bitmap>): Bitmap? {         if (!StitchNative.isAvailable) return null-        val handle = StitchNative.newSession(false)-        try {-            for (f in burst) {-                val baos = java.io.ByteArrayOutputStream()-                f.compress(Bitmap.CompressFormat.JPEG, 95, baos)-                StitchNative.addFrame(handle, baos.toByteArray(), 0f, 0f, 0f)+        // First try lossless RGBA session (no double JPEG quality loss)+        tryLosslessRgba(burst)?.let { return it }+        // Fallback: old JPEG-compressed path (backwards compat)+        return try {+            val handle = StitchNative.newSession(false)+            try {+                for (f in burst) {+                    val baos = java.io.ByteArrayOutputStream()+                    f.compress(Bitmap.CompressFormat.JPEG, 95, baos)+                    StitchNative.addFrame(handle, baos.toByteArray(), 0f, 0f, 0f)+                }+                val jpeg = StitchNative.merge(handle) ?: return null+                BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size)+            } finally {+                StitchNative.free(handle)+            }+        } catch (_: Throwable) {+            null+        }+    }++    private fun tryLosslessRgba(burst: List<Bitmap>): Bitmap? {+        return try {+            val handle = StitchNative.newNightSession()+            if (handle == 0L) return null+            try {+                for (f in burst) {+                    val w = f.width+                    val h = f.height+                    if (w <= 0 || h <= 0 || w > 20000 || h > 20000) continue+                    val ints = IntArray(w * h)+                    f.getPixels(ints, 0, w, 0, 0, w, h)+                    val rgba = ByteArray(w * h * 4)+                    var j = 0+                    for (p in ints) {+                        rgba[j] = ((p shr 16) and 0xFF).toByte() // R+                        rgba[j + 1] = ((p shr 8) and 0xFF).toByte() // G+                        rgba[j + 2] = (p and 0xFF).toByte() // B+                        rgba[j + 3] = ((p ushr 24) and 0xFF).toByte() // A+                        j += 4+                    }+                    StitchNative.addNightRgbaFrame(handle, rgba, w, h)+                }+                val jpeg = StitchNative.mergeNight(handle) ?: return null+                BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size)+            } finally {+                try {+                    StitchNative.freeNight(handle)+                } catch (_: Throwable) {+                    try { StitchNative.free(handle) } catch (_: Throwable) {}+                }             }-            val jpeg = StitchNative.merge(handle) ?: return null-            return BitmapFactory.decodeByteArray(jpeg, 0, jpeg.size)-        } finally {-            StitchNative.free(handle)+        } catch (_: Throwable) {+            null         }     } -    /** Applies the night gain + shadow lift to a single 0..255 channel value. */-    private fun brighten(value: Float): Int =-        (value * NIGHT_GAIN + NIGHT_SHADOW_LIFT).roundToInt().coerceIn(0, 255)+    /**+     * Highlight-preserving brightening:+     * - Shadow lift weighted more in dark regions+     * - Gain tapers toward highlights so brights don't clip+     * - Soft knee compression above [HIGHLIGHT_COMPRESS_START]+     */+    private fun brightenChannel(value: Float): Int {+        val y = value / 255f+        val taperedGain = NIGHT_GAIN - y * (NIGHT_GAIN - 1.15f) * 0.65f+        val lifted = value * taperedGain + NIGHT_SHADOW_LIFT * (1f - y) * (1f - y * 0.3f)+        val compressed = if (lifted > HIGHLIGHT_COMPRESS_START) {+            HIGHLIGHT_COMPRESS_START + (lifted - HIGHLIGHT_COMPRESS_START) * HIGHLIGHT_COMPRESS_FACTOR+        } else lifted+        return compressed.roundToInt().coerceIn(0, 255)+    } }
camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt b/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.ktindex 5093c833ff..08f9119b46 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/StitchNative.kt@@ -35,9 +35,23 @@ object StitchNative {      */     external fun estimate(handle: Long): ByteArray? -    /** Aligns + merges the added frames (night mode); returns JPEG bytes or null. Consumes the frames. */+    /** Aligns + merges the added frames (night mode, JPEG path); returns JPEG bytes or null. Consumes the frames. */     external fun merge(handle: Long): ByteArray? -    /** Releases the session. */+    /** Releases the session (also cleans night registry if mixed). */     external fun free(handle: Long)++    // --- Lossless night path: RGBA frames without double JPEG (no quality loss) ---++    /** Opens a night session that holds RGBA frames directly (lossless). */+    external fun newNightSession(): Long++    /** Adds one RGBA frame (len = w*h*4, R,G,B,A order) to a night session. */+    external fun addNightRgbaFrame(handle: Long, rgba: ByteArray, width: Int, height: Int)++    /** Aligns + merges the RGBA night session; returns JPEG bytes or null. Consumes session. */+    external fun mergeNight(handle: Long): ByteArray?++    /** Releases a night session (also cleans pano registry if mixed). */+    external fun freeNight(handle: Long) }
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 5b7abbf1bc..ff4b8f6cd8 100644--- a/camera/src/main/res/values/strings.xml+++ b/camera/src/main/res/values/strings.xml@@ -35,6 +35,12 @@      <string name="settings_video_codec">Video codec</string>     <string name="settings_video_codec_label">Video codec</string>+    <string name="codec_avc_label">H.264 / AVC</string>+    <string name="codec_avc_description">Most compatible</string>+    <string name="codec_hevc_label">H.265 / HEVC</string>+    <string name="codec_hevc_description">More efficient</string>+    <string name="codec_av1_label">AV1</string>+    <string name="codec_av1_description">Most efficient</string>      <string name="mode_portrait">Portrait</string> @@ -53,4 +59,13 @@     <string name="ae_af_lock">AE/AF LOCK</string>     <string name="pause_recording">Pause</string>     <string name="resume_recording">Resume</string>++    <!-- Migrated hardcoded UI strings (auto) -->+    <!-- CameraScreen -->+    <string name="processing_panorama_u2026">Processing panorama\u2026</string>+    <string name="night">Night</string>++    <!-- Migrated inner Text constants v3 (auto) -->+    <!-- CameraScreen -->+    <string name="auto">Auto</string> </resources>
camera/src/main/rust/src/lib.rs
diff --git a/camera/src/main/rust/src/lib.rs b/camera/src/main/rust/src/lib.rsindex f750fa46df..d802b6815d 100644--- a/camera/src/main/rust/src/lib.rs+++ b/camera/src/main/rust/src/lib.rs@@ -33,6 +33,11 @@ fn registry() -> &'static Mutex<HashMap<i64, Session>> {     REG.get_or_init(|| Mutex::new(HashMap::new())) } +fn night_registry() -> &'static Mutex<HashMap<i64, Vec<Rgba>>> {+    static NREG: OnceLock<Mutex<HashMap<i64, Vec<Rgba>>>> = OnceLock::new();+    NREG.get_or_init(|| Mutex::new(HashMap::new()))+}+ fn next_handle() -> i64 {     static CTR: OnceLock<Mutex<i64>> = OnceLock::new();     let m = CTR.get_or_init(|| Mutex::new(1));@@ -64,19 +69,27 @@ fn do_stitch(s: &mut Session) -> Option<Vec<u8>> {     let frames = std::mem::take(&mut s.frames);     let yaw = std::mem::take(&mut s.yaw);     let pitch = std::mem::take(&mut s.pitch);-    let _ = s.sphere; // sphere vs cylindrical handled by the (planar-chain) pipeline for now+    let _ = s.sphere;     let result = stitch::stitch_panorama(&frames, &yaw, &pitch)?;     encode_jpeg(&result, 92) }  fn do_merge(s: &mut Session) -> Option<Vec<u8>> {     let frames = std::mem::take(&mut s.frames);-    // Decode the JPEG burst to RGBA for alignment + merge.     let decoded: Vec<Rgba> = frames.iter().filter_map(|j| Rgba::from_jpeg(j)).collect();     let result = night::align_and_merge(&decoded)?;     encode_jpeg(&result, 95) } +fn do_merge_night_rgba(handle: i64) -> Option<Vec<u8>> {+    let frames = night_registry().lock().unwrap().remove(&handle)?;+    if frames.is_empty() {+        return None;+    }+    let result = night::align_and_merge(&frames)?;+    encode_jpeg(&result, 95)+}+ /// Serialize an [`stitch::Estimate`] to a compact little-endian blob for the /// Kotlin GPU compositor. Layout: ///   header: canvas_w u32, canvas_h u32, u0 f64, v0 f64, scale f64, count u32@@ -104,7 +117,7 @@ fn serialize_estimate(est: &stitch::Estimate) -> Vec<u8> { }  // Registration-only path for the GPU compositor. Borrows the session (does not-// consume its frames) so a CPU-stitch fallback can still run if the GPU fails.+// consume its frames) so a CPU-stitch fallback can still run if the GPU path fails. fn do_estimate(s: &Session) -> Option<Vec<u8>> {     let est = stitch::estimate_pano(&s.frames, &s.yaw, &s.pitch)?;     Some(serialize_estimate(&est))@@ -119,9 +132,6 @@ mod tests {         std::fs::read(path).expect("read image bytes")     } -    /// Stitches the two sample photos from linrl3/Image-Stitching-OpenCV and-    /// writes the result to testdata/output.jpg for visual comparison against-    /// testdata/panorama.jpg. Run with:  cargo test stitch_two_samples -- --nocapture     #[test]     fn stitch_two_samples() {         let a = load("testdata/q11.jpg");@@ -136,9 +146,6 @@ mod tests {         let dt = t0.elapsed();         let jpeg = encode_jpeg(&out, 92).expect("encode");         std::fs::write("testdata/output.jpg", &jpeg).expect("write output");--        // Quantitatively count pure-black pixels (the uncovered-warp fill) — both-        // overall and specifically on the four borders.         let total = out.w * out.h;         let mut black = 0usize;         for i in 0..total {@@ -163,8 +170,6 @@ mod tests {             count_px(out.w - 1, y, &mut border_black);         }         let black_pct = 100.0 * black as f64 / total as f64;-        // Locate the brightest vertical streak in the sky (top 25%): per-column-        // mean brightness, find the peak column and dump values around it.         let top = out.h / 4;         let colmean: Vec<f64> = (0..out.w)             .map(|x| {@@ -182,32 +187,15 @@ mod tests {             "streak: peak col {} mean {:.0} vs avg {:.0} (+{:.0})",             peak, colmean[peak], avg, colmean[peak] - avg         );-        let y = top / 2;-        let mut line = String::new();-        for x in (peak.saturating_sub(10))..(peak + 11).min(out.w) {-            let i = (y * out.w + x) * 4;-            line.push_str(&format!("{}:{},{},{} ", x, out.px[i], out.px[i + 1], out.px[i + 2]));-        }-        eprintln!("row {y} around peak: {line}");         eprintln!(             "inputs {aw}x{ah}; stitched {}x{} in {:?} -> {} KB; black={} ({:.3}%), border_black={}",-            out.w,-            out.h,-            dt,-            jpeg.len() / 1024,-            black,-            black_pct,-            border_black+            out.w, out.h, dt, jpeg.len() / 1024, black, black_pct, border_black         );         assert!(out.w > 800 && out.h > 800, "degenerate crop: {}x{}", out.w, out.h);         assert_eq!(border_black, 0, "black pixels on the border");         assert!(black_pct < 0.05, "too many black pixels: {:.3}%", black_pct);     } -    /// Registration-only path used by the GPU compositor: decode the estimate-    /// blob and assert it yields 2 cameras with finite intrinsics/rotation and a-    /// plausible canvas size. (GLES compositing itself needs an Android EGL-    /// context, so it can't run under host `cargo test`.)     #[test]     fn estimate_two_samples() {         let a = load("testdata/q11.jpg");@@ -215,8 +203,6 @@ mod tests {         let est = crate::stitch::estimate_pano(&[a, b], &[0.0, 0.0], &[0.0, 0.0])             .expect("estimate returned None");         let blob = serialize_estimate(&est);--        // Header: canvas_w u32, canvas_h u32, u0 f64, v0 f64, scale f64, count u32.         let u32_at = |o: usize| u32::from_le_bytes(blob[o..o + 4].try_into().unwrap());         let f64_at = |o: usize| f64::from_le_bytes(blob[o..o + 8].try_into().unwrap());         let canvas_w = u32_at(0);@@ -229,8 +215,6 @@ mod tests {             canvas_w > 800 && canvas_h > 400 && (canvas_w as u64 * canvas_h as u64) < 12_000_000,             "implausible canvas {canvas_w}x{canvas_h}"         );--        // Per-cam records begin at offset 36; each is 4 + 8*12 + 4 = 104 bytes.         let rec = 4 + 8 * 12 + 4;         assert_eq!(blob.len(), 36 + count as usize * rec, "blob size mismatch");         for i in 0..count as usize {@@ -251,7 +235,7 @@ mod tests { mod jni_bindings {     use super::*;     use jni::objects::{JByteArray, JClass};-    use jni::sys::{jboolean, jbyteArray, jfloat, jlong};+    use jni::sys::{jboolean, jbyteArray, jfloat, jint, jlong};     use jni::JNIEnv;      #[no_mangle]@@ -317,9 +301,6 @@ mod jni_bindings {         handle: jlong,     ) -> jbyteArray {         let null = std::ptr::null_mut();-        // Move the session data out so the (long) registration doesn't hold the-        // registry lock, then restore it afterwards so a CPU-stitch fallback can-        // still consume the same frames if the GPU path fails.         let session = match registry().lock().unwrap().get_mut(&(handle as i64)) {             Some(s) => Session {                 sphere: s.sphere,@@ -345,6 +326,75 @@ mod jni_bindings {         }     } +    // --- Lossless night path: RGBA frames without double JPEG ---++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_newNightSession<'l>(+        _env: JNIEnv<'l>,+        _class: JClass<'l>,+    ) -> jlong {+        let h = next_handle();+        night_registry().lock().unwrap().insert(h, Vec::new());+        h+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_addNightRgbaFrame<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+        rgba: JByteArray<'l>,+        width: jint,+        height: jint,+    ) {+        let w = width as usize;+        let h = height as usize;+        if w == 0 || h == 0 || w > 20000 || h > 20000 {+            return;+        }+        let bytes = match env.convert_byte_array(&rgba) {+            Ok(b) => b,+            Err(_) => return,+        };+        if bytes.len() != w * h * 4 {+            return;+        }+        let frame = Rgba::from_bytes(w, h, bytes);+        if let Some(v) = night_registry().lock().unwrap().get_mut(&(handle as i64)) {+            v.push(frame);+        }+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_mergeNight<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+    ) -> jbyteArray {+        let null = std::ptr::null_mut();+        let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            do_merge_night_rgba(handle as i64)+        }))+        .unwrap_or(None);+        match bytes {+            Some(b) => match env.byte_array_from_slice(&b) {+                Ok(arr) => arr.into_raw(),+                Err(_) => null,+            },+            None => null,+        }+    }++    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_freeNight<'l>(+        _env: JNIEnv<'l>,+        _class: JClass<'l>,+        handle: jlong,+    ) {+        night_registry().lock().unwrap().remove(&(handle as i64));+        registry().lock().unwrap().remove(&(handle as i64));+    }+     #[no_mangle]     pub extern "system" fn Java_com_vayunmathur_camera_util_StitchNative_free<'l>(         _env: JNIEnv<'l>,@@ -352,11 +402,11 @@ mod jni_bindings {         handle: jlong,     ) {         registry().lock().unwrap().remove(&(handle as i64));+        night_registry().lock().unwrap().remove(&(handle as i64));     }      fn run_and_return(env: JNIEnv, handle: jlong, panorama: bool) -> jbyteArray {         let null = std::ptr::null_mut();-        // Pull the session out so the (potentially long) compute doesn't hold the lock.         let mut session = match registry().lock().unwrap().get_mut(&(handle as i64)) {             Some(s) => Session {                 sphere: s.sphere,@@ -366,7 +416,6 @@ mod jni_bindings {             },             None => return null,         };-        // Never let a panic unwind across the JNI/FFI boundary — return null instead.         let bytes = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {             if panorama {                 do_stitch(&mut session)@@ -384,4 +433,3 @@ mod jni_bindings {         }     } }-
camera/src/main/rust/src/night.rs
diff --git a/camera/src/main/rust/src/night.rs b/camera/src/main/rust/src/night.rsindex a87b6ddc34..d87d26b098 100644--- a/camera/src/main/rust/src/night.rs+++ b/camera/src/main/rust/src/night.rs@@ -1,22 +1,50 @@ //! Night mode: align a hand-held burst to the first frame (ORB + RANSAC-//! homography) and temporally average to reduce noise.+//! homography) and temporally average with deghosting to reduce noise.  use crate::features::{detect_and_describe, match_features}; use crate::geometry::{find_homography_ransac, Pt}; use crate::imgbuf::{to_gray, Rgba}; use nalgebra::{Matrix3, Vector3}; -const MAX_FEATURES: usize = 1200;-const FAST_THRESHOLD: i32 = 20;-const RATIO: f32 = 0.8;-const RANSAC_ITERS: usize = 400;+// Tuned for low-light: lower FAST threshold, more features, more RANSAC,+// lower min-inliers. Registration runs at reduced res for speed.+const MAX_FEATURES: usize = 2000;+const FAST_THRESHOLD: i32 = 12;+const RATIO: f32 = 0.78;+const RANSAC_ITERS: usize = 500; const RANSAC_THRESH: f32 = 3.0;-const MIN_INLIERS: usize = 20;+const MIN_INLIERS: usize = 12;+const REG_MAX_MP: f64 = 0.8; // registration resolution+const GHOST_THRESH_SUM: i32 = 110; // sum |Rdiff|+|Gdiff|+|Bdiff| above -> ghost, skip  #[inline] fn apply(h: &Matrix3<f64>, x: f64, y: f64) -> (f64, f64) {     let v = h * Vector3::new(x, y, 1.0);-    if v.z.abs() < 1e-12 { (v.x, v.y) } else { (v.x / v.z, v.y / v.z) }+    if v.z.abs() < 1e-12 {+        (v.x, v.y)+    } else {+        (v.x / v.z, v.y / v.z)+    }+}++/// Scale a homography estimated at reg_scale to full resolution:+/// H_full = S^-1 * H_small * S  where S=diag(s,s,1)+fn scale_homography(h: &Matrix3<f64>, s: f64) -> Matrix3<f64> {+    if (s - 1.0).abs() < 1e-6 {+        return *h;+    }+    // Derived: [[h00, h01, h02/s], [h10, h11, h12/s], [h20*s, h21*s, h22]]+    Matrix3::new(+        h[(0, 0)],+        h[(0, 1)],+        h[(0, 2)] / s,+        h[(1, 0)],+        h[(1, 1)],+        h[(1, 2)] / s,+        h[(2, 0)] * s,+        h[(2, 1)] * s,+        h[(2, 2)],+    ) }  pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> {@@ -30,36 +58,80 @@ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> {     let reff = &frames[0];     let w = reff.w;     let h = reff.h;-    let ref_feat = detect_and_describe(&to_gray(reff), MAX_FEATURES, FAST_THRESHOLD);+    if w == 0 || h == 0 {+        return None;+    }++    // Registration scale: downscale large frames for feature detection.+    let area = w as f64 * h as f64;+    let reg_scale = (REG_MAX_MP * 1e6 / area).sqrt().min(1.0);+    let (ref_small, ref_s) = if reg_scale < 0.999 {+        let rw = ((w as f64 * reg_scale).round() as usize).max(1);+        let rh = ((h as f64 * reg_scale).round() as usize).max(1);+        (reff.resized(rw, rh), reg_scale)+    } else {+        (reff.clone(), 1.0)+    };+    let ref_feat = detect_and_describe(&to_gray(&ref_small), MAX_FEATURES, FAST_THRESHOLD);      let mut acc = vec![0f32; w * h * 3];     let mut cnt = vec![0f32; w * h]; -    for (i, f) in frames.iter().enumerate() {-        // homography mapping this frame -> reference-        let h_to_ref = if i == 0 {-            Matrix3::identity()-        } else {-            let feat = detect_and_describe(&to_gray(f), MAX_FEATURES, FAST_THRESHOLD);-            let matches = match_features(&feat, &ref_feat, RATIO);-            if matches.len() < MIN_INLIERS {-                continue; // too different; skip rather than ghost-            }-            let a: Vec<Pt> = matches.iter().map(|&(ia, _)| (feat.kps[ia].x, feat.kps[ia].y)).collect();-            let b: Vec<Pt> = matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect();-            match find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH) {-                Some((hm, inl)) if inl >= MIN_INLIERS => hm,-                _ => continue,+    // Reference pixels always contribute.+    for yy in 0..h {+        for xx in 0..w {+            let rc = reff.get(xx, yy);+            let idx = yy * w + xx;+            acc[idx * 3] = rc[0] as f32;+            acc[idx * 3 + 1] = rc[1] as f32;+            acc[idx * 3 + 2] = rc[2] as f32;+            cnt[idx] = 1.0;+        }+    }++    for (i, f) in frames.iter().enumerate().skip(1) {+        // Feature detection at reduced resolution.+        let (cur_small, s) = if ref_s < 0.999 {+            let rw = ((f.w as f64 * ref_s).round() as usize).max(1);+            let rh = ((f.h as f64 * ref_s).round() as usize).max(1);+            // Guard dimension mismatch (should match reg scale but keep safe)+            if rw * rh == 0 {+                (f.clone(), 1.0)+            } else {+                (f.resized(rw, rh), ref_s)             }+        } else {+            (f.clone(), 1.0)+        };+        let feat = detect_and_describe(&to_gray(&cur_small), MAX_FEATURES, FAST_THRESHOLD);+        let matches = match_features(&feat, &ref_feat, RATIO);+        if matches.len() < MIN_INLIERS {+            continue;+        }+        let a: Vec<Pt> = matches.iter().map(|&(ia, _)| (feat.kps[ia].x, feat.kps[ia].y)).collect();+        let b: Vec<Pt> = matches.iter().map(|&(_, ib)| (ref_feat.kps[ib].x, ref_feat.kps[ib].y)).collect();+        let h_small = match find_homography_ransac(&a, &b, RANSAC_ITERS, RANSAC_THRESH) {+            Some((hm, inl)) if inl >= MIN_INLIERS => hm,+            _ => continue,         };+        let h_to_ref = scale_homography(&h_small, s);         let h_inv = match h_to_ref.try_inverse() {             Some(m) => m,             None => continue,         };+        // Warp and accumulate with deghosting against reference.         for y in 0..h {             for x in 0..w {                 let (sx, sy) = apply(&h_inv, x as f64, y as f64);                 if let Some(c) = f.sample(sx as f32, sy as f32) {+                    // Deghost: skip samples far from reference to avoid moving-object ghosts.+                    let rp = reff.get(x, y);+                    let diff = (c[0] as i32 - rp[0] as i32).abs()+                        + (c[1] as i32 - rp[1] as i32).abs()+                        + (c[2] as i32 - rp[2] as i32).abs();+                    if diff > GHOST_THRESH_SUM {+                        continue;+                    }                     let idx = y * w + x;                     acc[idx * 3] += c[0];                     acc[idx * 3 + 1] += c[1];@@ -80,7 +152,6 @@ pub fn align_and_merge(frames: &[Rgba]) -> Option<Rgba> {             out.px[d + 2] = (acc[i * 3 + 2] / c).round().clamp(0.0, 255.0) as u8;             out.px[d + 3] = 255;         } else {-            // fall back to the reference pixel if nothing aligned here             let rc = reff.get(i % w, i / w);             out.px[d] = rc[0];             out.px[d + 1] = rc[1];
clock/src/main/java/com/vayunmathur/clock/ui/AlarmActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmActivity.kt b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmActivity.ktindex 0e2d025c81..3c6fdad260 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmActivity.kt@@ -158,7 +158,7 @@ fun AlarmRingingScreen(                     style = MaterialTheme.typography.displayLarge.copy(                         fontSize = 80.sp,                         fontWeight = FontWeight.Black,-                        // Tighten letter spacing for that "Clock" look+                        // Tighten letter spacing for that stringResource(R.string.label_clock) look                         letterSpacing = (-2).sp                     ),                     color = MaterialTheme.colorScheme.onPrimaryContainer
clock/src/main/java/com/vayunmathur/clock/ui/AlarmSettingsPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmSettingsPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmSettingsPage.ktindex b7b1f0f1a8..5ec497a328 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmSettingsPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmSettingsPage.kt@@ -34,12 +34,14 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.net.toUri import com.vayunmathur.clock.Route+import com.vayunmathur.clock.R import com.vayunmathur.clock.util.ClockViewModel import com.vayunmathur.clock.util.RINGTONE_SILENT import com.vayunmathur.library.ui.IconBack import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.NavBackStack import kotlinx.coroutines.launch+import androidx.compose.ui.res.stringResource  /** Snooze length choices, in minutes. */ val SNOOZE_OPTIONS = listOf(1, 5, 10, 15, 20, 30)@@ -47,15 +49,15 @@ val SNOOZE_OPTIONS = listOf(1, 5, 10, 15, 20, 30) /** Gradually-increase-volume choices, in seconds (0 = off). */ val GRADUAL_OPTIONS = listOf(0, 5, 15, 30, 60) -fun gradualLabel(seconds: Int): String = if (seconds <= 0) "Off" else "${seconds}s"+fun gradualLabel(context: android.content.Context, seconds: Int): String = if (seconds <= 0) context.getString(R.string.gradual_off) else "${seconds}s"  /** Human-readable name for a stored ringtone value (null = default, [RINGTONE_SILENT] = silent). */ fun ringtoneTitle(context: android.content.Context, uriString: String?): String = when (uriString) {-    null -> "Default"-    RINGTONE_SILENT -> "Silent"+    null -> context.getString(R.string.ringtone_default)+    RINGTONE_SILENT -> context.getString(R.string.ringtone_silent)     

Diff truncated.