Modern Apps git

← Modern-Apps.git

various fixes

Commit
66a4eacf41fd37a093f0113c4486edc6a9e13982
Author
Vayun Mathur <[email protected]>
When
2026-07-31 17:43 UTC (4 months ago)
Parents
4a0cbf6

Diff

Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 1d23325102..e6b0c6a787 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1721,6 +1721,20 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" +[[package]]+name = "whatsapp_signal"+version = "0.1.0"+dependencies = [+ "aes 0.8.4",+ "curve25519-dalek",+ "hmac 0.12.1",+ "jni",+ "rand_core 0.6.4",+ "sha2 0.10.9",+ "subtle",+ "x25519-dalek",+]+ [[package]] name = "windows-core" version = "0.62.2"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 1570594e66..dee857e0c5 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -10,6 +10,7 @@ members = [   "passwords/src/main/rust",   "vpn/src/main/rust",   "library/e2ee-p2p/src/main/rust",+  "messages/src/main/rust",   "third_party/om-file-format-sys", ] resolver = "2"@@ -44,6 +45,11 @@ sha2 = { version = "0.10.9", features = ["oid"] } aes = "0.8.4" md-5 = "0.10.6" keepass = { version = "0.13.17", default-features = false, features = ["save_kdbx4"] }+# Classic Signal protocol (WhatsApp bridge) – X25519/XEdDSA + AES-CBC + HMAC.+curve25519-dalek = { version = "4.1.3", default-features = false, features = ["alloc", "precomputed-tables", "zeroize"] }+x25519-dalek = { version = "2.0.1", default-features = false, features = ["static_secrets"] }+hmac = "0.12.1"+subtle = "2.6.1" fips203 = "0.4.3" fips204 = "0.4.6" rand_core = { version = "0.6.4", features = ["getrandom"] }
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex d962d9bbda..46d0d615e4 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -55,7 +55,7 @@ Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `conta - **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 ✅).+- **Version drift**: `okhttp 4.12.0` (2y old, 5.x exists) ⚠️ still pinned. `ktor` fully removed (`:messages` migrated to `:library:network` ✅) 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`. Rust versions unified in root `/Cargo.toml` (workspace resolver 2, mirrors Gradle catalog) – see `/scripts/rust-deps-count.sh`.@@ -130,7 +130,7 @@ Summed old per-crate locks (before workspace) = 712 total (641 excluding voxels)  ### 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.+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`, `okhttp 4.12.0` + `okio 3.17.0`, `kotlin 2.4.0` + `coroutines 1.11.0` + `serialization-json 1.11.0` + `datetime 0.8.0`, `ksp 2.3.10`, `protobuf 4.36.0-RC1` / `protobuf-javalite 4.35.0`, `libphonenumber 9.0.34`, `fhir-model 1.0.0-beta02`, `health/connect-client 1.2.0-alpha04`, etc.  --- 
appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex 14e620bf10..5a7ff480e4 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -18,10 +18,12 @@ dependencies {     implementRoom(libs)     implementation(project(":library:room"))     implementation(project(":library:network"))+    implementation(project(":library:work"))     implementation(libs.androidx.datastore.preferences)     implementation(libs.coil.compose)     implementation(libs.coil.svg)     implementation(libs.jsoup)     implementation(libs.okhttp)     implementation(libs.kotlinx.serialization.json)+    implementation(libs.auroraoss.gplayapi) }
appstore/src/main/AndroidManifest.xml
diff --git a/appstore/src/main/AndroidManifest.xml b/appstore/src/main/AndroidManifest.xmlindex 1148a508ac..355fcb1ecb 100644--- a/appstore/src/main/AndroidManifest.xml+++ b/appstore/src/main/AndroidManifest.xml@@ -5,6 +5,7 @@     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />+    <uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />     <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"         tools:ignore="QueryAllPackagesPermission" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />@@ -54,5 +55,13 @@             android:foregroundServiceType="dataSync"             tools:node="merge" /> +        <receiver+            android:name=".data.installer.InstallStatusReceiver"+            android:exported="false">+            <intent-filter>+                <action android:name="com.vayunmathur.appstore.INSTALL_STATUS" />+            </intent-filter>+        </receiver>+     </application> </manifest>
appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.ktindex 6f2897ead7..4310b3e7ac 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -1,13 +1,10 @@ package com.vayunmathur.appstore.data -import kotlinx.serialization.Serializable- enum class AppSource {     FDROID,     PLAYSTORE } -@Serializable data class UnifiedApp(     val packageName: String,     val source: AppSource,@@ -22,8 +19,6 @@ data class UnifiedApp(     val sizeBytes: Long = 0L,     val apkUrl: String? = null,     val targetSdk: Int? = null,-    val screenshotUrls: List<String> = emptyList(),-    val rating: Float? = null,     val license: String? = null,     val website: String? = null,     val sourceCode: String? = null,@@ -31,8 +26,11 @@ data class UnifiedApp(     val addedTimestamp: Long = 0L,     val lastUpdated: Long = 0L,     val antiFeatures: List<String> = emptyList(),-    val isFree: Boolean = true,-    val repoUrl: String? = null+    val repoUrl: String? = null,+    val offerType: Int = 0,+    val rating: Float? = null,+    val containsSplit: Boolean = false,+    val isFree: Boolean = true )  data class InstalledInfo(@@ -40,7 +38,7 @@ data class InstalledInfo(     val name: String,     val versionName: String?,     val versionCode: Long,-    val isSystem: Boolean = false+    val enabled: Boolean = true )  object DefaultRepos {@@ -48,11 +46,3 @@ object DefaultRepos {     const val FDROID_ARCHIVE = "https://f-droid.org/archive"     const val IZVYZID = "https://apt.izzysoft.de/fdroid/repo" }--@Serializable-data class RepoInfo(-    val url: String,-    val name: String,-    val enabled: Boolean = true,-    val fingerprint: String? = null-)
appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.ktindex 4705b3b983..6e99f29cf4 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppProvider.kt@@ -1,34 +1,40 @@ package com.vayunmathur.appstore.data  /**- * Generic app store source — F-Droid (Droid-ify style) or Play Store (Aurora style).- * The app registers 2 providers in order: fdroid base repo + play store.- * [isPresent] is used for installed filtering: check F-Droid first, then Play,- * if none — hide from installed list.+ * Generic abstraction for any app provider (F-Droid base repo, Play Store via Aurora anonymous).+ * App registers 2 providers in order: fdroid base repo + play store.+ * Installed presence check: F-Droid first -> Play Store -> if none, hide app from list.  */ interface AppProvider {     val id: String     val name: String     val source: AppSource -    /** All apps available from this provider (browse / sync). Must filter targetSdk < 35. */+    /** Full catalog — must pre-filter targetSdk < MIN_TARGET_SDK. */     suspend fun fetchAll(): List<UnifiedApp>      /** Search within this provider. */     suspend fun search(query: String): List<UnifiedApp> -    /** Presence check for installed filtering: true if package exists in this store. */+    /** Presence check for installed filtering. */     suspend fun isPresent(packageName: String): Boolean -    /** Detailed listing for a package, or null. */+    /** Detailed entry or null. */     suspend fun getDetails(packageName: String): UnifiedApp?      companion object {         const val MIN_TARGET_SDK = 35 -        /** Keep only apps targeting >= MIN_TARGET_SDK, or unknown targetSdk (can't verify). */         fun filterTargetSdk(apps: List<UnifiedApp>): List<UnifiedApp> {             return apps.filter { app -> app.targetSdk == null || app.targetSdk >= MIN_TARGET_SDK }         }++        /** Resolve source for a package using ordered providers: fdroid first, then play. Returns null if absent in all. */+        suspend fun resolveSource(packageName: String, providers: List<AppProvider>): AppSource? {+            for (provider in providers) {+                if (provider.isPresent(packageName)) return provider.source+            }+            return null+        }     } }
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.ktindex 185aa71247..274bf78066 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt@@ -1,10 +1,12 @@ package com.vayunmathur.appstore.data +import android.content.Context import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext  class FDroidAppProvider(-    private val db: AppDatabase+    private val db: AppDatabase,+    private val appContext: Context ) : AppProvider {     override val id = "fdroid"     override val name = "F-Droid"@@ -16,7 +18,7 @@ class FDroidAppProvider(         val repos = db.repoDao().all().filter { it.enabled }         val all = mutableListOf<UnifiedApp>()         for (repo in repos) {-            try { all += FDroidRepository.fetchRepoIndex(repo.url) } catch (_: Exception) { }+            try { all += FDroidRepository.fetchRepoIndex(appContext, repo.url) } catch (_: Exception) { }         }         val filtered = AppProvider.filterTargetSdk(all).distinctBy { it.packageName }         cachedPackageNames = filtered.map { it.packageName }.toSet()@@ -29,7 +31,7 @@ class FDroidAppProvider(         val live = mutableListOf<UnifiedApp>()         for (url in listOf(DefaultRepos.FDROID_MAIN, DefaultRepos.IZVYZID)) {             try {-                live += FDroidRepository.fetchRepoIndex(url).filter {+                live += FDroidRepository.fetchRepoIndex(appContext, url).filter {                     it.name.lowercase().contains(q) || it.packageName.lowercase().contains(q) || it.summary.lowercase().contains(q)                 }             } catch (_: Exception) {}@@ -54,12 +56,13 @@ class FDroidAppProvider(         } catch (_: Exception) { null }     } -    suspend fun syncIntoDb(): Int = withContext(Dispatchers.IO) {+    suspend fun syncIntoDb(context: Context? = null): Int = withContext(Dispatchers.IO) {+        val ctx = context ?: appContext         val repos = db.repoDao().all().filter { it.enabled }         var total = 0         for (repo in repos) {             try {-                val apps = FDroidRepository.fetchRepoIndex(repo.url)+                val apps = FDroidRepository.fetchRepoIndex(ctx, repo.url)                 val filtered = AppProvider.filterTargetSdk(apps)                 val entities = filtered.map { it.toEntity() }                 db.cachedAppDao().deleteByRepo(repo.url.trimEnd('/'))
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.ktindex 6d590c9c19..09bfb51dd1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -1,189 +1,549 @@ package com.vayunmathur.appstore.data +import android.content.Context+import android.util.JsonReader+import android.util.JsonToken import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.jsonArray-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive-import kotlinx.serialization.json.longOrNull+import java.io.File+import java.io.FileReader import java.net.HttpURLConnection import java.net.URL  /**- * F-Droid index v2 client — Droid-ify style. Fetches index-v2.json then v1.- * Filters targetSdk < AppProvider.MIN_TARGET_SDK when manifest provides it.+ * Fixed F-Droid repo client — avoids OOM on 99MB index-v2.json.+ * Downloads to file first (buffered), then streaming-parses with android.util.JsonReader+ * so we never hold the full String + JsonObject tree in memory.+ * Filters targetSdk < AppProvider.MIN_TARGET_SDK.  */ object FDroidRepository { -    private val json = Json { ignoreUnknownKeys = true; isLenient = true }--    suspend fun fetchRepoIndex(repoUrl: String): List<UnifiedApp> = withContext(Dispatchers.IO) {+    suspend fun fetchRepoIndex(context: Context, repoUrl: String): List<UnifiedApp> = withContext(Dispatchers.IO) {         val base = repoUrl.trimEnd('/')-        val urls = listOf("$base/index-v2.json", "$base/index-v1.json")+        val cacheFile = File(context.cacheDir, "fdroid_${base.hashCode()}_index.json")+        val candidates = listOf("$base/index-v2.json", "$base/index-v1.json")         var lastErr: Exception? = null-        for (url in urls) {+        for (url in candidates) {             try {-                val apps = if (url.endsWith("v2.json")) fetchV2(url, base) else fetchV1(url, base)-                // Filter targetSdk < 35 for both sources requirement-                return@withContext AppProvider.filterTargetSdk(apps)+                downloadToFile(url, cacheFile)+                val apps = if (url.endsWith("v2.json")) parseV2Streaming(cacheFile, base) else parseV1Streaming(cacheFile, base)+                val filtered = AppProvider.filterTargetSdk(apps)+                cacheFile.delete()+                return@withContext filtered             } catch (e: Exception) {                 lastErr = e             }         }+        cacheFile.delete()         throw lastErr ?: RuntimeException("Failed to fetch $repoUrl")     } -    private fun fetchV2(url: String, repoBase: String): List<UnifiedApp> {+    suspend fun fetchRepoIndex(repoUrl: String): List<UnifiedApp> = withContext(Dispatchers.IO) {+        val base = repoUrl.trimEnd('/')+        val temp = File.createTempFile("fdroid_index_", ".json")+        try {+            val candidates = listOf("$base/index-v2.json", "$base/index-v1.json")+            var lastErr: Exception? = null+            for (url in candidates) {+                try {+                    downloadToFile(url, temp)+                    val apps = if (url.endsWith("v2.json")) parseV2Streaming(temp, base) else parseV1Streaming(temp, base)+                    return@withContext AppProvider.filterTargetSdk(apps)+                } catch (e: Exception) {+                    lastErr = e+                }+            }+            throw lastErr ?: RuntimeException("Failed to fetch $repoUrl")+        } finally {+            temp.delete()+        }+    }++    private fun downloadToFile(url: String, outFile: File) {         val conn = (URL(url).openConnection() as HttpURLConnection).apply {-            connectTimeout = 20000-            readTimeout = 60000+            connectTimeout = 30000+            readTimeout = 120000             setRequestProperty("Accept", "application/json")             setRequestProperty("User-Agent", "ModernAppStore/1.0")+            instanceFollowRedirects = true         }-        val text = conn.inputStream.bufferedReader().readText()-        val root = json.parseToJsonElement(text).jsonObject-        val packages = root["packages"]?.jsonObject ?: return emptyList()-        val result = mutableListOf<UnifiedApp>()+        if (conn.responseCode !in 200..299) throw java.io.IOException("HTTP ${conn.responseCode} for $url")+        conn.inputStream.use { input ->+            outFile.outputStream().use { out ->+                val buf = ByteArray(32 * 1024)+                var n: Int+                while (input.read(buf).also { n = it } != -1) out.write(buf, 0, n)+            }+        }+    } -        for ((pkg, pkgEl) in packages) {-            try {-                val pkgObj = pkgEl.jsonObject-                val meta = pkgObj["metadata"]?.jsonObject ?: continue-                val versions = pkgObj["versions"]?.jsonObject ?: continue-                if (versions.isEmpty()) continue--                val latestEntry = versions.values.mapNotNull { it.jsonObject }-                    .maxByOrNull { it["added"]?.jsonPrimitive?.longOrNull ?: 0L } ?: continue--                val fileObj = latestEntry["file"]?.jsonObject-                val manifest = latestEntry["manifest"]?.jsonObject-                val usesSdk = manifest?.get("usesSdk")?.jsonObject--                val name = extractLocalized(meta["name"]) ?: pkg.substringAfterLast('.')-                val summary = extractLocalized(meta["summary"]) ?: ""-                val desc = extractLocalized(meta["description"]) ?: ""-                val author = meta["authorName"]?.jsonPrimitive?.contentOrNull-                val cats = meta["categories"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull } ?: emptyList()-                val versionName = manifest?.get("versionName")?.jsonPrimitive?.contentOrNull-                val versionCode = manifest?.get("versionCode")?.jsonPrimitive?.longOrNull ?: 0L-                val sizeBytes = fileObj?.get("size")?.jsonPrimitive?.longOrNull ?: 0L-                val apkName = fileObj?.get("name")?.jsonPrimitive?.contentOrNull-                val apkUrl = if (apkName != null) "$repoBase/$apkName" else null-                val website = meta["webSite"]?.jsonPrimitive?.contentOrNull-                val source = meta["sourceCode"]?.jsonPrimitive?.contentOrNull-                val license = meta["license"]?.jsonPrimitive?.contentOrNull-                val whatsNew = extractLocalized(latestEntry["whatsNew"])-                val added = meta["added"]?.jsonPrimitive?.longOrNull ?: 0L-                val lastUpdated = meta["lastUpdated"]?.jsonPrimitive?.longOrNull ?: added-                val targetSdk = usesSdk?.get("targetSdkVersion")?.jsonPrimitive?.contentOrNull?.toIntOrNull()--                val iconName = runCatching {-                    meta["icon"]?.jsonObject?.values?.firstOrNull()-                        ?.jsonObject?.values?.firstOrNull()-                        ?.jsonObject?.get("name")?.jsonPrimitive?.contentOrNull-                }.getOrNull()-                val iconUrl = iconName?.let { "$repoBase/icons/$it" }--                result += UnifiedApp(-                    packageName = pkg,-                    source = AppSource.FDROID,-                    name = name,-                    summary = summary,-                    description = desc,-                    iconUrl = iconUrl,-                    author = author,-                    categories = cats,-                    versionName = versionName,-                    versionCode = versionCode,-                    sizeBytes = sizeBytes,-                    apkUrl = apkUrl,-                    targetSdk = targetSdk,-                    license = license,-                    website = website,-                    sourceCode = source,-                    whatsNew = whatsNew,-                    addedTimestamp = added,-                    lastUpdated = lastUpdated,-                    repoUrl = repoBase-                )-            } catch (_: Exception) { }+    // ---- Streaming V2 parser ----++    private fun parseV2Streaming(file: File, repoBase: String): List<UnifiedApp> {+        val result = mutableListOf<UnifiedApp>()+        JsonReader(FileReader(file)).use { r ->+            r.isLenient = true+            r.beginObject()+            while (r.hasNext()) {+                when (r.nextName()) {+                    "packages" -> {+                        r.beginObject()+                        while (r.hasNext()) {+                            val pkg = r.nextName()+                            try {+                                val app = parsePackageV2(r, pkg, repoBase)+                                if (app != null) result.add(app)+                            } catch (_: Exception) {+                                try { r.skipValue() } catch (_: Exception) {}+                            }+                        }+                        r.endObject()+                    }+                    else -> r.skipValue()+                }+            }+            r.endObject()         }         return result     } -    private fun fetchV1(url: String, repoBase: String): List<UnifiedApp> {-        val conn = (URL(url).openConnection() as HttpURLConnection).apply {-            connectTimeout = 20000-            readTimeout = 60000-            setRequestProperty("User-Agent", "ModernAppStore/1.0")+    private fun parsePackageV2(reader: JsonReader, packageName: String, repoBase: String): UnifiedApp? {+        // reader at BEGIN_OBJECT of package+        var metaName: String? = null+        var metaSummary: String? = null+        var metaDesc: String? = null+        var author: String? = null+        var categories: List<String> = emptyList()+        var website: String? = null+        var sourceCode: String? = null+        var license: String? = null+        var added: Long = 0L+        var lastUpdated: Long = 0L+        var iconUrl: String? = null+        var latestAdded: Long = -1L+        var latestFileName: String? = null+        var latestSize: Long = 0L+        var latestVersionName: String? = null+        var latestVersionCode: Long = 0L+        var latestTargetSdk: Int? = null+        var latestWhatsNew: String? = null++        reader.beginObject()+        while (reader.hasNext()) {+            when (reader.nextName()) {+                "metadata" -> {+                    reader.beginObject()+                    while (reader.hasNext()) {+                        when (val mk = reader.nextName()) {+                            "name" -> metaName = readLocalizedString(reader)+                            "summary" -> metaSummary = readLocalizedString(reader)+                            "description" -> metaDesc = readLocalizedString(reader)+                            "authorName" -> author = nextStringOrNull(reader)+                            "categories" -> categories = readStringArray(reader)+                            "webSite" -> website = nextStringOrNull(reader)+                            "sourceCode" -> sourceCode = nextStringOrNull(reader)+                            "license" -> license = nextStringOrNull(reader)+                            "added" -> added = nextLongOrNull(reader) ?: 0L+                            "lastUpdated" -> lastUpdated = nextLongOrNull(reader) ?: 0L+                            "icon" -> {+                                val iconName = readIconName(reader)+                                if (iconName != null) iconUrl = "$repoBase/icons/$iconName"+                            }+                            else -> reader.skipValue()+                        }+                    }+                    reader.endObject()+                }+                "versions" -> {+                    reader.beginObject()+                    while (reader.hasNext()) {+                        reader.nextName() // version key+                        try {+                            reader.beginObject()+                            var vAdded: Long = 0L+                            var vFileName: String? = null+                            var vFileSize: Long = 0L+                            var vVersionName: String? = null+                            var vVersionCode: Long = 0L+                            var vTargetSdk: Int? = null+                            var vWhatsNew: String? = null+                            while (reader.hasNext()) {+                                when (reader.nextName()) {+                                    "added" -> vAdded = nextLongOrNull(reader) ?: 0L+                                    "file" -> {+                                        reader.beginObject()+                                        while (reader.hasNext()) {+                                            when (reader.nextName()) {+                                                "name" -> vFileName = nextStringOrNull(reader)+                                                "size" -> vFileSize = nextLongOrNull(reader) ?: 0L+                                                else -> reader.skipValue()+                                            }+                                        }+                                        reader.endObject()+                                    }+                                    "manifest" -> {+                                        reader.beginObject()+                                        while (reader.hasNext()) {+                                            when (reader.nextName()) {+                                                "versionName" -> vVersionName = nextStringOrNull(reader)+                                                "versionCode" -> vVersionCode = nextLongOrNull(reader) ?: 0L+                                                "usesSdk" -> {+                                                    reader.beginObject()+                                                    while (reader.hasNext()) {+                                                        when (reader.nextName()) {+                                                            "targetSdkVersion" -> vTargetSdk = nextIntOrNull(reader)+                                                            else -> reader.skipValue()+                                                        }+                                                    }+                                                    reader.endObject()+                                                }+                                                else -> reader.skipValue()+                                            }+                                        }+                                        reader.endObject()+                                    }+                                    "whatsNew" -> vWhatsNew = readLocalizedString(reader)+                                    else -> reader.skipValue()+                                }+                            }+                            reader.endObject()+                            if (vAdded >= latestAdded) {+                                latestAdded = vAdded+                                latestFileName = vFileName+                                latestSize = vFileSize+                                latestVersionName = vVersionName+                                latestVersionCode = vVersionCode+                                latestTargetSdk = vTargetSdk+                                latestWhatsNew = vWhatsNew+                            }+                        } catch (_: Exception) {+                            try { reader.endObject() } catch (_: Exception) {}+                        }+                    }+                    reader.endObject()+                }+                else -> reader.skipValue()+            }+        }+        reader.endObject()++        val apkUrl = latestFileName?.let { "$repoBase/$it" }+        return UnifiedApp(+            packageName = packageName,+            source = AppSource.FDROID,+            name = metaName ?: packageName.substringAfterLast('.'),+            summary = metaSummary ?: "",+            description = metaDesc ?: "",+            iconUrl = iconUrl,+            author = author,+            categories = categories,+            versionName = latestVersionName,+            versionCode = latestVersionCode,+            sizeBytes = latestSize,+            apkUrl = apkUrl,+            targetSdk = latestTargetSdk,+            license = license,+            website = website,+            sourceCode = sourceCode,+            whatsNew = latestWhatsNew,+            addedTimestamp = added,+            lastUpdated = if (lastUpdated != 0L) lastUpdated else added,+            repoUrl = repoBase+        )+    }++    // ---- Streaming V1 parser (apps[] + packages{ pkg:[...] }) ----++    private fun parseV1Streaming(file: File, repoBase: String): List<UnifiedApp> {+        val appsMeta = mutableMapOf<String, V1AppMeta>()+        val packagesMap = mutableMapOf<String, V1PackageLatest>()+        JsonReader(FileReader(file)).use { r ->+            r.isLenient = true+            r.beginObject()+            while (r.hasNext()) {+                when (r.nextName()) {+                    "apps" -> {+                        r.beginArray()+                        while (r.hasNext()) {+                            try {+                                val meta = parseV1AppMeta(r)+                                if (meta != null) appsMeta[meta.packageName] = meta+                            } catch (_: Exception) {+                                try { r.skipValue() } catch (_: Exception) {}+                            }+                        }+                        r.endArray()+                    }+                    "packages" -> {+                        r.beginObject()+                        while (r.hasNext()) {+                            val pkgName = r.nextName()+                            try {+                                val latest = parseV1PackagesArray(r)+                                if (latest != null) packagesMap[pkgName] = latest+                            } catch (_: Exception) {+                                try { r.skipValue() } catch (_: Exception) {}+                            }+                        }+                        r.endObject()+                    }+                    else -> r.skipValue()+                }+            }+            r.endObject()         }-        val text = conn.inputStream.bufferedReader().readText()-        val root = json.parseToJsonElement(text).jsonObject-        val apps = root["apps"]?.jsonArray ?: return emptyList()-        val packages = root["packages"]?.jsonObject          val result = mutableListOf<UnifiedApp>()-        for (el in apps) {-            try {-                val obj = el.jsonObject-                val pkg = obj["packageName"]?.jsonPrimitive?.contentOrNull ?: continue-                val name = obj["name"]?.jsonPrimitive?.contentOrNull ?: pkg-                val summary = obj["summary"]?.jsonPrimitive?.contentOrNull ?: ""-                val desc = obj["description"]?.jsonPrimitive?.contentOrNull ?: ""-                val author = obj["authorName"]?.jsonPrimitive?.contentOrNull-                val cats = obj["categories"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull } ?: emptyList()-                val website = obj["webSite"]?.jsonPrimitive?.contentOrNull-                val src = obj["sourceCode"]?.jsonPrimitive?.contentOrNull-                val license = obj["license"]?.jsonPrimitive?.contentOrNull-                val added = obj["added"]?.jsonPrimitive?.longOrNull ?: 0L-                val lastUpdated = obj["lastUpdated"]?.jsonPrimitive?.longOrNull ?: added-                val iconName = obj["icon"]?.jsonPrimitive?.contentOrNull-                val iconUrl = iconName?.let { "$repoBase/icons/$it" }--                val versions = packages?.get(pkg)?.jsonArray-                val latestVer = versions?.lastOrNull()?.jsonObject-                val apkName = latestVer?.get("apkName")?.jsonPrimitive?.contentOrNull-                val apkUrl = apkName?.let { "$repoBase/$it" }-                val vName = latestVer?.get("versionName")?.jsonPrimitive?.contentOrNull-                val vCode = latestVer?.get("versionCode")?.jsonPrimitive?.longOrNull ?: 0L-                val size = latestVer?.get("size")?.jsonPrimitive?.longOrNull ?: 0L-                val targetSdk = latestVer?.get("targetSdkVersion")?.jsonPrimitive?.contentOrNull?.toIntOrNull()--                result += UnifiedApp(+        for ((pkg, meta) in appsMeta) {+            val latest = packagesMap[pkg]+            result.add(+                UnifiedApp(                     packageName = pkg,                     source = AppSource.FDROID,-                    name = name,-                    summary = summary,-                    description = desc,-                    iconUrl = iconUrl,-                    author = author,-                    categories = cats,-                    versionName = vName,-                    versionCode = vCode,-                    sizeBytes = size,-                    apkUrl = apkUrl,-                    targetSdk = targetSdk,-                    website = website,-                    sourceCode = src,-                    license = license,-                    addedTimestamp = added,-                    lastUpdated = lastUpdated,+                    name = meta.name ?: pkg.substringAfterLast('.'),+                    summary = meta.summary ?: "",+                    description = meta.description ?: "",+                    iconUrl = meta.icon?.let { "$repoBase/icons/$it" },+                    author = meta.authorName,+                    categories = meta.categories,+                    versionName = latest?.versionName,+                    versionCode = latest?.versionCode ?: 0L,+                    sizeBytes = latest?.size ?: 0L,+                    apkUrl = latest?.apkName?.let { "$repoBase/$it" },+                    targetSdk = latest?.targetSdk,+                    website = meta.webSite,+                    sourceCode = meta.sourceCode,+                    license = meta.license,+                    addedTimestamp = meta.added,+                    lastUpdated = meta.lastUpdated,                     repoUrl = repoBase                 )-            } catch (_: Exception) { }+            )         }         return result     } -    private fun extractLocalized(elem: kotlinx.serialization.json.JsonElement?): String? {-        if (elem == null) return null-        if (elem is kotlinx.serialization.json.JsonPrimitive) return elem.contentOrNull-        val obj = elem as? JsonObject ?: return null-        return obj["en-US"]?.jsonPrimitive?.contentOrNull-            ?: obj["en"]?.jsonPrimitive?.contentOrNull-            ?: obj.values.firstOrNull()?.jsonPrimitive?.contentOrNull+    private data class V1AppMeta(+        val packageName: String,+        val name: String?,+        val summary: String?,+        val description: String?,+        val icon: String?,+        val authorName: String?,+        val categories: List<String>,+        val webSite: String?,+        val sourceCode: String?,+        val license: String?,+        val added: Long,+        val lastUpdated: Long+    )++    private data class V1PackageLatest(+        val apkName: String?,+        val versionName: String?,+        val versionCode: Long,+        val size: Long,+        val targetSdk: Int?+    )++    private fun parseV1AppMeta(reader: JsonReader): V1AppMeta? {+        var packageName: String? = null+        var name: String? = null+        var summary: String? = null+        var description: String? = null+        var icon: String? = null+        var authorName: String? = null+        var categories: List<String> = emptyList()+        var webSite: String? = null+        var sourceCode: String? = null+        var license: String? = null+        var added: Long = 0L+        var lastUpdated: Long = 0L++        reader.beginObject()+        while (reader.hasNext()) {+            when (reader.nextName()) {+                "packageName" -> packageName = nextStringOrNull(reader)+                "name" -> name = nextStringOrNull(reader)+                "summary" -> summary = nextStringOrNull(reader)+                "description" -> description = nextStringOrNull(reader)+                "icon" -> icon = nextStringOrNull(reader)+                "authorName" -> authorName = nextStringOrNull(reader)+                "categories" -> categories = readStringArray(reader)+                "webSite" -> webSite = nextStringOrNull(reader)+                "sourceCode" -> sourceCode = nextStringOrNull(reader)+                "license" -> license = nextStringOrNull(reader)+                "added" -> added = nextLongOrNull(reader) ?: 0L+                "lastUpdated" -> lastUpdated = nextLongOrNull(reader) ?: 0L+                else -> reader.skipValue()+            }+        }+        reader.endObject()+        val pkg = packageName ?: return null+        return V1AppMeta(pkg, name, summary, description, icon, authorName, categories, webSite, sourceCode, license, added, lastUpdated)+    }++    private fun parseV1PackagesArray(reader: JsonReader): V1PackageLatest? {+        // array of package versions, take last+        var last: V1PackageLatest? = null+        reader.beginArray()+        while (reader.hasNext()) {+            try {+                reader.beginObject()+                var apkName: String? = null+                var versionName: String? = null+                var versionCode: Long = 0L+                var size: Long = 0L+                var targetSdk: Int? = null+                while (reader.hasNext()) {+                    when (reader.nextName()) {+                        "apkName" -> apkName = nextStringOrNull(reader)+                        "versionName" -> versionName = nextStringOrNull(reader)+                        "versionCode" -> versionCode = nextLongOrNull(reader) ?: 0L+                        "size" -> size = nextLongOrNull(reader) ?: 0L+                        "targetSdkVersion" -> targetSdk = nextIntOrNull(reader)+                        else -> reader.skipValue()+                    }+                }+                reader.endObject()+                last = V1PackageLatest(apkName, versionName, versionCode, size, targetSdk)+            } catch (_: Exception) {+                try { reader.endObject() } catch (_: Exception) {}+                try { reader.skipValue() } catch (_: Exception) {}+            }+        }+        reader.endArray()+        return last+    }++    // ---- Helpers ----++    private fun readLocalizedString(reader: JsonReader): String? {+        return when (reader.peek()) {+            JsonToken.STRING -> reader.nextString()+            JsonToken.BEGIN_OBJECT -> {+                var first: String? = null+                var enUs: String? = null+                var en: String? = null+                reader.beginObject()+                while (reader.hasNext()) {+                    val locale = reader.nextName()+                    when (reader.peek()) {+                        JsonToken.STRING -> {+                            val v = reader.nextString()+                            if (first == null) first = v+                            if (locale == "en-US") enUs = v+                            if (locale == "en") en = v+                        }+                        else -> reader.skipValue()+                    }+                }+                reader.endObject()+                enUs ?: en ?: first+            }+            else -> { reader.skipValue(); null }+        }+    }++    private fun readIconName(reader: JsonReader): String? {+        // icon can be: { "en-US": { "96": {"name":...} } } or { "en-US": {"name":...} }+        return try {+            if (reader.peek() != JsonToken.BEGIN_OBJECT) { reader.skipValue(); return null }+            var found: String? = null+            reader.beginObject()+            while (reader.hasNext() && found == null) {+                reader.nextName() // locale+                found = findFirstNameInAnyNested(reader)+            }+            while (reader.hasNext()) { reader.nextName(); reader.skipValue() }+            reader.endObject()+            found+        } catch (_: Exception) { null }+    }++    private fun findFirstNameInAnyNested(reader: JsonReader): String? {+        // searches recursively for first object containing key "name" = String+        return when (reader.peek()) {+            JsonToken.BEGIN_OBJECT -> {+                var found: String? = null+                reader.beginObject()+                while (reader.hasNext()) {+                    val key = reader.nextName()+                    if (key == "name" && reader.peek() == JsonToken.STRING) {+                        val v = reader.nextString()+                        if (found == null) found = v+                        // keep consuming remaining to properly close+                    } else {+                        if (found == null && reader.peek() == JsonToken.BEGIN_OBJECT) {+                            val inner = findFirstNameInAnyNested(reader)+                            if (inner != null) found = inner+                        } else if (found == null && reader.peek() == JsonToken.BEGIN_ARRAY) {+                            reader.skipValue()+                        } else {+                            reader.skipValue()+                        }+                    }+                }+                reader.endObject()+                found+            }+            JsonToken.BEGIN_ARRAY -> {+                reader.beginArray()+                var found: String? = null+                while (reader.hasNext() && found == null) {+                    found = findFirstNameInAnyNested(reader)+                }+                while (reader.hasNext()) reader.skipValue()+                reader.endArray()+                found+            }+            else -> { reader.skipValue(); null }+        }+    }++    private fun readStringArray(reader: JsonReader): List<String> {+        return try {+            if (reader.peek() != JsonToken.BEGIN_ARRAY) { reader.skipValue(); return emptyList() }+            val list = mutableListOf<String>()+            reader.beginArray()+            while (reader.hasNext()) {+                if (reader.peek() == JsonToken.STRING) list.add(reader.nextString()) else reader.skipValue()+            }+            reader.endArray()+            list+        } catch (_: Exception) { emptyList() }+    }++    private fun nextStringOrNull(reader: JsonReader): String? {+        return try {+            when (reader.peek()) {+                JsonToken.STRING -> reader.nextString()+                JsonToken.NULL -> { reader.nextNull(); null }+                JsonToken.NUMBER -> reader.nextString()+                else -> { reader.skipValue(); null }+            }+        } catch (_: Exception) { null }+    }++    private fun nextLongOrNull(reader: JsonReader): Long? {+        return try {+            when (reader.peek()) {+                JsonToken.NUMBER -> reader.nextLong()+                JsonToken.STRING -> reader.nextString().toLongOrNull()+                JsonToken.NULL -> { reader.nextNull(); null }+                else -> { reader.skipValue(); null }+            }+        } catch (_: Exception) { null }+    }++    private fun nextIntOrNull(reader: JsonReader): Int? {+        return try {+            when (reader.peek()) {+                JsonToken.NUMBER -> reader.nextInt()+                JsonToken.STRING -> reader.nextString().toIntOrNull()+                JsonToken.NULL -> { reader.nextNull(); null }+                else -> { reader.skipValue(); null }+            }+        } catch (_: Exception) { null }     } }
appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.ktindex 03ad6eb703..95a33e2057 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/PlayStoreDataSource.kt@@ -63,7 +63,6 @@ object PlayStoreDataSource {             val ratingText = doc.selectFirst("div.TT9eCd")?.text()             val rating = ratingText?.toFloatOrNull() -            // Try to infer targetSdk from page text (best effort)             val pageText = doc.text()             val targetSdk = Regex("Target.*API.*?(\\d{2})|targetSdk.*?(\\d{2})", RegexOption.IGNORE_CASE)                 .find(pageText)?.groupValues?.filter { it.toIntOrNull() != null }?.lastOrNull()?.toIntOrNull()
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex f70f2b3b9e..2effe69e22 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -19,9 +19,9 @@ import com.vayunmathur.appstore.data.DefaultRepos import com.vayunmathur.appstore.data.FDroidAppProvider import com.vayunmathur.appstore.data.InstalledInfo import com.vayunmathur.appstore.data.PlayStoreAppProvider+import com.vayunmathur.appstore.data.PlayStoreDataSource import com.vayunmathur.appstore.data.RepoEntity import com.vayunmathur.appstore.data.UnifiedApp-import com.vayunmathur.appstore.data.PlayStoreDataSource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow@@ -35,21 +35,17 @@ import java.io.File import java.net.HttpURLConnection import java.net.URL -enum class InstalledFilter {-    ALL,-    FDROID,-    PLAYSTORE-}+enum class InstalledFilter { ALL, FDROID, PLAYSTORE }  class AppStoreViewModel(     private val context: Context,     private val db: AppDatabase ) : ViewModel() { -    // Providers — app registers 2 providers, fdroid base repo + play store-    private val fdroidProvider = FDroidAppProvider(db)+    // App registers 2 providers: fdroid base repo + play store (order matters for presence)+    private val fdroidProvider = FDroidAppProvider(db, context.applicationContext)     private val playProvider = PlayStoreAppProvider()-    private val providers: List<AppProvider> = listOf(fdroidProvider, playProvider)+    val providers: List<AppProvider> get() = listOf(fdroidProvider, playProvider)      private val _isSyncing = MutableStateFlow(false)     val isSyncing: StateFlow<Boolean> = _isSyncing@@ -77,45 +73,40 @@ class AppStoreViewModel(      private val _activeRepo = MutableStateFlow<String?>(null) -    // Installed filtering: presence-resolved source per package, order F-Droid -> Play Store+    // Presence-resolved: pkg -> source, checked F-Droid first then Play Store, else absent (hide)     private val _installedSourceMap = MutableStateFlow<Map<String, AppSource>>(emptyMap())     val installedSourceMap: StateFlow<Map<String, AppSource>> = _installedSourceMap      private val _installedFilter = MutableStateFlow(InstalledFilter.ALL)     val installedFilter: StateFlow<InstalledFilter> = _installedFilter -    val repos = db.repoDao().allFlow()-        .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())--    val cachedApps = db.cachedAppDao().allFlow()-        .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())+    val repos = db.repoDao().allFlow().stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())+    val cachedApps = db.cachedAppDao().allFlow().stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())      val combinedBrowse: StateFlow<List<UnifiedApp>> = combine(         cachedApps, _playSearchResults, _topCharts, _searchQuery, _activeRepo     ) { cached, playSearch, topCharts, query, activeRepo ->         val fdroidAll = cached.map { it.toUnifiedApp() }-        val fdroidFiltered = if (activeRepo != null) fdroidAll.filter { it.repoUrl == activeRepo } else fdroidAll+        val fdroid = if (activeRepo != null) fdroidAll.filter { it.repoUrl == activeRepo } else fdroidAll         val fdroidPkgs = fdroidAll.map { it.packageName }.toSet()-         fun infer(pkg: String): AppSource = if (fdroidPkgs.contains(pkg)) AppSource.FDROID else AppSource.PLAYSTORE          val infSearch = playSearch.map { it.copy(source = infer(it.packageName)) }         val infCharts = topCharts.map { it.copy(source = infer(it.packageName)) }          val list = if (query.isBlank()) {-            fdroidFiltered + (if (infSearch.isEmpty()) infCharts else infSearch)+            fdroid + (if (infSearch.isEmpty()) infCharts else infSearch)         } else {             val q = query.lowercase()-            val fd = fdroidFiltered.filter {+            val fd = fdroid.filter {                 it.name.lowercase().contains(q) || it.packageName.lowercase().contains(q) || it.summary.lowercase().contains(q)             }             (fd + infSearch).distinctBy { it.packageName }.map { it.copy(source = infer(it.packageName)) }         }-        // Filter targetSdk < 35 for both sources (defense in depth)         AppProvider.filterTargetSdk(list.distinctBy { it.packageName }).sortedBy { it.name.lowercase() }     }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) -    // Presence-resolved installed list: only apps present in fdroid or play (order checked), with counts+    // Installed filtered: only apps present in fdroid or play (order checked), with counts for filter chips     val filteredInstalled: StateFlow<List<InstalledInfo>> = combine(         _installedApps, _installedSourceMap, _installedFilter     ) { installed, srcMap, filter ->@@ -127,8 +118,8 @@ class AppStoreViewModel(         }     }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) -    var searchJob: Job? = null-    var topJob: Job? = null+    private var searchJob: Job? = null+    private var topJob: Job? = null      init {         viewModelScope.launch {@@ -136,7 +127,6 @@ class AppStoreViewModel(             refreshInstalled()             loadTopCharts()         }-        // Keep fdroid provider cache synced with DB flow         viewModelScope.launch {             cachedApps.collect { list ->                 fdroidProvider.cachedPackageNames = list.map { it.packageName }.toSet()@@ -157,8 +147,7 @@ class AppStoreViewModel(         topJob?.cancel()         topJob = viewModelScope.launch {             _syncMessage.value = "Loading top charts..."-            val charts = playProvider.fetchAll()-            _topCharts.value = charts+            _topCharts.value = playProvider.fetchAll()             _syncMessage.value = ""         }     }@@ -173,8 +162,7 @@ class AppStoreViewModel(         searchJob = viewModelScope.launch {             kotlinx.coroutines.delay(400)             _syncMessage.value = "Searching Play Store..."-            val results = playProvider.search(q)-            _playSearchResults.value = results+            _playSearchResults.value = playProvider.search(q)             _syncMessage.value = ""         }     }@@ -185,10 +173,10 @@ class AppStoreViewModel(             _isSyncing.value = true             _syncMessage.value = "Syncing F-Droid repositories..."             try {-                val total = fdroidProvider.syncIntoDb()-                _syncMessage.value = if (total > 0) "Synced $total apps from F-Droid" else "Sync complete"+                val total = fdroidProvider.syncIntoDb(context.applicationContext)+                _syncMessage.value = if (total > 0) "Synced $total F-Droid apps" else "Sync complete"             } catch (e: Exception) {-                _syncMessage.value = "F-Droid sync failed: ${e.message}"+                _syncMessage.value = "Sync failed: ${e.message}"             }             kotlinx.coroutines.delay(1500)             _syncMessage.value = ""@@ -201,7 +189,6 @@ class AppStoreViewModel(         viewModelScope.launch(Dispatchers.IO) {             val pm = context.packageManager             val all = pm.getInstalledApplications(PackageManager.MATCH_ALL)-            // User apps only — not system partition             val userApps = all.filter { (it.flags and ApplicationInfo.FLAG_SYSTEM) == 0 }             val installed = userApps.mapNotNull { ai ->                 try {@@ -223,7 +210,6 @@ class AppStoreViewModel(                 _installedApps.value = installed                 _installedIcons.value = icons             }-            // Resolve source presence for each installed app, order: fdroid -> play -> none (hide)             resolveInstalledSources(installed.map { it.packageName })         }     }@@ -232,24 +218,17 @@ class AppStoreViewModel(         viewModelScope.launch(Dispatchers.IO) {             val map = mutableMapOf<String, AppSource>()             for (pkg in packages) {-                // Order: fdroid first, then play store-                if (fdroidProvider.isPresent(pkg)) {-                    map[pkg] = AppSource.FDROID-                } else if (playProvider.isPresent(pkg)) {-                    map[pkg] = AppSource.PLAYSTORE-                }-                // else not in any store -> hidden from installed list (per requirement)+                // Order: F-Droid first, then Play Store, else hide from installed list+                if (fdroidProvider.isPresent(pkg)) map[pkg] = AppSource.FDROID+                else if (playProvider.isPresent(pkg)) map[pkg] = AppSource.PLAYSTORE             }             _installedSourceMap.value = map         }     } -    fun setInstalledFilter(filter: InstalledFilter) {-        _installedFilter.value = filter-    }+    fun setInstalledFilter(filter: InstalledFilter) { _installedFilter.value = filter }      fun selectApp(app: UnifiedApp) {-        // Re-infer via providers order: fdroid check takes precedence         val fdroidPkgs = cachedApps.value.map { it.packageName }.toSet()         val inferredSource = if (fdroidPkgs.contains(app.packageName)) AppSource.FDROID else AppSource.PLAYSTORE         _selectedApp.value = app.copy(source = inferredSource)@@ -265,37 +244,26 @@ class AppStoreViewModel(      fun openInPlayStore(pkg: String) {         try {-            val market = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$pkg")).apply {-                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)-            }-            context.startActivity(market)+            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$pkg")).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })         } catch (_: Exception) {-            val web = Intent(Intent.ACTION_VIEW, Uri.parse(PlayStoreDataSource.playStoreUrl(pkg))).apply {-                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)-            }-            context.startActivity(web)+            context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PlayStoreDataSource.playStoreUrl(pkg))).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })         }     }      fun openInBrowser(url: String) {         if (url.isBlank()) return-        try {-            val i = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }-            context.startActivity(i)-        } catch (_: Exception) { }+        try { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) } catch (_: Exception) {}     }      fun addRepo(url: String, name: String) {         viewModelScope.launch {-            val clean = url.trim().trimEnd('/')-            db.repoDao().upsert(RepoEntity(clean, name.ifBlank { clean }, true))+            db.repoDao().upsert(RepoEntity(url.trim().trimEnd('/'), name.ifBlank { url.trim() }, true))         }     }      fun toggleRepo(url: String) {         viewModelScope.launch {-            val existing = db.repoDao().all().find { it.url == url } ?: return@launch-            db.repoDao().upsert(existing.copy(enabled = !existing.enabled))+            db.repoDao().all().find { it.url == url }?.let { db.repoDao().upsert(it.copy(enabled = !it.enabled)) }         }     } @@ -307,23 +275,17 @@ class AppStoreViewModel(     }      fun downloadAndInstall(app: UnifiedApp) {-        // Use presence logic: fdroid present -> direct APK, else play -> market intent         viewModelScope.launch {-            val srcMap = _installedSourceMap.value             val fdroidPkgs = cachedApps.value.map { it.packageName }.toSet()-            val isFdroid = fdroidPkgs.contains(app.packageName) || srcMap[app.packageName] == AppSource.FDROID || app.source == AppSource.FDROID-            if (!isFdroid) {-                openInPlayStore(app.packageName)-                return@launch-            }+            val isFdroid = fdroidPkgs.contains(app.packageName) || app.source == AppSource.FDROID+            if (!isFdroid) { openInPlayStore(app.packageName); return@launch }             val apkUrl = app.apkUrl ?: cachedApps.value.find { it.packageName == app.packageName }?.apkUrl ?: return@launch             withContext(Dispatchers.IO) {                 try {                     _downloadProgress.value = _downloadProgress.value + (app.packageName to 0.01f)                     val file = File(context.cacheDir, "${app.packageName}.apk")                     val conn = (URL(apkUrl).openConnection() as HttpURLConnection).apply {-                        connectTimeout = 20000-                        readTimeout = 60000+                        connectTimeout = 20000; readTimeout = 60000                     }                     val total = conn.contentLengthLong.takeIf { it > 0 } ?: app.sizeBytes                     conn.inputStream.use { input ->@@ -334,9 +296,7 @@ class AppStoreViewModel(                             while (input.read(buf).also { read = it } != -1) {                                 out.write(buf, 0, read)                                 downloaded += read-                                if (total > 0) {-                                    _downloadProgress.value = _downloadProgress.value + (app.packageName to (downloaded.toFloat() / total))-                                }+                                if (total > 0) _downloadProgress.value = _downloadProgress.value + (app.packageName to (downloaded.toFloat() / total))                             }                         }                     }@@ -353,37 +313,14 @@ class AppStoreViewModel(     private fun installApk(file: File) {         try {             val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)-            val intent = Intent(Intent.ACTION_VIEW).apply {+            context.startActivity(Intent(Intent.ACTION_VIEW).apply {                 setDataAndType(uri, "application/vnd.android.package-archive")                 addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)-            }-            context.startActivity(intent)-        } catch (e: Exception) {-            _syncMessage.value = "Install failed: ${e.message}"-        }-    }--    fun setActiveRepoFilter(repoUrl: String?) {-        _activeRepo.value = repoUrl+            })+        } catch (e: Exception) { _syncMessage.value = "Install failed: ${e.message}" }     } -    private fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(-        packageName = packageName,-        source = source.name,-        name = name,-        summary = summary,-        description = description,-        iconUrl = iconUrl,-        author = author,-        categories = categories.joinToString(","),-        versionName = versionName,-        versionCode = versionCode,-        sizeBytes = sizeBytes,-        apkUrl = apkUrl,-        targetSdk = targetSdk,-        repoUrl = repoUrl?.removeSuffix("/") ?: DefaultRepos.FDROID_MAIN,-        lastUpdated = lastUpdated-    )+    fun setActiveRepoFilter(repoUrl: String?) { _activeRepo.value = repoUrl }      private fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(         packageName = packageName,@@ -404,10 +341,7 @@ class AppStoreViewModel(     ) } -class AppStoreViewModelFactory(-    private val context: Context,-    private val db: AppDatabase-) : ViewModelProvider.Factory {+class AppStoreViewModelFactory(private val context: Context, private val db: AppDatabase) : ViewModelProvider.Factory {     @Suppress("UNCHECKED_CAST")     override fun <T : ViewModel> create(modelClass: Class<T>): T {         return AppStoreViewModel(context.applicationContext, db) as T
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex b389f3d31d..a81551ed0d 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -152,8 +152,9 @@ configure<com.android.build.api.dsl.ApplicationExtension> {      packaging {         resources {-            // bouncycastle 1.85 (bcprov/bcpkix/bcutil) each ship these license files,-            // which collide during Java-resource merge.+            // :email's jakarta.mail stack (org.eclipse.angus:jakarta.mail,+            // jakarta.activation-api, angus-activation) each ship these license+            // files, which collide during Java-resource merge.             excludes += setOf(                 "META-INF/LICENSE.md",                 "META-INF/NOTICE.md",
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 cc4ebf8501..2d3dd19c54 100644--- a/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt+++ b/camera/src/main/java/com/vayunmathur/camera/ui/CameraScreen.kt@@ -140,6 +140,8 @@ import com.vayunmathur.camera.util.CameraViewModel import com.vayunmathur.camera.util.GuideDot import com.vayunmathur.camera.util.GuideDotState import com.vayunmathur.camera.util.FlashMode+import com.vayunmathur.camera.util.BOKEH_SHADER+import com.vayunmathur.camera.util.bokehBlurScale import com.vayunmathur.camera.util.buildColorAdjustmentMatrix import com.vayunmathur.camera.util.formatZoomLabel import com.vayunmathur.camera.util.PhotoAnalyzer@@ -151,60 +153,6 @@ import kotlinx.coroutines.launch import kotlin.math.roundToInt  -private const val BOKEH_SHADER = """-    uniform shader cameraInput;-    uniform shader alphaMask;-    uniform float blurScale;--    half4 main(float2 fragCoord) {-        float maskAlpha = alphaMask.eval(fragCoord).a;-        half4 sharp = cameraInput.eval(fragCoord);--        // 3-pass separable bokeh: blur along 0°, 120°, 240° axes then average.-        // Each pass samples 13 taps along its direction (radius ~36px).-        float2 dir0 = float2(1.0, 0.0);-        float2 dir1 = float2(-0.5, 0.866);-        float2 dir2 = float2(-0.5, -0.866);--        // 1D Gaussian-ish weights for 13 taps (symmetric, sum ≈ 1)-        float w0 = 0.14;-        float w1 = 0.13;-        float w2 = 0.11;-        float w3 = 0.09;-        float w4 = 0.06;-        float w5 = 0.04;-        float w6 = 0.02;--        half4 pass0 = cameraInput.eval(fragCoord) * w0;-        half4 pass1 = cameraInput.eval(fragCoord) * w0;-        half4 pass2 = cameraInput.eval(fragCoord) * w0;--        for (float i = 1.0; i <= 6.0; i += 1.0) {-            float w;-            if (i < 1.5) w = w1;-            else if (i < 2.5) w = w2;-            else if (i < 3.5) w = w3;-            else if (i < 4.5) w = w4;-            else if (i < 5.5) w = w5;-            else w = w6;--            float2 off0 = dir0 * i * 6.0 * blurScale;-            float2 off1 = dir1 * i * 6.0 * blurScale;-            float2 off2 = dir2 * i * 6.0 * blurScale;--            pass0 += cameraInput.eval(fragCoord + off0) * w;-            pass0 += cameraInput.eval(fragCoord - off0) * w;-            pass1 += cameraInput.eval(fragCoord + off1) * w;-            pass1 += cameraInput.eval(fragCoord - off1) * w;-            pass2 += cameraInput.eval(fragCoord + off2) * w;-            pass2 += cameraInput.eval(fragCoord - off2) * w;-        }--        half4 blur = (pass0 + pass1 + pass2) / 3.0;-        return mix(blur, sharp, maskAlpha);-    }-"""- private enum class CameraSetting {     BRIGHTNESS, SHADOWS, WARMTH, EXPOSURE_TIME, PORTRAIT_BLUR, ISO }@@ -619,7 +567,7 @@ fun CameraScreen(                                                     matrix.setScale(size.width / localMask.width, size.height / localMask.height)                                                     maskShader.setLocalMatrix(matrix)                                                     shader.setInputShader("alphaMask", maskShader)-                                                    shader.setFloatUniform("blurScale", 0.4f + blurStrength * 1.4f)+                                                    shader.setFloatUniform("blurScale", bokehBlurScale(blurStrength))                                                     effect = RenderEffect.createRuntimeShaderEffect(shader, "cameraInput")                                                 } catch (_: Exception) {                                                     // Mask may be recycled between snapshot and render – skip bokeh this frame
camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.ktindex d25db526b1..8ac34bedde 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/BokehAnalyzer.kt@@ -2,7 +2,6 @@ package com.vayunmathur.camera.util  import android.content.Context import android.graphics.Bitmap-import android.graphics.Color import android.graphics.Matrix import android.os.SystemClock import android.util.Log@@ -24,13 +23,18 @@ class BokehAnalyzer(     private val onMaskGenerated: (Bitmap) -> Unit ) : ImageAnalysis.Analyzer { +    // Guard for the native handle and buffer fields – analyze() runs on bokehExecutor+    // while close() runs on the main composable's DisposableEffect. Without mutual+    // exclusion, close() destroys the ncnn net while openmp_worker threads are still+    // reading it → SEGV_MTESERR tagged fault in libncnn_android.so.+    private val lock = Any()     private var prevMask: FloatArray? = null     private var blurTemp: FloatArray? = null     private var blurDst: FloatArray? = null     private var pixelBuffer: IntArray? = null     private var lastSegmentMs: Long = 0L     @Volatile private var closed = false-    private val segmenter = PortraitSegmenter(context, "erdnet.param", "erdnet.bin")+    private var segmenter: PortraitSegmenter? = PortraitSegmenter(context, "erdnet.param", "erdnet.bin")      @androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)     override fun analyze(imageProxy: ImageProxy) {@@ -68,54 +72,69 @@ class BokehAnalyzer(             }              // Synchronous forward pass; runs on dedicated bokehExecutor with KEEP_ONLY_LATEST.-            val result = try {-                segmenter.segment(frame)-            } catch (e: IllegalStateException) {-                // PortraitSegmenter is closed – analyzer disposed while frame in-flight-                Log.w("BokehAnalyzer", "segmenter closed mid-frame", e)-                frame.recycle()-                return+            // Hold lock across the native call so close() blocks until OpenMP workers finish,+            // preventing the SEGV_MTESERR use-after-free seen in tombstones.+            val result = synchronized(lock) {+                if (closed) {+                    frame.recycle()+                    return+                }+                val seg = segmenter+                if (seg == null) {+                    frame.recycle()+                    return+                }+                try {+                    seg.segment(frame)+                } catch (e: IllegalStateException) {+                    // PortraitSegmenter is closed – analyzer disposed while frame in-flight+                    Log.w("BokehAnalyzer", "segmenter closed mid-frame", e)+                    frame.recycle()+                    return+                }             }             frame.recycle()             if (closed) return -            val w = result.width-            val h = result.height-            val current = result.mask // foreground prob [0,1], row-major--            // Temporal smoothing: in-place blend into current array when possible to avoid alloc.-            val prev = prevMask-            val smoothed = if (prev != null && prev.size == current.size) {-                for (i in current.indices) {-                    current[i] = current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT+            synchronized(lock) {+                if (closed) return+                val w = result.width+                val h = result.height+                val current = result.mask // foreground prob [0,1], row-major++                // Temporal smoothing: in-place blend into current array when possible to avoid alloc.+                val prev = prevMask+                val smoothed = if (prev != null && prev.size == current.size) {+                    for (i in current.indices) {+                        current[i] = current[i] * (1f - TEMPORAL_WEIGHT) + prev[i] * TEMPORAL_WEIGHT+                    }+                    current+                } else {+                    current                 }-                current-            } else {-                current-            }-            prevMask = smoothed+                prevMask = smoothed -            // Blur for soft edges – reuses temp/dst buffers.-            val blurred = blurMask(smoothed, w, h)+                // Blur for soft edges – reuses temp/dst buffers across frames to avoid GC pressure.+                var temp = blurTemp+                if (temp == null || temp.size != w * h) {+                    temp = FloatArray(w * h)+                    blurTemp = temp+                }+                var dst = blurDst+                if (dst == null || dst.size != w * h) {+                    dst = FloatArray(w * h)+                    blurDst = dst+                }+                val blurred = blurMask(smoothed, w, h, temp, dst) -            // Reuse pixel buffer.-            var pixels = pixelBuffer-            if (pixels == null || pixels.size != w * h) {-                pixels = IntArray(w * h)-                pixelBuffer = pixels-            }-            for (i in 0 until w * h) {-                val v = blurred[i]-                val clamped = when {-                    v < 0f -> 0f-                    v > 1f -> 1f-                    else -> v+                // Reuse pixel buffer.+                var pixels = pixelBuffer+                if (pixels == null || pixels.size != w * h) {+                    pixels = IntArray(w * h)+                    pixelBuffer = pixels                 }-                val alpha = (clamped * 255f).toInt()-                pixels[i] = Color.argb(alpha, 255, 255, 255)+                onMaskGenerated(maskToBitmap(blurred, w, h, pixels))             }-            val maskBitmap = Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)-            onMaskGenerated(maskBitmap)         } catch (e: Throwable) {             Log.e("BokehAnalyzer", "segmentation failed", e)         } finally {@@ -124,12 +143,21 @@ class BokehAnalyzer(     }      fun close() {-        closed = true-        try { segmenter.close() } catch (_: Exception) {}-        prevMask = null-        blurTemp = null-        blurDst = null-        pixelBuffer = null+        val toClose: PortraitSegmenter?+        synchronized(lock) {+            if (closed) return+            closed = true+            toClose = segmenter+            segmenter = null+            prevMask = null+            blurTemp = null+            blurDst = null+            pixelBuffer = null+        }+        // Destroy outside lock after nulling handle, but close() itself was blocked until+        // any in-flight segment() finished (lock held across native call), so no OpenMP+        // worker is still reading the net.+        try { toClose?.close() } catch (_: Exception) {}     }      private fun downscaleIfNeeded(src: Bitmap, maxSide: Int): Bitmap {@@ -155,86 +183,4 @@ class BokehAnalyzer(         if (isFrontFacing) matrix.postScale(-1f, 1f) // preview mirrors the front lens         return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, false)     }--    private fun blurMask(src: FloatArray, w: Int, h: Int): FloatArray {-        // Two-pass separable Gaussian blur (radius 3, sigma ~1.5)-        // Reuse buffers to avoid per-frame allocs that caused GC pressure.-        val wh = w * h-        var temp = blurTemp-        if (temp == null || temp.size != wh) {-            temp = FloatArray(wh)-            blurTemp = temp-        }-        var dst = blurDst-        if (dst == null || dst.size != wh) {-            dst = FloatArray(wh)-            blurDst = dst-        }--        // Horizontal pass – manual clamp instead of coerceIn in inner loop-        for (y in 0 until h) {-            val row = y * w-            for (x in 0 until w) {-                var sum = 0f-                var sx: Int-                // k = -3-                sx = x - 3-                if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1-                sum += src[row + sx] * 0.06f-                // k = -2-                sx = x - 2-                if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1-                sum += src[row + sx] * 0.12f-                // k = -1-                sx = x - 1-                if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1-                sum += src[row + sx] * 0.18f-                // k = 0-                sum += src[row + x] * 0.28f-                // k = 1-                sx = x + 1-                if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1-                sum += src[row + sx] * 0.18f-                // k = 2-                sx = x + 2-                if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1-                sum += src[row + sx] * 0.12f-                // k = 3-                sx = x + 3-                if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1-                sum += src[row + sx] * 0.06f--                temp[row + x] = sum-            }-        }-        // Vertical pass-        for (x in 0 until w) {-            for (y in 0 until h) {-                var sum = 0f-                var sy: Int-                sy = y - 3-                if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1-                sum += temp[sy * w + x] * 0.06f-                sy = y - 2-                if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1-                sum += temp[sy * w + x] * 0.12f-                sy = y - 1-                if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1-                sum += temp[sy * w + x] * 0.18f-                sum += temp[y * w + x] * 0.28f-                sy = y + 1-                if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1-                sum += temp[sy * w + x] * 0.18f-                sy = y + 2-                if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1-                sum += temp[sy * w + x] * 0.12f-                sy = y + 3-                if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1-                sum += temp[sy * w + x] * 0.06f--                dst[y * w + x] = sum-            }-        }-        return dst-    } }
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 91578a7a42..ecc1a2fb1b 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/CameraViewModel.kt@@ -275,6 +275,9 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     private val sensorManager by lazy { app.getSystemService(Context.SENSOR_SERVICE) as SensorManager }     // Dedicated single thread for portrait segmentation so main thread stays free for preview rendering.     private val bokehExecutor: ExecutorService = Executors.newSingleThreadExecutor()+    // Bakes the same bokeh into the saved still. Separate from the preview's BokehAnalyzer, which is+    // owned by the composable and torn down with it; this one loads its model on the first capture.+    private val stillBokeh = StillBokehRenderer(app)     private val levelListener = object : SensorEventListener {         override fun onSensorChanged(event: SensorEvent) {             val x = event.values[0]@@ -2398,13 +2401,16 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {             val warmth = _warmth.value             val shadows = _shadows.value             val mirror = mirrorCaptures-            if (warmth != 0f || shadows != 0f) {-                // The warmth/shadows adjustment only lives in the preview RenderEffect, so bake-                // it into the pixels here: capture in-memory, apply the same color matrix, then-                // re-encode. Re-encoding drops the JPEG's EXIF, so we copy it back from the-                // original frame (plus GPS and the orientation tag) to match the normal path.+            val bokeh = _cameraMode.value == CameraMode.PORTRAIT+            val strength = _blurStrength.value+            if (bokeh || warmth != 0f || shadows != 0f) {+                // The warmth/shadows adjustment and the portrait bokeh only live in the preview+                // RenderEffect, so bake them into the pixels here: capture in-memory, re-run the+                // same shader/color matrix over the full-resolution frame, then re-encode.+                // Re-encoding drops the JPEG's EXIF, so we copy it back from the original frame+                // (plus GPS and the orientation tag) to match the normal path.                 // Caveat: this processed path is always SDR JPEG — decoding to an ARGB_8888 bitmap-                // discards any Ultra HDR gain map, so warmth/shadows captures lose HDR even when+                // discards any Ultra HDR gain map, so processed captures lose HDR even when                 // Ultra HDR is otherwise active. Normal (unprocessed) captures keep the gain map.                 capture.takePicture(                     ContextCompat.getMainExecutor(app),@@ -2427,7 +2433,13 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {                                         BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size),                                         cropRect                                     )-                                    val adjusted = applyColorAdjustments(decoded, warmth, shadows, mirror)+                                    // The bokeh renderer folds the colour matrix and the mirror in+                                    // as it composites; it leaves `decoded` alone if it can't run,+                                    // so fall back to the plain colour pass.+                                    val adjusted = (if (bokeh) {+                                        stillBokeh.render(decoded, degrees, strength, warmth, shadows, mirror)+                                    } else null)+                                        ?: applyColorAdjustments(decoded, warmth, shadows, mirror)                                     val values = MediaStoreSaver.imageValues("IMG_${MediaStoreSaver.timestamp()}.jpg")                                     MediaStoreSaver.saveBitmap(app.contentResolver, values, adjusted)                                         ?.also { writeCaptureExif(it, sourceJpeg, degrees) }@@ -2871,6 +2883,14 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         val executor = ContextCompat.getMainExecutor(app)         val outputUri = resultOutputUri +        // Portrait bokeh / warmth / shadows only exist in the preview, so a shot taken in those+        // modes has to be re-processed before it goes back to the caller, exactly as+        // captureSinglePhoto() does for the gallery.+        if (_cameraMode.value == CameraMode.PORTRAIT || _warmth.value != 0f || _shadows.value != 0f) {+            capturePhotoForResultProcessed(capture, outputUri, onSaved, onError)+            return+        }+         if (outputUri != null) {             val outputStream = try {                 app.contentResolver.openOutputStream(outputUri)@@ -2918,6 +2938,107 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {         }     } +    /**+     * [capturePhotoForResult] for a shot that needs the preview's portrait bokeh / colour+     * adjustments baked in: capture in-memory, re-run them over the full-resolution frame, then+     * either re-encode into the caller's EXTRA_OUTPUT stream or hand back the "data" thumbnail.+     * Shares captureSinglePhoto()'s Ultra HDR caveat — the decode to ARGB_8888 drops the gain map.+     */+    private fun capturePhotoForResultProcessed(+        capture: ImageCapture,+        outputUri: Uri?,+        onSaved: (Bitmap?) -> Unit,+        onError: () -> Unit,+    ) {+        val warmth = _warmth.value+        val shadows = _shadows.value+        val mirror = mirrorCaptures+        val bokeh = _cameraMode.value == CameraMode.PORTRAIT+        val strength = _blurStrength.value++        capture.takePicture(+            ContextCompat.getMainExecutor(app),+            object : ImageCapture.OnImageCapturedCallback() {+                override fun onCaptureSuccess(image: ImageProxy) {+                    val degrees = image.imageInfo.rotationDegrees+                    val cropRect = Rect(image.cropRect)+                    val sourceJpeg = try {+                        image.planes[0].buffer.let { buf ->+                            ByteArray(buf.remaining()).also { buf.get(it) }+                        }+                    } finally {+                        image.close()+                    }+                    viewModelScope.launch {+                        val result = withContext(Dispatchers.IO) {+                            runCatching {+                                val decoded = cropToRect(+                                    BitmapFactory.decodeByteArray(sourceJpeg, 0, sourceJpeg.size),+                                    cropRect+                                )+                                val adjusted = (if (bokeh) {+                                    stillBokeh.render(decoded, degrees, strength, warmth, shadows, mirror)+                                } else null)+                                    ?: applyColorAdjustments(decoded, warmth, shadows, mirror)+                                // The gallery path leaves rotation to the EXIF tag, but a caller's+                                // Uri may not open "rw" for writeCaptureExif, so bake it into the+                                // pixels here and tag the result upright.+                                val upright = uprightCopy(adjusted, degrees, if (outputUri == null) 512 else 0)+                                adjusted.recycle()+                                if (outputUri == null) {+                                    upright+                                } else {+                                    val wrote = try {+                                        app.contentResolver.openOutputStream(outputUri)?.use { out ->+                                            upright.compress(Bitmap.CompressFormat.JPEG, 95, out)+                                        } ?: false+                                    } finally {+                                        upright.recycle()+                                    }+                                    if (!wrote) error("Could not write to EXTRA_OUTPUT")+                                    writeCaptureExif(outputUri, sourceJpeg, 0)+                                    null+                                }+                            }+                        }+                        _isCapturing.value = false+                        result.fold(+                            onSuccess = { onSaved(it) },+                            onFailure = {+                                Log.e("CameraViewModel", "Processed IMAGE_CAPTURE failed", it)+                                onError()+                            }+                        )+                    }+                }+                override fun onError(exception: ImageCaptureException) {+                    _isCapturing.value = false+                    Log.e("CameraViewModel", "Processed IMAGE_CAPTURE capture failed", exception)+                    onError()+                }+            }+        )+    }++    /**+     * Rotates an already-processed capture's pixels upright, optionally scaling its long side down+     * to [maxSide] (0 = keep full resolution) for the result "data" thumbnail. Unlike+     * [downscaledThumbnail] it does not mirror — the processed bitmap already is. Always returns a+     * bitmap distinct from [src] so the caller can recycle it.+     */+    private fun uprightCopy(src: Bitmap, rotationDegrees: Int, maxSide: Int): Bitmap {+        val scale = if (maxSide > 0) {+            (maxSide.toFloat() / maxOf(src.width, src.height)).coerceAtMost(1f)+        } else 1f+        val matrix = Matrix().apply {+            postRotate(rotationDegrees.toFloat())+            if (scale < 1f) postScale(scale, scale)+        }+        val out = Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true)+        // createBitmap hands back the input itself when the transform is an identity.+        return if (out === src) src.copy(Bitmap.Config.ARGB_8888, false) else out+    }+     /** Rotates the captured frame upright (mirroring for the front camera) and scales it down for the result "data" thumbnail. */     private fun downscaledThumbnail(image: ImageProxy, mirror: Boolean): Bitmap {         val raw = image.toBitmap()@@ -3216,6 +3337,7 @@ class CameraViewModel(private val app: Application) : AndroidViewModel(app) {     override fun onCleared() {         unregisterLevelSensor()         try { bokehExecutor.shutdown() } catch (_: Exception) {}+        try { stillBokeh.close() } catch (_: Exception) {}         super.onCleared()     } }
camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt b/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.ktnew file mode 100644index 0000000000..1126d7a5b4--- /dev/null+++ b/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt@@ -0,0 +1,415 @@+package com.vayunmathur.camera.util++import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapShader+import android.graphics.Canvas+import android.graphics.Color+import android.graphics.ColorMatrixColorFilter+import android.graphics.HardwareRenderer+import android.graphics.Matrix+import android.graphics.Paint+import android.graphics.PixelFormat+import android.graphics.PorterDuff+import android.graphics.PorterDuffXfermode+import android.graphics.Rect+import android.graphics.RenderNode+import android.graphics.RuntimeShader+import android.graphics.Shader+import android.hardware.HardwareBuffer+import android.media.ImageReader+import android.util.Log+import com.vayunmathur.ncnn.PortraitSegmenter+import kotlin.math.max+import kotlin.math.min+import kotlin.math.roundToInt++/**+ * Pseudo-bokeh used by both the portrait viewfinder ([com.vayunmathur.camera.ui.CameraScreen]) and+ * the still-capture path ([StillBokehRenderer]), so a saved photo matches what the preview showed.+ *+ * 3-pass separable blur along the 0°/120°/240° axes, averaged, then cross-faded back to the sharp+ * input by the segmentation mask's alpha (1 = subject, 0 = background).+ */+internal const val BOKEH_SHADER = """+    uniform shader cameraInput;+    uniform shader alphaMask;+    uniform float blurScale;++    half4 main(float2 fragCoord) {+        float maskAlpha = alphaMask.eval(fragCoord).a;+        half4 sharp = cameraInput.eval(fragCoord);++        // 3-pass separable bokeh: blur along 0°, 120°, 240° axes then average.+        // Each pass samples 13 taps along its direction (radius ~36px).+        float2 dir0 = float2(1.0, 0.0);+        float2 dir1 = float2(-0.5, 0.866);+        float2 dir2 = float2(-0.5, -0.866);++        // 1D Gaussian-ish weights for 13 taps (symmetric, sum ≈ 1)+        float w0 = 0.14;+        float w1 = 0.13;+        float w2 = 0.11;+        float w3 = 0.09;+        float w4 = 0.06;+        float w5 = 0.04;+        float w6 = 0.02;++        half4 pass0 = cameraInput.eval(fragCoord) * w0;+        half4 pass1 = cameraInput.eval(fragCoord) * w0;+        half4 pass2 = cameraInput.eval(fragCoord) * w0;++        for (float i = 1.0; i <= 6.0; i += 1.0) {+            float w;+            if (i < 1.5) w = w1;+            else if (i < 2.5) w = w2;+            else if (i < 3.5) w = w3;+            else if (i < 4.5) w = w4;+            else if (i < 5.5) w = w5;+            else w = w6;++            float2 off0 = dir0 * i * 6.0 * blurScale;+            float2 off1 = dir1 * i * 6.0 * blurScale;+            float2 off2 = dir2 * i * 6.0 * blurScale;++            pass0 += cameraInput.eval(fragCoord + off0) * w;+            pass0 += cameraInput.eval(fragCoord - off0) * w;+            pass1 += cameraInput.eval(fragCoord + off1) * w;+            pass1 += cameraInput.eval(fragCoord - off1) * w;+            pass2 += cameraInput.eval(fragCoord + off2) * w;+            pass2 += cameraInput.eval(fragCoord - off2) * w;+        }++        half4 blur = (pass0 + pass1 + pass2) / 3.0;+        return mix(blur, sharp, maskAlpha);+    }+"""++/** Maps the 0..1 "blur strength" slider onto the shader's tap-spacing multiplier. */+internal fun bokehBlurScale(strength: Float): Float = 0.4f + strength.coerceIn(0f, 1f) * 1.4f++/**+ * Two-pass separable Gaussian blur (radius 3, sigma ~1.5) of a row-major foreground-probability+ * mask, which softens the segmenter's hard edges. [temp] and [dst] are w*h scratch buffers owned by+ * the caller so the per-frame preview path can reuse them across frames; the result is [dst].+ */+internal fun blurMask(src: FloatArray, w: Int, h: Int, temp: FloatArray, dst: FloatArray): FloatArray {+    // Horizontal pass – manual clamp instead of coerceIn in inner loop+    for (y in 0 until h) {+        val row = y * w+        for (x in 0 until w) {+            var sum = 0f+            var sx: Int+            // k = -3+            sx = x - 3+            if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+            sum += src[row + sx] * 0.06f+            // k = -2+            sx = x - 2+            if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+            sum += src[row + sx] * 0.12f+            // k = -1+            sx = x - 1+            if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+            sum += src[row + sx] * 0.18f+            // k = 0+            sum += src[row + x] * 0.28f+            // k = 1+            sx = x + 1+            if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+            sum += src[row + sx] * 0.18f+            // k = 2+            sx = x + 2+            if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+            sum += src[row + sx] * 0.12f+            // k = 3+            sx = x + 3+            if (sx < 0) sx = 0 else if (sx >= w) sx = w - 1+            sum += src[row + sx] * 0.06f++            temp[row + x] = sum+        }+    }+    // Vertical pass+    for (x in 0 until w) {+        for (y in 0 until h) {+            var sum = 0f+            var sy: Int+            sy = y - 3+            if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+            sum += temp[sy * w + x] * 0.06f+            sy = y - 2+            if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+            sum += temp[sy * w + x] * 0.12f+            sy = y - 1+            if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+            sum += temp[sy * w + x] * 0.18f+            sum += temp[y * w + x] * 0.28f+            sy = y + 1+            if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+            sum += temp[sy * w + x] * 0.18f+            sy = y + 2+            if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+            sum += temp[sy * w + x] * 0.12f+            sy = y + 3+            if (sy < 0) sy = 0 else if (sy >= h) sy = h - 1+            sum += temp[sy * w + x] * 0.06f++            dst[y * w + x] = sum+        }+    }+    return dst+}++/**+ * Packs a foreground-probability mask into a white ARGB_8888 bitmap whose alpha is that+ * probability, which is the form both the preview shader and [StillBokehRenderer] sample.+ * [pixels] is a w*h scratch buffer owned by the caller (reused per frame by the preview).+ */+internal fun maskToBitmap(mask: FloatArray, w: Int, h: Int, pixels: IntArray): Bitmap {+    for (i in 0 until w * h) {+        val v = mask[i]+        val clamped = when {+            v < 0f -> 0f+            v > 1f -> 1f+            else -> v+        }+        pixels[i] = Color.argb((clamped * 255f).toInt(), 255, 255, 255)+    }+    return Bitmap.createBitmap(pixels, w, h, Bitmap.Config.ARGB_8888)+}++// Segmentation input: the model runs at 256x256 internally, so there is nothing to gain from+// feeding it the full-resolution still. Matches the preview analyzer's cap.+private const val SEGMENT_INPUT_MAX_SIDE = 512++// The shader's tap spacing is in surface pixels and was tuned against a phone-sized viewfinder, so+// running it straight on a 12MP still would both under-blur relative to the preview and spread the+// fixed 13 taps far enough apart to ghost. Instead blur a viewfinder-sized copy with the exact+// preview parameters and scale the (already soft) result back up when compositing.+private const val BLUR_LONG_SIDE = 1440++/**+ * Bakes the portrait bokeh the viewfinder previews into a captured still.+ *+ * Owns its own [PortraitSegmenter] (created on first use) because the preview's instance lives in+ * [BokehAnalyzer], which is disposed with the composable and runs on a different thread.+ */+class StillBokehRenderer(private val context: Context) : AutoCloseable {++    private var segmenter: PortraitSegmenter? = null+    @Volatile private var closed = false++    /**+     * Returns [src] with its background blurred, the warmth/shadows matrix baked in and the frame+     * mirrored when [mirror] is set — i.e. everything the preview applied on top of the raw frame.+     * [src] is expected in sensor orientation (rotation left to the EXIF tag, as the rest of the+     * capture path does), with [rotationDegrees] describing how far it has to be rotated to sit+     * upright; segmentation runs on an upright copy since the model expects upright subjects.+     *+     * Recycles [src] and returns the new bitmap on success. Returns null (leaving [src] intact for+     * the caller to fall back on) if segmentation or the GPU pass fails.+     */+    @Synchronized+    fun render(+        src: Bitmap,+        rotationDegrees: Int,+        strength: Float,+        warmth: Float,+        shadows: Float,+        mirror: Boolean,+    ): Bitmap? {+        if (closed) return null+        val mask = try {+            buildMask(src, rotationDegrees)+        } catch (e: Throwable) {+            Log.e("StillBokeh", "segmentation failed", e)+            return null+        }++        // Blurred background, viewfinder-sized: alpha is punched out where the subject is so it can+        // be laid straight over the sharp frame.+        val background = try {+            blurBackground(src, mask, strength)+        } catch (e: Throwable) {+            Log.e("StillBokeh", "blur pass failed", e)+            null+        }+        mask.recycle()+        if (background == null) return null++        return try {+            val out = Bitmap.createBitmap(src.width, src.height, Bitmap.Config.ARGB_8888)+            val canvas = Canvas(out)+            if (mirror) canvas.scale(-1f, 1f, src.width / 2f, src.height / 2f)+            canvas.drawBitmap(src, 0f, 0f, Paint().apply {+                colorFilter = ColorMatrixColorFilter(buildColorAdjustmentMatrix(warmth, shadows))+            })+            // Upscaling the blurred background costs no detail – it has none left – and bilinear+            // filtering also smooths the 256px mask's alpha edge in the process.+            canvas.drawBitmap(+                background,+                null,+                Rect(0, 0, src.width, src.height),+                Paint().apply { isFilterBitmap = true }+            )+            src.recycle()+            out+        } catch (e: Throwable) {+            Log.e("StillBokeh", "composite failed", e)+            null+        } finally {+            background.recycle()+        }+    }++    @Synchronized+    override fun close() {+        closed = true+        try { segmenter?.close() } catch (_: Exception) {}+        segmenter = null+    }++    /**+     * Runs the segmenter on a downscaled, upright copy of [src] and returns the softened mask+     * rotated back into [src]'s orientation.+     */+    private fun buildMask(src: Bitmap, rotationDegrees: Int): Bitmap {+        val seg = segmenter ?: PortraitSegmenter(context, "erdnet.param", "erdnet.bin")+            .also { segmenter = it }++        // Both helpers hand back their input when there is nothing to do, so only recycle the+        // intermediates we actually allocated – never the caller's bitmap.+        val downscaled = scaleToMaxSide(src, SEGMENT_INPUT_MAX_SIDE)+        val upright = rotate(downscaled, rotationDegrees.toFloat())+        if (downscaled !== src && downscaled !== upright) downscaled.recycle()++        val result = try {+            seg.segment(upright)+        } finally {+            if (upright !== src) upright.recycle()+        }++        val w = result.width+        val h = result.height+        val softened = blurMask(result.mask, w, h, FloatArray(w * h), FloatArray(w * h))+        val mask = maskToBitmap(softened, w, h, IntArray(w * h))++        val sensorSpace = rotate(mask, -rotationDegrees.toFloat())+        if (sensorSpace !== mask) mask.recycle()+        return sensorSpace+    }++    /**+     * Renders the bokeh shader over a viewfinder-sized copy of [src], then clears the subject out+     * of it (DST_OUT against the mask's alpha) so only the blurred background is left.+     */+    private fun blurBackground(src: Bitmap, mask: Bitmap, strength: Float): Bitmap? {+        val scale = min(1f, BLUR_LONG_SIDE.toFloat() / max(src.width, src.height))+        val small = if (scale < 1f) {+            Bitmap.createScaledBitmap(+                src,+                (src.width * scale).roundToInt().coerceAtLeast(1),+                (src.height * scale).roundToInt().coerceAtLeast(1),+                true+            )+        } else {+            src+        }+        // Preview parameters verbatim; the trailing factor only matters for stills whose long side+        // came in under BLUR_LONG_SIDE and so could not be scaled to the viewfinder's pixel pitch.+        val blurScale = bokehBlurScale(strength) *+            (max(small.width, small.height).toFloat() / BLUR_LONG_SIDE)++        val blurred = try {+            renderBlur(small, blurScale)+        } finally {+            if (small !== src) small.recycle()+        }+        if (blurred == null) return null++        Canvas(blurred).drawBitmap(+            mask,+            null,+            Rect(0, 0, blurred.width, blurred.height),+            Paint().apply {+                isFilterBitmap = true+                xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)+            }+        )+        return blurred+    }++    /**+     * Draws [src] through [BOKEH_SHADER] into an offscreen GPU surface — AGSL only runs on a+     * hardware canvas, so there is a HardwareRenderer/ImageReader pair rather than a plain Canvas.+     * The shader samples [src] through a CLAMP BitmapShader (instead of the preview's RenderEffect)+     * so taps past the frame edge repeat the border rather than fading the edges to transparent.+     */+    private fun renderBlur(src: Bitmap, blurScale: Float): Bitmap? {+        val w = src.width+        val h = src.height+        val reader = ImageReader.newInstance(+            w, h, PixelFormat.RGBA_8888, 1,+            HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT+        )+        val node = RenderNode("still-bokeh")+        val renderer = HardwareRenderer()+        try {+            renderer.setSurface(reader.surface)+            renderer.setContentRoot(node)+            node.setPosition(0, 0, w, h)++            val shader = RuntimeShader(BOKEH_SHADER)+            shader.setInputShader(+                "cameraInput",+                BitmapShader(src, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)+            )+            // Background-only pass: a fully transparent mask makes the shader's mix() return the+            // blur everywhere. The subject is restored by compositing this over the sharp frame.+            shader.setInputShader("alphaMask", BitmapShader(TRANSPARENT_1X1, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP))+            shader.setFloatUniform("blurScale", blurScale)++            val canvas = node.beginRecording()+            canvas.drawRect(0f, 0f, w.toFloat(), h.toFloat(), Paint().apply { this.shader = shader })+            node.endRecording()+            renderer.createRenderRequest().setWaitForPresent(true).syncAndDraw()++            val image = reader.acquireNextImage() ?: return null+            return image.use { img ->+                val buffer = img.hardwareBuffer ?: return@use null+                buffer.use { hb ->+                    val hardware = Bitmap.wrapHardwareBuffer(hb, null) ?: return@use null+                    hardware.copy(Bitmap.Config.ARGB_8888, true).also { hardware.recycle() }+                }+            }+        } finally {+            node.discardDisplayList()+            renderer.destroy()+            reader.close()+        }+    }++    private fun scaleToMaxSide(src: Bitmap, maxSide: Int): Bitmap {+        val longest = max(src.width, src.height)+        if (longest <= maxSide) return src+        val scale = maxSide.toFloat() / longest+        return Bitmap.createScaledBitmap(+            src,+            (src.width * scale).roundToInt().coerceAtLeast(1),+            (src.height * scale).roundToInt().coerceAtLeast(1),+            true+        )+    }++    private fun rotate(src: Bitmap, degrees: Float): Bitmap {+        if (degrees % 360f == 0f) return src+        val matrix = Matrix().apply { postRotate(degrees) }+        return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true)+    }++    private companion object {+        val TRANSPARENT_1X1: Bitmap =+            Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.TRANSPARENT) }+    }+}
everysync/build.gradle.kts
diff --git a/everysync/build.gradle.kts b/everysync/build.gradle.ktsindex 44035386a6..8bd3014e97 100644--- a/everysync/build.gradle.kts+++ b/everysync/build.gradle.kts@@ -50,7 +50,7 @@ dependencies {     // Background sync     implementation(libs.androidx.work.runtime.ktx) -    // ktor client (custom WebDAV methods + JSON)+    // HTTP client (custom WebDAV methods + JSON)     implementation(project(":library:network"))  }
everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.ktindex b50c102927..e64c19e741 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt@@ -27,7 +27,7 @@ data class DavCollection(  /**  * WebDAV client for CalDAV (RFC 4791) and CardDAV (RFC 6352) over the shared- * ktor [NetworkClient], using the custom methods PROPFIND / REPORT / PUT / DELETE.+ * [NetworkClient], using the custom methods PROPFIND / REPORT / PUT / DELETE.  * Change detection uses collection ctags and per-resource ETags; the caller  * decides what to re-fetch.  */
findfamily/build.gradle.kts
diff --git a/findfamily/build.gradle.kts b/findfamily/build.gradle.ktsindex d2d6c2f45a..9d578e0cf6 100644--- a/findfamily/build.gradle.kts+++ b/findfamily/build.gradle.kts@@ -16,7 +16,7 @@ android {  dependencies { -    // ktor+    // HTTP + JSON     implementation(project(":library:network"))     implementation(project(":library:e2ee-p2p")) 
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 7a694aae09..e29460a0a7 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -1,96 +1,149 @@ [versions]-# rhino 1.9.0 requires Android minSDK >= 26; rhino-engine only published for 1.8.x-rhino = "1.8.1"-jsr305 = "3.0.2"-protobufJavalite = "4.35.0"-protobufPlugin = "0.10.0"-quickjs = "1.0.5"-brotli = "0.1.2"-# Build & Core Language++# =============================================================================+# GOOGLE / ANDROID / JETBRAINS+# =============================================================================++# Build & tooling agp = "9.4.0-alpha04"-flatgeobuf = "3.29.0" kotlin = "2.4.0" kotlinGradlePlugin = "2.3.20" ksp = "2.3.10"+protobufPlugin = "0.10.0"+protoc = "4.28.3"+desugarJdkLibs = "2.1.5" -# Instrumented screenshot tests (metadata generation)-junit = "4.13.2"-androidxTestRunner = "1.7.0"-androidxTestExtJunit = "1.3.0"+# Kotlin stdlib ecosystem (JetBrains)+kotlinxCoroutines = "1.11.0"+kotlinxSerializationJson = "1.11.0"+kotlinxDatetime = "0.8.0" -# AndroidX Core & Lifecycle+# AndroidX – core & lifecycle coreKtx = "1.19.0"-# litertlm 0.14.0 is compiled against coroutines 1.11.0 (close$default moved onto-# the SendChannel interface via -Xjvm-default=all); older versions crash its JNI-# callback with NoSuchMethodError. Request it directly so it wins conflict resolution.-kotlinxCoroutines = "1.11.0"+fragmentKtx = "1.9.0-alpha02" lifecycle = "2.11.0"-litertlmAndroid = "0.14.0"-sqlcipherAndroid = "4.17.0" sqlite = "2.7.0" workRuntimeKtx = "2.11.2" datastorePreferences = "1.3.0-alpha09" -# Compose & UI Foundations+# AndroidX – Compose & UI composeBom = "2026.06.01" activityCompose = "1.13.0" material3 = "1.5.0-alpha23"+material3AdaptiveNavigationSuite = "1.5.0-alpha23"+foundation = "1.12.0-beta02" wearComposeMaterial = "1.7.0-alpha05" -# Navigation+# AndroidX – navigation navigation3 = "1.2.0-alpha05" adaptiveNavigation3 = "1.3.0-rc01" -# Media & Images+# AndroidX – media, camera & images media3Exoplayer = "1.11.0-beta01"-coilCompose = "2.7.0"-exifinterface = "1.4.2" camerax = "1.7.0-alpha02"-jsoup = "1.22.2"-webkit = "1.17.0-alpha03"+exifinterface = "1.4.2" -# Networking & Data-ktor = "3.5.1" # TODO: remove after :messages migrates to :library:network (RpcClient, GVoice, Meta, Signal, WhatsApp)-okio = "3.17.0" # isolated: contacts/files VCF+zip + messages MetaMqtt/Signal/WhatsApp ByteString – NOT networking-okhttp = "4.12.0" # isolated: media3-datasource-okhttp (youpipe player) + Vonage SDK (dooraccess) + messages GVoice TLS-kotlinxSerializationJson = "1.11.0"-kotlinxDatetime = "0.8.0"+# AndroidX – storage room = "2.8.4"-autofill = "1.3.0"-credentials = "1.7.0-alpha02"++# AndroidX – widgets, web & browser+glance = "1.3.0-alpha02"+webkit = "1.17.0-alpha03" browser = "1.9.0" -# Special Features (PDF, Maps, Health, Crypto)+# AndroidX – security, identity & health biometric = "1.4.0-alpha07"-glance = "1.3.0-alpha02"+credentials = "1.7.0-alpha02"+autofill = "1.3.0" connectClient = "1.2.0-alpha04"-cryptographyCore = "0.6.0"-libphonenumber = "9.0.34"-material3AdaptiveNavigationSuite = "1.5.0-alpha23"-maplibre = "0.13.0"-foundation = "1.12.0-beta02"++# AndroidX – ink ink = "1.1.0-alpha04"++# AndroidX – testing+androidxTestRunner = "1.7.0"+androidxTestExtJunit = "1.3.0"++# Google libraries protobuf = "4.36.0-RC1"-keepassJava2 = "2.2.4"+protobufJavalite = "4.35.0"+jsr305 = "3.0.2" zxing = "3.5.4"-bouncycastle = "1.85"+libphonenumber = "9.0.34"+litertlmAndroid = "0.14.0"+brotli = "0.1.2"++# =============================================================================+# THIRD PARTY+# =============================================================================++# Networking (Square)+okio = "3.17.0" # isolated: contacts/files VCF+zip + messages MetaMqtt/Signal/WhatsApp ByteString – NOT networking+okhttp = "4.12.0" # isolated: media3-datasource-okhttp (youpipe player) + Vonage SDK (dooraccess)++# Images+coilCompose = "2.7.0"++# Maps & geospatial+maplibre = "0.13.0"+flatgeobuf = "3.29.0"++# JavaScript engines & HTML+# rhino 1.9.0 requires Android minSDK >= 26; rhino-engine only published for 1.8.x+rhino = "1.8.1"+quickjs = "1.0.5"+jsoup = "1.22.2"++# On-device AI onnxruntimeAndroid = "1.27.0"-jakartaMail = "2.0.3"-stockfishLibrary = "1.1.0"-ncnnAndroid = "1.6.1"-kxml2 = "2.3.0"++# Crypto, security & credential storage+cryptographyCore = "0.6.0"+sqlcipherAndroid = "4.17.0" libsignalAndroid = "0.86.5" signalProtocolJava = "2.8.1"-fragmentKtx = "1.9.0-alpha02"-desugarJdkLibs = "2.1.5"-protoc = "4.28.3"++# Mail & XML+jakartaMail = "2.0.3"+kxml2 = "2.3.0"++# Payments, telephony & auth+stripe = "21.12.0" vonageVoice = "2.6.0" appauth = "0.11.1"-stripe = "21.12.0"++# Own libraries (vayun-mathur, via JitPack)+stockfishLibrary = "1.1.0"+ncnnAndroid = "1.6.1"++# Testing+junit = "4.13.2"+gplayapi = "3.6.4"++# Gradle plugins shadow = "9.0.0"  [libraries]-# AndroidX Core & Lifecycle++# =============================================================================+# GOOGLE / ANDROID / JETBRAINS+# =============================================================================++# Gradle plugin artifacts (build-logic classpath)+gradle = { module = "com.android.tools.build:gradle", version.ref = "agp" }+kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlinGradlePlugin" }+kotlin-compose-gradle = { module = "org.jetbrains.kotlin:compose-compiler-gradle-plugin", version.ref = "kotlin" }+kotlin-serialization-gradle = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" }+symbol-processing-gradle-plugin = { module = "com.google.devtools.ksp:symbol-processing-gradle-plugin", version.ref = "ksp" }+desugar-jdk-libs = { module = "com.android.tools:desugar_jdk_libs", version.ref = "desugarJdkLibs" }++# Kotlin stdlib ecosystem (JetBrains)+kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }+kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }+kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinxDatetime" }+kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlin" }++# AndroidX – core & lifecycle androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } androidx-fragment-ktx = { group = "androidx.fragment", name = "fragment-ktx", version.ref = "fragmentKtx" } androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }@@ -99,128 +152,153 @@ androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "l androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" } androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" } androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }-androidx-biometric = { module = "androidx.biometric:biometric", version.ref = "biometric" }-androidx-exifinterface = { module = "androidx.exifinterface:exifinterface", version.ref = "exifinterface" }-androidx-camera-core = { group = "androidx.camera", name = "camera-core", version.ref = "camerax" }-androidx-camera-camera2 = { group = "androidx.camera", name = "camera-camera2", version.ref = "camerax" }-androidx-camera-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "camerax" }-androidx-camera-view = { group = "androidx.camera", name = "camera-view", version.ref = "camerax" }-androidx-camera-video = { group = "androidx.camera", name = "camera-video", version.ref = "camerax" }-androidx-camera-compose = { group = "androidx.camera", name = "camera-compose", version.ref = "camerax" }-androidx-camera-extensions = { group = "androidx.camera", name = "camera-extensions", version.ref = "camerax" }-androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" }-jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" }-rhino = { module = "org.mozilla:rhino", version.ref = "rhino" }-rhino-engine = { module = "org.mozilla:rhino-engine", version.ref = "rhino" }-google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" }-protobuf-javalite = { module = "com.google.protobuf:protobuf-javalite", version.ref = "protobufJavalite" }-quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" }-brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" }--# Instrumented screenshot tests (metadata generation)-junit = { module = "junit:junit", version.ref = "junit" }-androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }-androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExtJunit" }-androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }-androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" } -# Jetpack Compose (BOM Managed)+# AndroidX – Compose & UI (unversioned entries come from the BOM) androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" } androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }+androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundation" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" }+androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }+androidx-compose-material3-adaptive-navigation-suite = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite", version.ref = "material3AdaptiveNavigationSuite" } androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" } androidx-wear-compose-material = { group = "androidx.wear.compose", name = "compose-material", version.ref = "wearComposeMaterial" } androidx-wear-compose-foundation = { group = "androidx.wear.compose", name = "compose-foundation", version.ref = "wearComposeMaterial" }-# Navigation++# AndroidX – navigation androidx-navigation3-runtime = { group = "androidx.navigation3", name = "navigation3-runtime", version.ref = "navigation3" } androidx-navigation3-ui = { group = "androidx.navigation3", name = "navigation3-ui", version.ref = "navigation3" } androidx-compose-adaptive-navigation3 = { group = "androidx.compose.material3.adaptive", name = "adaptive-navigation3", version.ref = "adaptiveNavigation3" }-androidx-compose-material3-adaptive-navigation-suite = { group = "androidx.compose.material3", name = "material3-adaptive-navigation-suite", version.ref = "material3AdaptiveNavigationSuite" } -# Media3 (ExoPlayer & Session)+# AndroidX – Media3 (ExoPlayer & session) androidx-media3-exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "media3Exoplayer" } androidx-media3-exoplayer-dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "media3Exoplayer" } androidx-media3-session = { module = "androidx.media3:media3-session", version.ref = "media3Exoplayer" } androidx-media3-ui-compose-material3 = { module = "androidx.media3:media3-ui-compose-material3", version.ref = "media3Exoplayer" } androidx-media3-datasource-okhttp = { group = "androidx.media3", name = "media3-datasource-okhttp", version.ref = "media3Exoplayer" } -# Images & Visuals-coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" }-coil-svg = { module = "io.coil-kt:coil-svg", version.ref = "coilCompose" }-coil-video = { module = "io.coil-kt:coil-video", version.ref = "coilCompose" }-kotlin-gradle-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlinGradlePlugin" }-litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" }-kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }--# Maps – spatialk comes transitively via maplibre-compose (used by :maps), no direct dep needed-maplibre-compose = { module = "org.maplibre.compose:maplibre-compose", version.ref = "maplibre" }-flatgeobuf = { module = "org.wololo:flatgeobuf", version.ref = "flatgeobuf" }+# AndroidX – CameraX & images+androidx-camera-core = { group = "androidx.camera", name = "camera-core", version.ref = "camerax" }+androidx-camera-camera2 = { group = "androidx.camera", name = "camera-camera2", version.ref = "camerax" }+androidx-camera-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "camerax" }+androidx-camera-view = { group = "androidx.camera", name = "camera-view", version.ref = "camerax" }+androidx-camera-video = { group = "androidx.camera", name = "camera-video", version.ref = "camerax" }+androidx-camera-compose = { group = "androidx.camera", name = "camera-compose", version.ref = "camerax" }+androidx-camera-extensions = { group = "androidx.camera", name = "camera-extensions", version.ref = "camerax" }+androidx-exifinterface = { module = "androidx.exifinterface:exifinterface", version.ref = "exifinterface" } -# On-device AI-onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntimeAndroid" }+# AndroidX – Room+androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }+androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }+androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" } -# App Widgets (Glance)+# AndroidX – app widgets (Glance) androidx-glance = { module = "androidx.glance:glance", version.ref = "glance" } androidx-glance-appwidget = { module = "androidx.glance:glance-appwidget", version.ref = "glance" } androidx-glance-material3 = { module = "androidx.glance:glance-material3", version.ref = "glance" } -# Ktor & Networking – TODO: migrate :messages (core/cio/okhttp) to :library:network, then remove ktor version + libs-ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }-ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" }-ktor-client-okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.ref = "ktor" }-okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" } # isolated: contacts/files + messages ByteString-okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } # isolated: media3-datasource-okhttp + Vonage SDK--# Data Storage & Serialization-androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }-androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }-androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }-kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" }-kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinxDatetime" }+# AndroidX – web & browser+androidx-webkit = { group = "androidx.webkit", name = "webkit", version.ref = "webkit" }+androidx-browser = { group = "androidx.browser", name = "browser", version.ref = "browser" } -# Specialized Utilities-androidx-connect-client = { module = "androidx.health.connect:connect-client", version.ref = "connectClient" }-cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptographyCore" }-cryptography-provider-jdk = { module = "dev.whyoleg.cryptography:cryptography-provider-jdk", version.ref = "cryptographyCore" }-libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" }-jakarta-mail = { module = "org.eclipse.angus:jakarta.mail", version.ref = "jakartaMail" }-androidx-autofill = { group = "androidx.autofill", name = "autofill", version.ref = "autofill" }+# AndroidX – security, identity & health+androidx-biometric = { module = "androidx.biometric:biometric", version.ref = "biometric" } androidx-credentials-lib = { group = "androidx.credentials", name = "credentials", version.ref = "credentials" }-androidx-browser = { group = "androidx.browser", name = "browser", version.ref = "browser" }+androidx-autofill = { group = "androidx.autofill", name = "autofill", version.ref = "autofill" }+androidx-connect-client = { module = "androidx.health.connect:connect-client", version.ref = "connectClient" } -gradle = { module = "com.android.tools.build:gradle", version.ref = "agp" }-kotlin-compose-gradle = { module = "org.jetbrains.kotlin:compose-compiler-gradle-plugin", version.ref = "kotlin" }-kotlin-serialization-gradle = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" }-sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" }-symbol-processing-gradle-plugin = { module = "com.google.devtools.ksp:symbol-processing-gradle-plugin", version.ref = "ksp" }-androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundation" }+# AndroidX – ink androidx-ink-authoring = { group = "androidx.ink", name = "ink-authoring", version.ref = "ink" } androidx-ink-brush = { group = "androidx.ink", name = "ink-brush", version.ref = "ink" } androidx-ink-geometry = { group = "androidx.ink", name = "ink-geometry", version.ref = "ink" } androidx-ink-strokes = { group = "androidx.ink", name = "ink-strokes", version.ref = "ink" } androidx-ink-rendering = { group = "androidx.ink", name = "ink-rendering", version.ref = "ink" }++# AndroidX – testing+androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidxTestRunner" }+androidx-test-ext-junit = { module = "androidx.test.ext:junit", version.ref = "androidxTestExtJunit" }+androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }+androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }++# Google libraries protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" }+protobuf-javalite = { module = "com.google.protobuf:protobuf-javalite", version.ref = "protobufJavalite" }+google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" }-keepassjava2-dom = { module = "org.linguafranca.pwdb:KeePassJava2-dom", version.ref = "keepassJava2" }-bouncycastle = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }-stockfish-library = { module = "com.github.vayun-mathur:Stockfish-Library", version.ref = "stockfishLibrary" }-ncnn-android = { module = "com.github.vayun-mathur:ncnn-android", version.ref = "ncnnAndroid" }-kxml2 = { module = "net.sf.kxml:kxml2", version.ref = "kxml2" }+libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" }+litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" }+brotli-dec = { module = "org.brotli:dec", version.ref = "brotli" }++# =============================================================================+# THIRD PARTY+# =============================================================================++# Networking (Square)+okio = { group = "com.squareup.okio", name = "okio", version.ref = "okio" } # isolated: contacts/files + messages ByteString+okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } # isolated: media3-datasource-okhttp + Vonage SDK++# Images+coil-compose = { module = "io.coil-kt:coil-compose", version.ref = "coilCompose" }+coil-svg = { module = "io.coil-kt:coil-svg", version.ref = "coilCompose" }+coil-video = { module = "io.coil-kt:coil-video", version.ref = "coilCompose" }++# Maps & geospatial+maplibre-compose = { module = "org.maplibre.compose:maplibre-compose", version.ref = "maplibre" }+flatgeobuf = { module = "org.wololo:flatgeobuf", version.ref = "flatgeobuf" }++# JavaScript engines & HTML+# rhino 1.9.0 requires Android minSDK >= 26; rhino-engine only published for 1.8.x+rhino = { module = "org.mozilla:rhino", version.ref = "rhino" }+rhino-engine = { module = "org.mozilla:rhino-engine", version.ref = "rhino" }+quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" }+jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" }++# On-device AI+onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntimeAndroid" }++# Crypto, security & credential storage+cryptography-core = { module = "dev.whyoleg.cryptography:cryptography-core", version.ref = "cryptographyCore" }+cryptography-provider-jdk = { module = "dev.whyoleg.cryptography:cryptography-provider-jdk", version.ref = "cryptographyCore" }+sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" } libsignal-android = { module = "org.signal:libsignal-android", version.ref = "libsignalAndroid" } signal-protocol-java = { module = "org.whispersystems:signal-protocol-java", version.ref = "signalProtocolJ

Diff truncated.