Modern Apps git

← Modern-Apps.git

photos: fix delayed person names and the main-thread/IO starvation

Commit
eec2f697139519ebaae234d2d3c52aee6954dc96
Author
vayun-mathur <[email protected]>
When
2026-08-23 04:37 UTC (3 months ago)
Parents
3ab5ead

Diff

library/image/src/main/java/com/vayunmathur/library/image/DiskCache.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/DiskCache.kt b/library/image/src/main/java/com/vayunmathur/library/image/DiskCache.ktindex 1598ed7509..e8f3e7239d 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/DiskCache.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/DiskCache.kt@@ -1,6 +1,5 @@ package com.vayunmathur.library.image -import android.content.Context import com.vayunmathur.library.image.util.ensureExists import com.vayunmathur.library.image.util.sha256 import java.io.File@@ -14,70 +13,192 @@ import kotlin.concurrent.withLock  * - Eviction: oldest lastModified first when over size limit.  *  * Mirrors Coil diskCache { directory(cacheDir/image_cache).maxSizePercent(0.05) } shape.+ *+ * Locking is striped per key rather than global: during a fast scroll, dozens of+ * unrelated thumbnails are read and written at once, and a single lock made them+ * queue behind each other (and behind whichever one was doing a full directory+ * scan). Only [trim] is genuinely global, and it takes its own lock.  */ class DiskCache internal constructor(     private val directory: File,     private val maxSizeBytes: Long, ) {-    private val lock = ReentrantLock()+    private val stripes = Array(STRIPE_COUNT) { ReentrantLock() }+    private val trimLock = ReentrantLock()++    private val sizeLock = Any()+    private var totalBytes = 0L+    private var sizeSeeded = false      init {         directory.ensureExists()     } -    fun get(key: String): ByteArray? = lock.withLock {+    fun get(key: String): ByteArray? {         val file = fileFor(key)-        if (!file.exists()) return null+        val bytes = stripeFor(key).withLock {+            if (!file.exists()) return null+            try {+                file.readBytes()+            } catch (_: Exception) {+                null+            }+        } ?: return null++        // Best-effort LRU touch, outside the lock and rate-limited. This used to be+        // a filesystem *write* on every single read, performed while holding the+        // one lock every other read and write also needed.         try {-            file.setLastModified(System.currentTimeMillis())-            file.readBytes()+            val now = System.currentTimeMillis()+            if (now - file.lastModified() > TOUCH_INTERVAL_MS) file.setLastModified(now)         } catch (_: Exception) {-            null         }+        return bytes     }      fun put(key: String, bytes: ByteArray) {-        lock.withLock {+        // Seeded before the write lands, so this file is counted by its delta and not+        // a second time by the seeding scan.+        ensureSeeded()++        val file = fileFor(key)+        val delta = stripeFor(key).withLock {             try {                 directory.ensureExists()-                val file = fileFor(key)+                val previous = if (file.exists()) file.length() else 0L                 // atomic write via temp-                val tmp = File(directory, "${file.name}.tmp_${System.nanoTime()}")+                val tmp = File(directory, "${file.name}$TMP_MARKER${System.nanoTime()}")                 tmp.writeBytes(bytes)                 if (file.exists()) file.delete()-                tmp.renameTo(file)-                trimIfNeededLocked()+                if (!tmp.renameTo(file)) {+                    tmp.delete()+                    // The old file was already deleted above, so account for it.+                    -previous+                } else {+                    bytes.size.toLong() - previous+                }             } catch (_: Exception) {+                return             }         }++        // Total size is maintained incrementally, so a write no longer costs a+        // listFiles() + sumOf { length() } + sortedBy { lastModified() } over the+        // whole directory. That scan now happens only when actually trimming.+        if (addToTotal(delta) > maxSizeBytes) trim()     } -    fun remove(key: String) = lock.withLock {-        try { fileFor(key).delete() } catch (_: Exception) {}+    fun remove(key: String) {+        ensureSeeded()+        val file = fileFor(key)+        stripeFor(key).withLock {+            try {+                val len = if (file.exists()) file.length() else 0L+                if (file.delete()) addToTotal(-len)+            } catch (_: Exception) {}+        }     } -    fun clear() = lock.withLock {-        try { directory.listFiles()?.forEach { it.delete() } } catch (_: Exception) {}+    /**+     * Removes every entry.+     *+     * Takes all stripes (in a fixed order, and never while one is already held) so an+     * in-flight [put] cannot rename its temp file into place after the sweep and+     * survive a clear.+     */+    fun clear() {+        withAllStripes {+            trimLock.withLock {+                try {+                    directory.listFiles()?.forEach { it.delete() }+                    setTotal(0L)+                } catch (_: Exception) {}+            }+        }     }      private fun fileFor(key: String): File = File(directory, key.sha256()) -    private fun trimIfNeededLocked() {+    private fun stripeFor(key: String): ReentrantLock {+        val h = key.hashCode()+        val spread = h xor (h ushr 16)+        return stripes[(spread and Int.MAX_VALUE) % STRIPE_COUNT]+    }++    private fun <T> withAllStripes(block: () -> T): T {+        stripes.forEach { it.lock() }         try {-            val files = directory.listFiles()?.filter { it.isFile && !it.name.endsWith(".tmp") } ?: return-            var total = files.sumOf { it.length() }-            if (total <= maxSizeBytes) return+            return block()+        } finally {+            stripes.reversed().forEach { it.unlock() }+        }+    }++    /** Measures the directory once, so [addToTotal] only ever applies deltas. */+    private fun ensureSeeded() = synchronized(sizeLock) {+        if (!sizeSeeded) {+            totalBytes = measureDirectory()+            sizeSeeded = true+        }+    }++    private fun addToTotal(delta: Long): Long = synchronized(sizeLock) {+        totalBytes = (totalBytes + delta).coerceAtLeast(0L)+        totalBytes+    }++    private fun setTotal(value: Long) = synchronized(sizeLock) {+        totalBytes = value.coerceAtLeast(0L)+        sizeSeeded = true+    }++    private fun measureDirectory(): Long = try {+        directory.listFiles()?.filter { it.isFile && !it.name.contains(TMP_MARKER) }+            ?.sumOf { it.length() } ?: 0L+    } catch (_: Exception) {+        0L+    }++    private fun trim() {+        // Another thread is already trimming; its pass covers this overflow too.+        if (!trimLock.tryLock()) return+        try {+            // Note the TMP_MARKER exclusion: half-written files are not part of the+            // cache and must not be counted or deleted from under a writer.+            val files = directory.listFiles()?.filter { it.isFile && !it.name.contains(TMP_MARKER) }+                ?: return+            var remaining = files.sumOf { it.length() }+            if (remaining <= maxSizeBytes) return             // oldest first-            val sorted = files.sortedBy { it.lastModified() }-            for (f in sorted) {-                if (total <= maxSizeBytes) break+            var freed = 0L+            for (f in files.sortedBy { it.lastModified() }) {+                if (remaining - freed <= maxSizeBytes) break                 val len = f.length()-                if (f.delete()) total -= len+                if (f.delete()) freed += len             }+            // Applied as a delta, not as an absolute from the (already stale) scan+            // above: writes that completed while this pass ran must keep their deltas.+            addToTotal(-freed)         } catch (_: Exception) {+        } finally {+            trimLock.unlock()         }     } +    private companion object {+        const val STRIPE_COUNT = 16++        /** Marks in-progress writes so they are never counted or evicted. */+        const val TMP_MARKER = ".tmp_"++        /**+         * Smallest gap between LRU touches of the same file. Eviction order only+         * needs to be roughly right, and a hot key would otherwise pay a+         * filesystem write on every read.+         */+        const val TOUCH_INTERVAL_MS = 60_000L+    }+     class Builder {         private var directory: File? = null         private var maxSizePercent: Double = 0.02
library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt b/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.ktindex 920b9f6377..f0a98109a2 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/ImageLoader.kt@@ -2,6 +2,7 @@ package com.vayunmathur.library.image  import android.content.Context import android.graphics.Bitmap+import android.net.Uri import com.vayunmathur.library.image.decoders.BitmapDecoder import com.vayunmathur.library.image.decoders.SvgDecoder import com.vayunmathur.library.image.decoders.VideoFrameDecoder@@ -13,8 +14,14 @@ import com.vayunmathur.library.image.fetchers.FetchResult import com.vayunmathur.library.image.fetchers.FileFetcher import com.vayunmathur.library.image.fetchers.Fetcher import com.vayunmathur.library.image.fetchers.HttpFetcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.async import kotlinx.coroutines.withContext+import java.io.File  /**  * Replacement for `coil.ImageLoader`. Uses:@@ -31,6 +38,17 @@ class ImageLoader private constructor(     private val respectCacheHeaders: Boolean = false, ) { +    /** Owns in-flight work so it outlives any one caller's cancellation. */+    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())++    /**+     * Requests currently being fetched/decoded, keyed by cache key.+     *+     * A grid scrolling past several tiles of the same image used to fetch and decode+     * it once per tile; now the first request does the work and the rest await it.+     */+    private val inFlight = mutableMapOf<String, Deferred<ImageResult>>()+     companion object {         @Volatile         private var singleton: ImageLoader? = null@@ -46,34 +64,107 @@ class ImageLoader private constructor(         }     } +    private fun dataKey(request: ImageRequest): String = when (val d = request.data) {+        null -> "null"+        is String -> d+        is ByteArray -> "bytes_${d.size}_${d.take(16).hashCode()}"+        is Bitmap -> "bitmap_${d.width}x${d.height}_${d.hashCode()}"+        else -> d.toString()+    }+     private fun computeCacheKey(request: ImageRequest): String {-        request.memoryCacheKey?.let { return it }-        request.diskCacheKey?.let { return it }-        val dataStr = when (val d = request.data) {-            null -> "null"-            is String -> d-            is ByteArray -> "bytes_${d.size}_${d.take(16).hashCode()}"-            is Bitmap -> "bitmap_${d.width}x${d.height}_${d.hashCode()}"-            else -> d.toString()-        }-        val transKey = request.transformations.joinToString("|") { it.cacheKey }         val sizeKey = request.size?.let { "${it.width}x${it.height}" } ?: "orig"+        val transKey = request.transformations.joinToString("|") { it.cacheKey }         val videoKey = request.videoFrameMillis?.let { "vf_$it" } ?: ""-        return "$dataStr|$sizeKey|$transKey|$videoKey"+        // An explicit key names the *data*; size and transformations still have to be+        // folded in. Returning a caller's key verbatim meant every caller was+        // responsible for encoding its own size, and a caller that didn't (a 256 px+        // thumbnail key that says nothing about 256) collided by name with a request+        // for the same image at a different size and was served the wrong bitmap.+        val base = request.memoryCacheKey ?: request.diskCacheKey ?: dataKey(request)+        return "$base|$sizeKey|$transKey|$videoKey"     } -    suspend fun execute(request: ImageRequest): ImageResult = withContext(Dispatchers.IO) {-        val context = request.context ?: appContext+    /**+     * True for data already sitting on this device's storage.+     *+     * The disk cache exists to avoid re-downloading; for a local file it only+     * duplicated the user's own photo library into `cacheDir` (at up to 5% of device+     * storage) to avoid reopening a file that is already there and cheap to reopen.+     */+    private fun isLocalData(data: Any?): Boolean = when (data) {+        is File -> true+        is Uri -> data.scheme.let { it == "content" || it == "file" || it == null }+        is String -> data.startsWith("content://") || data.startsWith("file://") || data.startsWith("/")+        else -> false+    }++    /**+     * Memory-cache lookup with no dispatch and no IO.+     *+     * [execute] is a suspend function that hops to [Dispatchers.IO] before it can+     * even check the memory cache, so a cached bitmap was never available in time+     * for the first frame. Callers on the main thread can use this to paint+     * immediately on a hit (see `AsyncImage`).+     */+    fun peekMemoryCache(request: ImageRequest): Bitmap? {+        if (request.data is Bitmap) return null+        return try {+            memoryCache?.get(computeCacheKey(request))?.takeIf { !it.isRecycled }+        } catch (_: Exception) {+            null+        }+    } +    suspend fun execute(request: ImageRequest): ImageResult {+        // A Bitmap request has nothing to fetch or cache; transform and return it.+        // Still dispatched, because a transformation allocates and draws a bitmap and+        // the caller is usually on the main thread.         if (request.data is Bitmap) {             val bmp = request.data-            val transformed = applyTransformations(bmp, request)-            return@withContext ImageResult.Success(transformed, isFromMemory = false, dataSource = ImageResult.DataSource.MEMORY)+            return withContext(Dispatchers.IO) {+                val transformed = applyTransformations(bmp, request)+                ImageResult.Success(transformed, isFromMemory = false, dataSource = ImageResult.DataSource.MEMORY)+            }         }          val cacheKey = computeCacheKey(request)+        peekMemoryCache(request)?.let {+            return ImageResult.Success(it, isFromMemory = true, dataSource = ImageResult.DataSource.MEMORY)+        }++        val deferred = synchronized(inFlight) {+            // `isCompleted`, not `isActive`: a CoroutineStart.LAZY Deferred sits in the+            // NEW state where isActive is false, so testing isActive would reject the+            // entry during exactly the window between registration and start() and let+            // a second caller duplicate the work.+            val existing = inFlight[cacheKey]?.takeIf { !it.isCompleted }+            if (existing != null) {+                existing+            } else {+                // LAZY so the entry is registered (and its cleanup hooked up) before+                // the work can start and try to remove itself.+                val started = scope.async(start = CoroutineStart.LAZY) { load(request, cacheKey) }+                inFlight[cacheKey] = started+                started.invokeOnCompletion {+                    synchronized(inFlight) {+                        // Only if still ours; a later request may have replaced it.+                        if (inFlight[cacheKey] === started) inFlight.remove(cacheKey)+                    }+                }+                started+            }+        }+        deferred.start()+        return deferred.await()+    }++    private suspend fun load(request: ImageRequest, cacheKey: String): ImageResult = withContext(Dispatchers.IO) {+        val context = request.context ?: appContext         val diskKey = request.diskCacheKey ?: cacheKey+        val isLocal = isLocalData(request.data) +        // Another coalesced request may have filled the cache while this one waited.         try {             memoryCache?.get(cacheKey)?.let { cached ->                 return@withContext ImageResult.Success(cached, isFromMemory = true, dataSource = ImageResult.DataSource.MEMORY)@@ -81,7 +172,7 @@ class ImageLoader private constructor(         } catch (_: Exception) {}          var diskBytes: ByteArray? = null-        if (diskCache != null) {+        if (diskCache != null && !isLocal) {             try {                 diskBytes = diskCache.get(diskKey)                 if (diskBytes != null) {@@ -121,6 +212,24 @@ class ImageLoader private constructor(                             fetchedBytes = result.bytes                             break                         }+                        is FetchResult.Source -> {+                            // Fast path: decode (and downsample) straight from the file.+                            val decodedFromSource =+                                BitmapDecoder.decode(result.decoderSource, request, request.allowHardware)+                            if (decodedFromSource != null) {+                                val transformed = applyTransformations(decodedFromSource, request)+                                try { memoryCache?.put(cacheKey, transformed) } catch (_: Exception) {}+                                return@withContext ImageResult.Success(transformed, isFromMemory = false, dataSource = ImageResult.DataSource.DISK)+                            }+                            // ImageDecoder can't read it (an SVG, or a video whose frame+                            // decoder needs the bytes): fall back to the byte path.+                            fetchedBytes = try {+                                result.openStream()?.use { it.readBytes() }+                            } catch (_: Exception) {+                                null+                            }+                            break+                        }                     }                 }             }@@ -151,7 +260,7 @@ class ImageLoader private constructor(          try { memoryCache?.put(cacheKey, transformed) } catch (_: Exception) {}         try {-            if (diskCache != null) {+            if (diskCache != null && !isLocal) {                 diskCache.put(diskKey, fetchedBytes)             }         } catch (_: Exception) {}
library/image/src/main/java/com/vayunmathur/library/image/MemoryCache.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/MemoryCache.kt b/library/image/src/main/java/com/vayunmathur/library/image/MemoryCache.ktindex 81e7daf8c1..4c243e5d38 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/MemoryCache.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/MemoryCache.kt@@ -1,6 +1,7 @@ package com.vayunmathur.library.image  import android.content.Context+import android.content.pm.ApplicationInfo import android.graphics.Bitmap import android.util.LruCache import com.vayunmathur.library.image.util.maxMemoryBytes@@ -42,7 +43,13 @@ class MemoryCache internal constructor(         fun build(): MemoryCache {             val maxBytes = maxSizeBytes ?: run {                 val am = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager-                val memClass = am.memoryClass * 1024 * 1024+                // An app that asked for android:largeHeap gets the large heap, so+                // sizing off memoryClass gave it a cache measured for a heap it+                // isn't using — small enough that a single full-resolution decode+                // could evict everything else.+                val isLargeHeap = (context.applicationInfo.flags and ApplicationInfo.FLAG_LARGE_HEAP) != 0+                val heapMb = if (isLargeHeap) am.largeMemoryClass else am.memoryClass+                val memClass = heapMb * 1024 * 1024                 (memClass * maxSizePercent).toInt().coerceAtLeast(4 * 1024 * 1024)             } 
library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt b/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.ktindex 4207edee52..6f7b58f81e 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/compose/AsyncImage.kt@@ -57,12 +57,26 @@ fun AsyncImage(         }     } -    val bitmapState = produceState<Bitmap?>(initialValue = null, key1 = request) {+    // Synchronous memory-cache probe. On a hit the bitmap is available before the+    // first frame, so a scrolled-in item paints immediately instead of showing an+    // empty box for a frame and re-running its crossfade over an image that was+    // already in memory.+    val seeded = remember(request) { request?.let { loader.peekMemoryCache(it) } }++    val bitmapState = produceState<Bitmap?>(initialValue = seeded, key1 = request) {         if (request == null) {             value = null             onState?.invoke(AsyncImageState.Empty)             return@produceState         }+        if (seeded != null) {+            // Served by the probe. `value` is assigned explicitly because+            // produceState only applies initialValue on first composition — on a+            // key change it still holds the previous request's bitmap.+            value = seeded+            onState?.invoke(AsyncImageState.Success(BitmapPainter(seeded.asImageBitmap())))+            return@produceState+        }         onState?.invoke(AsyncImageState.Loading)         try {             val result = loader.execute(request)
library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt b/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.ktindex e073ab8acd..48da33b519 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/decoders/BitmapDecoder.kt@@ -21,13 +21,34 @@ object BitmapDecoder {         request: ImageRequest,         allowHardware: Boolean,     ): Bitmap? {-        // Try ImageDecoder on P+ for better resampling + hardware support+        val reqSize = request.size+        val targetW = reqSize?.width ?: -1+        val targetH = reqSize?.height ?: -1++        val viaImageDecoder = try {+            decode(ImageDecoder.createSource(ByteBuffer.wrap(bytes)), request, allowHardware)+        } catch (_: Exception) {+            null+        }+        if (viaImageDecoder != null) return viaImageDecoder+        return try { decodeWithBitmapFactory(bytes, targetW, targetH, allowHardware) } catch (_: Exception) { null }+    }++    /**+     * Decode straight from an [ImageDecoder.Source], so local media never has to be+     * read into a `ByteArray` first. Downsampling happens inside the decoder, which+     * is why the target size matters more than where the bytes came from.+     */+    fun decode(+        source: ImageDecoder.Source,+        request: ImageRequest,+        allowHardware: Boolean,+    ): Bitmap? {         val reqSize = request.size         val targetW = reqSize?.width ?: -1         val targetH = reqSize?.height ?: -1          return try {-            val source = ImageDecoder.createSource(ByteBuffer.wrap(bytes))             ImageDecoder.decodeBitmap(source) { decoder, info, _ ->                 val w = info.size.width                 val h = info.size.height@@ -45,7 +66,7 @@ object BitmapDecoder {                 }             }         } catch (_: Exception) {-            try { decodeWithBitmapFactory(bytes, targetW, targetH, allowHardware) } catch (_: Exception) { null }+            null         }     } 
library/image/src/main/java/com/vayunmathur/library/image/fetchers/ContentResolverFetcher.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/fetchers/ContentResolverFetcher.kt b/library/image/src/main/java/com/vayunmathur/library/image/fetchers/ContentResolverFetcher.ktindex 2ec2c55157..610e85e023 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/fetchers/ContentResolverFetcher.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/fetchers/ContentResolverFetcher.kt@@ -1,10 +1,9 @@ package com.vayunmathur.library.image.fetchers  import android.content.Context+import android.graphics.ImageDecoder import android.net.Uri import androidx.core.net.toUri-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext  class ContentResolverFetcher : Fetcher {     override suspend fun fetch(data: Any?, context: Context): FetchResult? {@@ -14,14 +13,15 @@ class ContentResolverFetcher : Fetcher {             else -> return null         }         if (uri.scheme != "content") return null-        return withContext(Dispatchers.IO) {-            try {-                context.contentResolver.openInputStream(uri)?.use { it.readBytes() }?.let {-                    FetchResult.Bytes(it)-                }-            } catch (_: Exception) {-                null-            }-        }++        // Handed to the decoder as a source rather than read into a ByteArray:+        // MediaStore images are multi-MB and the caller usually wants a thumbnail,+        // so the whole encoded file never needs to exist in memory at once.+        // Creating the source does no IO, so there is nothing to dispatch here.+        val resolver = context.contentResolver+        return FetchResult.Source(+            decoderSource = ImageDecoder.createSource(resolver, uri),+            openStream = { try { resolver.openInputStream(uri) } catch (_: Exception) { null } },+        )     } }
library/image/src/main/java/com/vayunmathur/library/image/fetchers/Fetcher.kt
diff --git a/library/image/src/main/java/com/vayunmathur/library/image/fetchers/Fetcher.kt b/library/image/src/main/java/com/vayunmathur/library/image/fetchers/Fetcher.ktindex e21d7017b5..5358cd222d 100644--- a/library/image/src/main/java/com/vayunmathur/library/image/fetchers/Fetcher.kt+++ b/library/image/src/main/java/com/vayunmathur/library/image/fetchers/Fetcher.kt@@ -1,10 +1,28 @@ package com.vayunmathur.library.image.fetchers  import android.content.Context+import android.graphics.ImageDecoder+import java.io.InputStream  sealed class FetchResult {     data class Bytes(val bytes: ByteArray, val isVideo: Boolean = false) : FetchResult()     data class BitmapResult(val bitmap: android.graphics.Bitmap) : FetchResult()++    /**+     * Data that is already on local storage, exposed as a re-openable stream.+     *+     * Lets the decoder sample straight from the file rather than having the loader+     * first materialise the whole encoded image as a `ByteArray`: during a fast+     * scroll that was one multi-MB allocation per visible tile, to produce a+     * 256 px thumbnail.+     *+     * [openStream] is the fallback for content [decoderSource] cannot handle (an+     * SVG, or a video the frame decoder has to open).+     */+    class Source(+        val decoderSource: ImageDecoder.Source,+        val openStream: () -> InputStream?,+    ) : FetchResult() }  interface Fetcher {
photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.ktindex 56d95b7ed2..65859b4252 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt@@ -6,7 +6,6 @@ import androidx.room.Index import androidx.room.Insert import androidx.room.PrimaryKey import androidx.room.Query-import androidx.room.Update import kotlinx.coroutines.flow.Flow  /**@@ -57,14 +56,30 @@ data class PhotoFace(     val srcHeight: Int, ) +/**+ * A face's geometry without its 512-float [PhotoFace.embedding] BLOB.+ *+ * The UI needs where a face is and which cluster it belongs to, never the+ * vector — and the vector dwarfs everything else on the row. Selecting it for+ * the three view flows meant shipping the whole embedding table into memory on+ * every face write during a scan.+ */+data class FaceGeometry(+    val photoId: Long,+    val clusterId: Long,+    val left: Float,+    val top: Float,+    val right: Float,+    val bottom: Float,+    val srcWidth: Int,+    val srcHeight: Int,+)+ @Dao interface FaceDao {     @Insert     suspend fun insertPerson(person: Person): Long -    @Update-    suspend fun updatePerson(person: Person)-     @Query("SELECT * FROM Person")     suspend fun getPersons(): List<Person> @@ -82,6 +97,28 @@ interface FaceDao {     @Query("UPDATE Person SET name = :name WHERE id = :id")     suspend fun setPersonName(id: Long, name: String?) +    /**+     * Update only the columns the clustering pass owns.+     *+     * Deliberately not an `@Update` of the whole [Person]: the indexer works+     * from a snapshot loaded at scan start, so writing the entire row would+     * clobber a [Person.name] the user entered *while* the scan was running+     * with the stale null from that snapshot.+     */+    @Query("UPDATE Person SET centroid = :centroid, faceCount = :faceCount WHERE id = :id")+    suspend fun updateClusterCentroid(id: Long, centroid: ByteArray, faceCount: Int)++    /**+     * Fold a merged cluster into the survivor [id].+     *+     * A name is the one thing here the user typed, so the survivor keeps its own+     * if it has one and otherwise inherits [fallbackName] from the discarded+     * row. `COALESCE` reads the *current* name rather than a snapshot, for the+     * same reason [updateClusterCentroid] exists.+     */+    @Query("UPDATE Person SET centroid = :centroid, faceCount = :faceCount, name = COALESCE(name, :fallbackName) WHERE id = :id")+    suspend fun mergeClusterInto(id: Long, centroid: ByteArray, faceCount: Int, fallbackName: String?)+     @Insert     suspend fun insertPhotoFaces(faces: List<PhotoFace>) @@ -95,9 +132,12 @@ interface FaceDao {     @Query("UPDATE PhotoFace SET clusterId = :newId WHERE clusterId = :oldId")     suspend fun reassignCluster(oldId: Long, newId: Long) -    /** Every detected face, for grouping photos by cluster in the UI. */-    @Query("SELECT * FROM PhotoFace")-    fun allFacesFlow(): Flow<List<PhotoFace>>+    /**+     * Every detected face's geometry, for grouping photos by cluster in the UI.+     * Excludes [PhotoFace.embedding]; see [FaceGeometry].+     */+    @Query("SELECT photoId, clusterId, `left`, `top`, `right`, `bottom`, srcWidth, srcHeight FROM PhotoFace")+    fun faceGeometryFlow(): Flow<List<FaceGeometry>>      @Query("SELECT DISTINCT photoId FROM PhotoFace WHERE clusterId = :clusterId")     suspend fun photoIdsForCluster(clusterId: Long): List<Long>
photos/src/main/java/com/vayunmathur/photos/data/Photo.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt b/photos/src/main/java/com/vayunmathur/photos/data/Photo.ktindex 22d0deb680..1c4cbfb632 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt@@ -36,7 +36,7 @@ data class PanoData( }  @Serializable-@Entity(indices = [Index(value = ["date"])])+@Entity(indices = [Index(value = ["date"]), Index(value = ["isTrashed", "duration"])]) data class Photo(     @PrimaryKey(autoGenerate = true) override val id: Long = 0,     val name: String,
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex 9cbeb344af..8d5c00d6e8 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -5,6 +5,7 @@ import androidx.room.Database import androidx.room.Delete import androidx.room.Query import androidx.room.RoomDatabase+import androidx.room.Transaction import androidx.room.Upsert import androidx.room.migration.Migration import kotlinx.coroutines.flow.Flow@@ -54,29 +55,119 @@ interface PhotoDao {     @Query("SELECT count(*) FROM Photo WHERE ocrScanned = 1 AND isTrashed = 0 AND duration IS NULL")     fun getOCRCountFlow(): Flow<Int> -    /** Photos that count toward OCR indexing (denominator of the progress bar). */+    /**+     * Photos that count toward on-device indexing — the denominator shared by the+     * OCR, CLIP and face progress bars.+     *+     * One query rather than three: the OCR/CLIP/face variants were byte-identical,+     * so every write during a scan re-ran the same full table scan three times for+     * three observers of the same number.+     */     @Query("SELECT count(*) FROM Photo WHERE isTrashed = 0 AND duration IS NULL")-    fun getOCRTargetCountFlow(): Flow<Int>+    fun getIndexTargetCountFlow(): Flow<Int>++    // The three getUnscannedFor* queries project into [PhotoScanTarget] rather+    // than selecting whole rows: a photo awaiting OCR/CLIP/face work has, by+    // definition, nothing on it worth loading, and `SELECT *` pulled every+    // already-computed clipEmbedding BLOB along with it. ORDER BY date DESC is+    // served by index_Photo_date, so the workers no longer sort in memory.      /** Not-yet-OCR'd images (skips videos and trashed items). */-    @Query("SELECT * FROM Photo WHERE ocrScanned = 0 AND isTrashed = 0 AND duration IS NULL")-    suspend fun getUnscannedForOCR(): List<Photo>+    @Query("SELECT id, uri, date, width, height FROM Photo WHERE ocrScanned = 0 AND isTrashed = 0 AND duration IS NULL ORDER BY date DESC")+    suspend fun getUnscannedForOCR(): List<PhotoScanTarget> -    @Query("SELECT * FROM Photo WHERE faceScanned = 0 AND isTrashed = 0 AND duration IS NULL")-    suspend fun getUnscannedForFaces(): List<Photo>+    @Query("SELECT id, uri, date, width, height FROM Photo WHERE faceScanned = 0 AND isTrashed = 0 AND duration IS NULL ORDER BY date DESC")+    suspend fun getUnscannedForFaces(): List<PhotoScanTarget>      /** Not-yet-CLIP-embedded images (skips videos and trashed items). */-    @Query("SELECT * FROM Photo WHERE clipScanned = 0 AND isTrashed = 0 AND duration IS NULL")-    suspend fun getUnscannedForClip(): List<Photo>+    @Query("SELECT id, uri, date, width, height FROM Photo WHERE clipScanned = 0 AND isTrashed = 0 AND duration IS NULL ORDER BY date DESC")+    suspend fun getUnscannedForClip(): List<PhotoScanTarget>++    /** Photos still needing EXIF/XMP parsing. */+    @Query("SELECT id, uri FROM Photo WHERE exifSet = 0 ORDER BY date DESC")+    suspend fun getUnscannedForExif(): List<PhotoExifTarget>++    // ------------------------------------------------------------------+    // Targeted indexing writes+    //+    // Every one of these used to be `upsertAll(listOf(photo.copy(...)))`, which+    // rewrites the whole row — including the multi-KB clipEmbedding — to flip a+    // boolean, and invalidates the Photo table once per photo. They are+    // column-targeted and batched into a single transaction so a scan invalidates+    // once per flush instead of once per item.+    // ------------------------------------------------------------------++    @Query("UPDATE Photo SET ocrScanned = 1 WHERE id IN (:ids)")+    suspend fun setOcrScanned(ids: List<Long>)++    @Query("UPDATE Photo SET faceScanned = 1 WHERE id IN (:ids)")+    suspend fun setFaceScanned(ids: List<Long>)++    @Query("UPDATE Photo SET ocrText = :text, ocrBoxes = :boxes, ocrScanned = 1 WHERE id = :id")+    suspend fun setOcrResult(id: Long, text: String?, boxes: String?)++    @Transaction+    suspend fun setOcrResults(results: List<OcrResult>) {+        for (r in results) setOcrResult(r.id, r.text, r.boxes)+    }++    @Query("UPDATE Photo SET clipEmbedding = :embedding, clipScanned = 1 WHERE id = :id")+    suspend fun setClipResult(id: Long, embedding: ByteArray?)++    @Transaction+    suspend fun setClipResults(results: List<ClipResult>) {+        for (r in results) setClipResult(r.id, r.embedding)+    }++    /**+     * Write parsed EXIF/XMP by column.+     *+     * Deliberately not an upsert: the projection this is driven from+     * ([PhotoExifTarget]) has no clipEmbedding, so upserting a reconstructed row+     * would write NULL over every embedding it touched.+     */+    @Query(+        "UPDATE Photo SET exifSet = 1, lat = :lat, `long` = :long, " ++            "fullWidth = :fullWidth, fullHeight = :fullHeight, " ++            "croppedWidth = :croppedWidth, croppedHeight = :croppedHeight, " ++            "croppedLeft = :croppedLeft, croppedTop = :croppedTop, " ++            "projectionType = :projectionType WHERE id = :id"+    )+    suspend fun setExif(+        id: Long,+        lat: Double?,+        long: Double?,+        fullWidth: Int?,+        fullHeight: Int?,+        croppedWidth: Int?,+        croppedHeight: Int?,+        croppedLeft: Int?,+        croppedTop: Int?,+        projectionType: String?,+    )++    @Transaction+    suspend fun setExifResults(results: List<ExifResult>) {+        for (r in results) {+            setExif(+                id = r.id,+                lat = r.lat,+                long = r.long,+                fullWidth = r.pano?.fullWidth,+                fullHeight = r.pano?.fullHeight,+                croppedWidth = r.pano?.croppedWidth,+                croppedHeight = r.pano?.croppedHeight,+                croppedLeft = r.pano?.croppedLeft,+                croppedTop = r.pano?.croppedTop,+                projectionType = r.pano?.projectionType,+            )+        }+    }      /** Photos with a stored embedding, i.e. actually indexed (progress numerator). */     @Query("SELECT count(*) FROM Photo WHERE clipEmbedding IS NOT NULL AND isTrashed = 0 AND duration IS NULL")     fun getClipCountFlow(): Flow<Int> -    /** Photos that count toward CLIP embedding (denominator of the progress bar). */-    @Query("SELECT count(*) FROM Photo WHERE isTrashed = 0 AND duration IS NULL")-    fun getClipTargetCountFlow(): Flow<Int>-     /** Lightweight (id, embedding) rows for semantic search; excludes trashed. */     @Query("SELECT id, clipEmbedding FROM Photo WHERE clipEmbedding IS NOT NULL AND isTrashed = 0")     suspend fun getClipEmbeddings(): List<PhotoEmbedding>@@ -85,10 +176,6 @@ interface PhotoDao {     @Query("UPDATE Photo SET clipEmbedding = NULL, clipScanned = 0")     suspend fun resetClipScanned() -    /** Photos that count toward face indexing (denominator of the progress bar). */-    @Query("SELECT count(*) FROM Photo WHERE isTrashed = 0 AND duration IS NULL")-    fun getFaceTargetCountFlow(): Flow<Int>-     /** Photos already scanned for faces (numerator of the progress bar). */     @Query("SELECT count(*) FROM Photo WHERE faceScanned = 1 AND isTrashed = 0 AND duration IS NULL")     fun getFaceScannedCountFlow(): Flow<Int>@@ -107,6 +194,14 @@ interface PhotoDao {     @Query("SELECT ocrBoxes FROM Photo WHERE id = :id")     suspend fun getOcrBoxes(id: Long): String? +    /**+     * URIs of untrashed stills, for the home-screen widget's random pick. The+     * widget needs nothing else off the row, and pulling whole rows meant loading+     * every clipEmbedding in the library to choose one photo.+     */+    @Query("SELECT uri FROM Photo WHERE isTrashed = 0 AND duration IS NULL")+    suspend fun getStillPhotoUris(): List<String>+     @Query("UPDATE Photo SET ocrBoxes = :json WHERE id = :id")     suspend fun setOcrBoxes(id: Long, json: String?) }@@ -117,13 +212,52 @@ data class PhotoEmbedding(     val clipEmbedding: ByteArray, ) -@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 16, exportSchema = false)+/**+ * The columns an indexing worker needs to open, order and size a photo. Notably+ * excludes clipEmbedding, ocrText and ocrBoxes.+ */+data class PhotoScanTarget(+    val id: Long,+    val uri: String,+    val date: Long,+    val width: Int,+    val height: Int,+)++/** The columns the EXIF backfill needs. */+data class PhotoExifTarget(+    val id: Long,+    val uri: String,+)++/** One photo's OCR output, for the batched write in [PhotoDao.setOcrResults]. */+data class OcrResult(+    val id: Long,+    val text: String?,+    val boxes: String?,+)++/** One photo's semantic embedding, for the batched write in [PhotoDao.setClipResults]. */+data class ClipResult(+    val id: Long,+    val embedding: ByteArray?,+)++/** One photo's parsed EXIF/XMP, for the batched write in [PhotoDao.setExifResults]. */+data class ExifResult(+    val id: Long,+    val lat: Double?,+    val long: Double?,+    val pano: PanoData?,+)++@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 17, exportSchema = false) abstract class PhotoDatabase : RoomDatabase() {     abstract fun photoDao(): PhotoDao     abstract fun faceDao(): FaceDao      companion object : com.vayunmathur.library.util.DatabaseMigrations {-        override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16)+        override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17)     } } @@ -176,6 +310,14 @@ val MIGRATION_7_8 = Migration(7, 8) {     it.execSQL("UPDATE Photo SET faceScanned = 0") } +val MIGRATION_16_17 = Migration(16, 17) {+    // Index the predicate every progress count and every getUnscannedFor* query+    // shares (`isTrashed = 0 AND duration IS NULL`). The only index before this+    // was on `date`, so all of them full-scanned the table — once per observer,+    // on every single write a scan made. No data changes.+    it.execSQL("CREATE INDEX IF NOT EXISTS `index_Photo_isTrashed_duration` ON `Photo` (`isTrashed`, `duration`)")+}+ val MIGRATION_8_9 = Migration(8, 9) {     // Move OCR text off the FTS side-table and onto the Photo row so search is a     // plain case-insensitive LIKE (no external inference service). ocrScanned
photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.ktindex 3ab40958c9..7ead9d3b02 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -2,6 +2,7 @@ package com.vayunmathur.photos.data  import android.content.Context import com.vayunmathur.library.room.RoomRepository+import androidx.room.withTransaction import kotlinx.coroutines.flow.Flow  /**@@ -21,15 +22,15 @@ class PhotosRepository private constructor(context: Context) :     fun getAllFlow(): Flow<List<Photo>> = photoDao.getAllFlow()     fun getByIdFlow(id: Long): Flow<Photo?> = photoDao.getByIdFlow(id)     fun getOCRCountFlow(): Flow<Int> = photoDao.getOCRCountFlow()-    fun getOCRTargetCountFlow(): Flow<Int> = photoDao.getOCRTargetCountFlow()     fun getClipCountFlow(): Flow<Int> = photoDao.getClipCountFlow()-    fun getClipTargetCountFlow(): Flow<Int> = photoDao.getClipTargetCountFlow()-    fun getFaceTargetCountFlow(): Flow<Int> = photoDao.getFaceTargetCountFlow()     fun getFaceScannedCountFlow(): Flow<Int> = photoDao.getFaceScannedCountFlow() +    /** Shared denominator for the OCR, CLIP and face progress bars. */+    fun getIndexTargetCountFlow(): Flow<Int> = photoDao.getIndexTargetCountFlow()+     // FaceDao read Flows     fun personsFlow(): Flow<List<Person>> = faceDao.personsFlow()-    fun allFacesFlow(): Flow<List<PhotoFace>> = faceDao.allFacesFlow()+    fun faceGeometryFlow(): Flow<List<FaceGeometry>> = faceDao.faceGeometryFlow()      // ------------------------------------------------------------------     // PhotoDao suspend wrappers@@ -41,31 +42,54 @@ class PhotosRepository private constructor(context: Context) :     suspend fun deleteByIds(ids: List<Long>) = photoDao.deleteByIds(ids)     suspend fun setTrashed(id: Long) = photoDao.setTrashed(id)     suspend fun searchPhotos(query: String): List<Photo> = photoDao.searchPhotos(query)-    suspend fun getUnscannedForOCR(): List<Photo> = photoDao.getUnscannedForOCR()-    suspend fun getUnscannedForFaces(): List<Photo> = photoDao.getUnscannedForFaces()-    suspend fun getUnscannedForClip(): List<Photo> = photoDao.getUnscannedForClip()+    suspend fun getUnscannedForOCR(): List<PhotoScanTarget> = photoDao.getUnscannedForOCR()+    suspend fun getUnscannedForFaces(): List<PhotoScanTarget> = photoDao.getUnscannedForFaces()+    suspend fun getUnscannedForClip(): List<PhotoScanTarget> = photoDao.getUnscannedForClip()+    suspend fun getUnscannedForExif(): List<PhotoExifTarget> = photoDao.getUnscannedForExif()+    suspend fun setOcrScanned(ids: List<Long>) = photoDao.setOcrScanned(ids)+    suspend fun setOcrResults(results: List<OcrResult>) = photoDao.setOcrResults(results)+    suspend fun setClipResults(results: List<ClipResult>) = photoDao.setClipResults(results)+    suspend fun setExifResults(results: List<ExifResult>) = photoDao.setExifResults(results)     suspend fun getClipEmbeddings(): List<PhotoEmbedding> = photoDao.getClipEmbeddings()     suspend fun resetClipScanned() = photoDao.resetClipScanned()     suspend fun resetFaceScanned() = photoDao.resetFaceScanned()     suspend fun countMissingMimeType(): Int = photoDao.countMissingMimeType()     suspend fun getOcrBoxes(id: Long): String? = photoDao.getOcrBoxes(id)+    suspend fun getStillPhotoUris(): List<String> = photoDao.getStillPhotoUris()     suspend fun setOcrBoxes(id: Long, json: String?) = photoDao.setOcrBoxes(id, json)      // ------------------------------------------------------------------     // FaceDao suspend wrappers     // ------------------------------------------------------------------     suspend fun insertPerson(person: Person): Long = faceDao.insertPerson(person)-    suspend fun updatePerson(person: Person) = faceDao.updatePerson(person)+    suspend fun updateClusterCentroid(id: Long, centroid: ByteArray, faceCount: Int) =+        faceDao.updateClusterCentroid(id, centroid, faceCount)+    suspend fun mergeClusterInto(id: Long, centroid: ByteArray, faceCount: Int, fallbackName: String?) =+        faceDao.mergeClusterInto(id, centroid, faceCount, fallbackName)     suspend fun getPersons(): List<Person> = faceDao.getPersons()     suspend fun clearPersons() = faceDao.clearPersons()     suspend fun deletePerson(id: Long) = faceDao.deletePerson(id)     suspend fun setPersonName(id: Long, name: String?) = faceDao.setPersonName(id, name)-    suspend fun insertPhotoFaces(faces: List<PhotoFace>) = faceDao.insertPhotoFaces(faces)-    suspend fun deletePhotoFacesByPhotoIds(photoIds: List<Long>) = faceDao.deletePhotoFacesByPhotoIds(photoIds)     suspend fun clearPhotoFaces() = faceDao.clearPhotoFaces()     suspend fun reassignCluster(oldId: Long, newId: Long) = faceDao.reassignCluster(oldId, newId)     suspend fun photoIdsForCluster(clusterId: Long): List<Long> = faceDao.photoIdsForCluster(clusterId) +    /**+     * Commit one batch of face scanning atomically: replace the face rows for+     * [photoIds] and mark those photos scanned in the same transaction.+     *+     * All three statements have to land together. If the rows were written but the+     * flag was not (a worker killed mid-batch, which WorkManager does routinely),+     * the next run would re-scan those photos and insert a second set of rows for+     * them. Delete-then-insert also makes a re-scan idempotent on its own.+     */+    suspend fun commitFaceScan(photoIds: List<Long>, faces: List<PhotoFace>) =+        db.withTransaction {+            faceDao.deletePhotoFacesByPhotoIds(photoIds)+            if (faces.isNotEmpty()) faceDao.insertPhotoFaces(faces)+            photoDao.setFaceScanned(photoIds)+        }+     companion object {         @Volatile         private var instance: PhotosRepository? = null
photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt b/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.ktindex 11f17da1ae..58621ccb70 100644--- a/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt+++ b/photos/src/main/java/com/vayunmathur/photos/glance/PhotoGlanceWidget.kt@@ -40,18 +40,18 @@ import kotlinx.coroutines.withContext class PhotoGlanceWidget : GlanceAppWidget() {     override suspend fun provideGlance(context: Context, id: GlanceId) { -        val photos = PhotosRepository.get(context.applicationContext).getAll()+        val uris = PhotosRepository.get(context.applicationContext).getStillPhotoUris()          provideContent {-            var photo by remember(photos) { mutableStateOf(photos.filter{it.videoData == null}.randomOrNull()) }-            val bitmap by produceState<Bitmap?>(initialValue = null, photo) {+            var uri by remember(uris) { mutableStateOf(uris.randomOrNull()) }+            val bitmap by produceState<Bitmap?>(initialValue = null, uri) {                 value = withContext(Dispatchers.IO) {-                    photo?.let { getResizedBitmap(context, it.uri.toUri(), 600) }+                    uri?.let { getResizedBitmap(context, it.toUri(), 600) }                 }             }             DynamicThemeGlance(context) {                 bitmap?.let {-                    Content(it) { photo = photos.randomOrNull() }+                    Content(it) { uri = uris.randomOrNull() }                 }             }         }
photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt b/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.ktindex 6f4b184bc7..811c9b467c 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt@@ -44,6 +44,10 @@ import kotlin.math.roundToInt  * things that must hold their on-screen size are counter-scaled by [zoom]: the  * stroke widths, and the name labels.  *+ * [zoom] is a lambda, not a value, so it is read inside the draw and layer+ * lambdas below rather than during composition — a pinch re-runs those without+ * recomposing this layer or anything around it.+ *  * Colours are fixed rather than themed for the reason spelled out on  * [OcrTextLayer]: a dynamic-colour pastel vanishes over a bright photo, so every  * line is a light stroke sitting inside a dark halo.@@ -52,7 +56,7 @@ import kotlin.math.roundToInt fun FaceBoxLayer(     boxes: PhotoFaceBoxes,     containerSize: IntSize,-    zoom: Float,+    zoom: () -> Float,     onFaceClick: (Long) -> Unit,     modifier: Modifier = Modifier, ) {@@ -82,9 +86,10 @@ fun FaceBoxLayer(             // Pre-divided by the zoom this whole layer sits inside, so the lines             // stay a constant thickness on screen instead of ballooning with the             // photo.-            val halo = OUTLINE_HALO.toPx() / zoom-            val line = OUTLINE_STROKE.toPx() / zoom-            val corner = CornerRadius(BOX_CORNER.toPx() / zoom)+            val scale = zoom()+            val halo = OUTLINE_HALO.toPx() / scale+            val line = OUTLINE_STROKE.toPx() / scale+            val corner = CornerRadius(BOX_CORNER.toPx() / scale)             placements.forEach { p ->                 // Wide dark stroke first, narrow light stroke centred inside it:                 // one of the two always contrasts, whatever is underneath.@@ -135,8 +140,9 @@ fun FaceBoxLayer(                         // grows with pinch-zoom.                         .graphicsLayer {                             transformOrigin = TransformOrigin(0f, 0f)-                            scaleX = 1f / zoom-                            scaleY = 1f / zoom+                            val inverse = 1f / zoom()+                            scaleX = inverse+                            scaleY = inverse                         }                 ) {                     Text(
photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.ktindex 1c733961a8..ea5db452dd 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt@@ -40,8 +40,12 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext import androidx.compose.ui.Modifier import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.changedToUp@@ -81,12 +85,15 @@ internal fun groupPhotosByMonth(     resources: android.content.res.Resources, ): Map<String, List<Photo>> {     val monthNames = localizedMonthNames(DateNameStyle.SHORT)+    // No per-group sort: PhotoDao.getAllFlow already returns rows newest-first+    // (ORDER BY date DESC, served by index_Photo_date) and groupBy preserves that+    // order within each group, so re-sorting every month was sorting sorted data.     return photos.groupBy {         val date = Instant.fromEpochMilliseconds(it.date).toLocalDateTime(TimeZone.currentSystemDefault())         LocalDate(date.year, date.month, 1)     }.toSortedMap(compareByDescending { it }).mapKeys {         resources.getString(R.string.month_year_format, monthNames[it.key.month.ordinal], it.key.year)-    }.mapValues { pair -> pair.value.sortedByDescending { it.date } }+    } }  /** Binds [GalleryViewModel] to the stateless [GalleryScreen]. */@@ -107,9 +114,8 @@ fun GalleryPage(     val searchResults by galleryViewModel.searchResults.collectAsState()     val searchAiState by galleryViewModel.searchAiState.collectAsState()     val ocrCount by galleryViewModel.ocrCount.collectAsState()-    val ocrTargetCount by galleryViewModel.ocrTargetCount.collectAsState()     val clipCount by galleryViewModel.clipCount.collectAsState()-    val clipTargetCount by galleryViewModel.clipTargetCount.collectAsState()+    val indexTargetCount by galleryViewModel.indexTargetCount.collectAsState()      LaunchedEffect(Unit) {         galleryViewModel.runSync()@@ -140,44 +146,57 @@ fun GalleryPage(         }     }     -    val onMoveToSecureClick: () -> Unit = onMoveToSecureClick@{-        val activity = context as FragmentActivity-        val selectedPhotos = photos.filter { it.id in selectedIds }-        -        secureFolderViewModel.unlock(-            activity,-            onSuccess = { _, _ ->-                secureFolderViewModel.moveToSecure(-                    photos = selectedPhotos,-                    sourceRepository = com.vayunmathur.photos.data.PhotosRepository.get(context.applicationContext),-                ) { urisToDelete ->-                    // Use MediaStore operations to delete files-                    // MANAGE_MEDIA permission is required to run the app (checked in PermissionsWrapper)-                    try {-                        val pendingIntent = MediaStore.createDeleteRequest(-                            context.contentResolver,-                            urisToDelete-                        )-                        // With MANAGE_MEDIA permission granted, this will delete without popup-                        mediaResultLauncher.launch(-                            IntentSenderRequest.Builder(pendingIntent.intentSender).build()-                        )-                    } catch (e: Exception) {-                        android.util.Log.e("GalleryPage", "MediaStore delete request failed", e)-                        // Fallback: clear selection and refresh anyway-                        galleryViewModel.clearSelection()-                        galleryViewModel.runSync()-                    }-                }-            },-            onFailure = {},-        )-    }+    // Read through State holders so the lambdas below see current values without+    // being reallocated each recomposition — which is what lets the `actions`+    // object be remembered rather than rebuilt (and every grid item lambda+    // invalidated) on every frame.+    val currentPhotos by rememberUpdatedState(photos)+    val currentSelectedIds by rememberUpdatedState(selectedIds)++    val actions = remember(galleryViewModel, secureFolderViewModel, context) {+        // The ViewModel is the actions implementation; the two MediaStore operations are+        // the exception, because they need the launchers created above.+        object : GalleryActions by galleryViewModel {+            override fun moveSelectionToSecureFolder() {+                val activity = context as FragmentActivity+                val selectedPhotos = currentPhotos.filter { it.id in currentSelectedIds } -    val onDeleteClick: () -> Unit = {-        val uris = photos.filter { it.id in selectedIds }.map { it.uri.toUri() }-        val pendingIntent = MediaStore.createTrashRequest(context.contentResolver, uris, true)-        mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+                secureFolderViewModel.unlock(+                    activity,+                    onSuccess = { _, _ ->+                        secureFolderViewModel.moveToSecure(+                            photos = selectedPhotos,+                            sourceRepository = com.vayunmathur.photos.data.PhotosRepository.get(context.applicationContext),+                        ) { urisToDelete ->+                            // Use MediaStore operations to delete files+                            // MANAGE_MEDIA permission is required to run the app (checked in PermissionsWrapper)+                            try {+                                val pendingIntent = MediaStore.createDeleteRequest(+                                    context.contentResolver,+                                    urisToDelete+                                )+                                // With MANAGE_MEDIA permission granted, this will delete without popup+                                mediaResultLauncher.launch(+                                    IntentSenderRequest.Builder(pendingIntent.intentSender).build()+                                )+                            } catch (e: Exception) {+                                android.util.Log.e("GalleryPage", "MediaStore delete request failed", e)+                                // Fallback: clear selection and refresh anyway+                                galleryViewModel.clearSelection()+                                galleryViewModel.runSync()+                            }+                        }+                    },+                    onFailure = {},+                )+            }++            override fun trashSelection() {+                val uris = currentPhotos.filter { it.id in currentSelectedIds }.map { it.uri.toUri() }+                val pendingIntent = MediaStore.createTrashRequest(context.contentResolver, uris, true)+                mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+            }+        }     }      GalleryScreen(@@ -190,16 +209,11 @@ fun GalleryPage(             searchResults = searchResults,             searchAiState = searchAiState,             ocrCount = ocrCount,-            ocrTargetCount = ocrTargetCount,+            ocrTargetCount = indexTargetCount,             clipCount = clipCount,-            clipTargetCount = clipTargetCount,+            clipTargetCount = indexTargetCount,         ),-        // The ViewModel is the actions implementation; the two MediaStore operations are-        // the exception, because they need the launchers created above.-        actions = object : GalleryActions by galleryViewModel {-            override fun moveSelectionToSecureFolder() = onMoveToSecureClick()-            override fun trashSelection() = onDeleteClick()-        },+        actions = actions,     ) } @@ -228,14 +242,29 @@ fun GalleryScreen(     var searchActive by remember { mutableStateOf(initialSearchActive) }     val isSelectionMode = state.selectedIds.isNotEmpty() -    // Keyed on the incoming lists rather than derivedStateOf: `state` is a plain value, so-    // there is nothing for a derived state to observe.+    // Grouping is O(library) with a timezone conversion per photo, so it runs on+    // Dispatchers.Default. The initial value is computed inline so the very first+    // composition (and a @Preview, which never gets to run the producer) still has+    // a populated grid; every later change is computed off the main thread while+    // the previous grouping stays on screen.+    //+    // Only the list actually being displayed is grouped — with the search bar+    // closed, search results are not grouped at all.     val resources = LocalResources.current-    val photosGroupedByMonth = remember(state.photos, resources) {-        groupPhotosByMonth(state.photos, resources)-    }-    val searchResultsGroupedByMonth = remember(state.searchResults, resources) {-        groupPhotosByMonth(state.searchResults, resources)+    val visiblePhotos =+        if (searchActive && state.searchQuery.isNotEmpty()) state.searchResults else state.photos+    // Computed exactly once (no remember keys), for the first frame only — and for a+    // @Preview, which never gets to run the producer below. It has to be a remember:+    // produceState's initialValue is an ordinary eagerly-evaluated argument, so+    // calling groupPhotosByMonth inline there would run the whole grouping on the+    // main thread on every recomposition and throw the result away.+    val initialGrouping = remember { groupPhotosByMonth(visiblePhotos, resources) }+    val groupedPhotos by produceState(+        initialValue = initialGrouping,+        visiblePhotos,+        resources,+    ) {+        value = withContext(Dispatchers.Default) { groupPhotosByMonth(visiblePhotos, resources) }     }      // RAW SCAFFOLD EXCEPTION: top bar is an expandable SearchBar (with in-bar search@@ -383,8 +412,7 @@ fun GalleryScreen(                     horizontalArrangement = Arrangement.spacedBy(4.dp),                     verticalArrangement = Arrangement.spacedBy(4.dp)                 ) {-                    val currentGroupedPhotos = if (searchActive && state.searchQuery.isNotEmpty()) searchResultsGroupedByMonth else photosGroupedByMonth-                    currentGroupedPhotos.forEach { (month, photosInMonth) ->+                    groupedPhotos.forEach { (month, photosInMonth) ->                         item(span = { GridItemSpan(maxLineSpan) }) {                             Text(                                 month,
photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.ktindex 510e810fff..f7165c5a70 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/MapPage.kt@@ -42,7 +42,13 @@ import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.ImageLoader import com.vayunmathur.photos.util.PhotoMapViewModel+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.conflate+import kotlinx.coroutines.flow.filterNotNull+import kotlinx.coroutines.withContext+import androidx.compose.runtime.snapshotFlow+import com.vayunmathur.library.map.CameraPosition import com.vayunmathur.library.map.GeoPoint import com.vayunmathur.library.map.RasterMap import com.vayunmathur.library.map.TileSource@@ -56,6 +62,19 @@ data class MapCluster(     val count: Int, ) +/**+ * The inputs [MapPage]'s per-frame re-projection last ran for, so an unchanged+ * frame can be skipped. Deliberately not Compose state: `onFrame` runs every+ * frame, and a state write there would mean a recomposition every frame.+ */+private class ProjectionMemo {+    var position: CameraPosition? = null+    var source: List<MapCluster>? = null+}++/** Minimum gap between re-clustering passes while the camera keeps moving. */+private const val CLUSTER_THROTTLE_MS = 200L+ @Composable fun MapPage(     backStack: NavBackStack<Route>,@@ -78,22 +97,34 @@ fun MapPage(     var selectedCluster: MapCluster? by remember { mutableStateOf(null) }      val dpsize = LocalWindowInfo.current.containerDpSize+    val projectionMemo = remember { ProjectionMemo() } -    LaunchedEffect(photos) {-        cameraState.awaitProjection()-        while (true) {-            val projection = cameraState.projection ?: continue-            val rawLocations = positions.map { (gps, photo) ->-                val dpOffset = projection.screenLocationFromPosition(-                    GeoPoint(gps.second, gps.first)-                )-                dpOffset to photo-            }.filter { (dpOffset, _) ->-                dpOffset.x.value > 0 && dpOffset.y.value > 0 && dpOffset.x < dpsize.width && dpOffset.y < dpsize.height+    // Driven by camera movement rather than a fixed 200 ms tick, so an idle map+    // does no work. This also removes the old `?: continue` on a null projection,+    // which skipped the delay and spun the main dispatcher without suspending — a+    // hard UI freeze until the viewport was measured.+    //+    // Projection is pure maths over immutable captured values, so the pass is safe+    // off the main thread. conflate plus the trailing delay throttle a continuous+    // pan to one pass per interval, dropping superseded camera states.+    LaunchedEffect(positions, dpsize) {+        snapshotFlow { cameraState.projection }+            .filterNotNull()+            .conflate()+            .collect { projection ->+                val rawLocations = withContext(Dispatchers.Default) {+                    positions.mapNotNull { (gps, photo) ->+                        val dpOffset = projection.screenLocationFromPosition(+                            GeoPoint(gps.second, gps.first)+                        )+                        val visible = dpOffset.x.value > 0 && dpOffset.y.value > 0 &&+                            dpOffset.x < dpsize.width && dpOffset.y < dpsize.height+                        if (visible) dpOffset to photo else null+                    }+                }+                photoMapViewModel.regenerateClusters(rawLocations, 50.dp)+                delay(CLUSTER_THROTTLE_MS)             }-            photoMapViewModel.regenerateClusters(rawLocations, 50.dp)-            delay(200)-        }     }      LaunchedEffect(generatedClusters) {@@ -115,28 +146,35 @@ fun MapPage(                 },                 onFrame = {                     val projection = cameraState.projection+                    val position = cameraState.position++                    // FAST PATH: re-project existing clusters so markers don't+                    // drift when panning/zooming between re-clustering intervals.+                    // Gated on the inputs actually changing: this runs every frame,+                    // and assigning `clusters` unconditionally was a state write —+                    // so a recomposition — on every frame of a still map.+                    if (projection != null &&+                        (projectionMemo.position != position || projectionMemo.source !== generatedClusters)+                    ) {+                        projectionMemo.position = position+                        projectionMemo.source = generatedClusters -                    if (projection != null) {-                        // FAST PATH: re-project existing clusters every frame to-                        // prevent markers from drifting when panning/zooming-                        // between re-clustering intervals.                         val updatedClusters = generatedClusters.mapNotNull { cluster ->                             val lat = cluster.coverPhoto.lat                             val long = cluster.coverPhoto.long-                            val nc = if (lat != null && long != null) {-                                val newOffset = projection.screenLocationFromPosition(-                                    GeoPoint(long, lat)-                                )-                                cluster.copy(position = newOffset)-                            } else {-                                null-                            }-                            if (cluster == selectedCluster) {-                                selectedCluster = nc-                            }-                            nc+                            if (lat == null || long == null) return@mapNotNull null+                            cluster.copy(+                                position = projection.screenLocationFromPosition(GeoPoint(long, lat))+                            )                         }                         clusters = updatedClusters++                        // Lifted out of the mapping pass, which mutated it while+                        // iterating and matched on a value that includes the very+                        // position being replaced.+                        selectedCluster = selectedCluster?.let { selected ->+                            updatedClusters.find { it.coverPhoto.id == selected.coverPhoto.id }+                        }                     }                 }             )
photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.ktindex bbe6bded96..95dd8660a3 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt@@ -53,7 +53,9 @@ import kotlin.math.roundToInt  * mapped through the `ContentScale.Fit` letterbox this image is drawn in — hence  * [containerSize] and the layout's own dimensions rather than [com.vayunmathur.photos.data.Photo.width].  * The caller passes the image's zoom/pan `graphicsLayer` in [modifier] so the- * text tracks pinch-zoom in lockstep.+ * text tracks pinch-zoom in lockstep. [zoom] is a lambda so the stroke+ * counter-scaling reads it in the draw phase, and a pinch redraws without+ * recomposing.  *  * Everything drawn here has to stay legible on top of an arbitrary photo, which  * rules out theme colours (a dynamic-colour primary is often a pale pastel that@@ -66,7 +68,7 @@ fun OcrTextLayer(     layout: OcrLayout,     containerSize: IntSize,     showOutlines: Boolean,-    zoom: Float,+    zoom: () -> Float,     modifier: Modifier = Modifier, ) {     if (layout.boxes.isEmpty() || containerSize.width <= 0 || containerSize.height <= 0) return@@ -125,8 +127,8 @@ fun OcrTextLayer(                 // The whole layer is inside the image's zoom transform, so the                 // strokes are pre-divided by it to stay a constant thickness                 // on screen instead of ballooning as the photo is magnified.-                val halo = OUTLINE_HALO.toPx() / zoom-                val line = OUTLINE_STROKE.toPx() / zoom+                val halo = OUTLINE_HALO.toPx() / zoom()+                val line = OUTLINE_STROKE.toPx() / zoom()                 placements.forEach { p ->                     // Wide dark stroke first, narrow light stroke centred inside it:                     // one of the two always contrasts, whatever is underneath.
photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.ktindex 39a529fe86..547a5a4c1f 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt@@ -68,7 +68,7 @@ fun PeoplePage(     val people by galleryViewModel.people.collectAsState()     val indexing by galleryViewModel.faceIndexing.collectAsState()     val scanned by galleryViewModel.faceScannedCount.collectAsState()-    val target by galleryViewModel.faceTargetCount.collectAsState()+    val target by galleryViewModel.indexTargetCount.collectAsState()     val modelsAvailable = remember { FaceRecognizer.modelsAvailable(context) }      // The contact picker's result carries only the picked contact, with nothing to
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex bf3da90a8d..58e2c66d8f 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -45,6 +45,7 @@ import com.vayunmathur.library.ui.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue@@ -118,21 +119,21 @@ data class ZoomState(val scale: Float = 1f, val offset: Offset = Offset.Zero) @Composable fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapViewModel, id: Long, overridePhotosList: List<Photo>?, pendingUri: String? = null, backStack: NavBackStack<Route>? = null) {     val photosAll by galleryViewModel.photos.collectAsState()-    val photos = overridePhotosList ?: photosAll.filter { !it.isTrashed }     val context = LocalContext.current     val coroutineScope = rememberCoroutineScope()     // Photos deleted from within this viewer, hidden immediately so the pager     // advances to the next photo without waiting for the MediaStore resync.     val locallyDeleted = remember { mutableStateListOf<Long>() }-    val photosSorted = remember(photos, locallyDeleted.toList()) {-        photos.asSequence()-            .filter { it.id !in locallyDeleted }-            .sortedByDescending { it.date }-            .toList()+    // One remembered pass instead of an unmemoized filter plus a sort plus two+    // index scans in the composable body. The sort is gone: the DAO returns rows+    // newest-first (ORDER BY date DESC) and every list handed in via+    // overridePhotosList is already date-descending.+    val photosSorted = remember(photosAll, overridePhotosList, locallyDeleted.toList()) {+        val source = overridePhotosList ?: photosAll.filter { !it.isTrashed }+        source.filter { it.id !in locallyDeleted }     }     val matchedCounts by galleryViewModel.faceCountByPhoto.collectAsState()     val faceBoxes by galleryViewModel.faceBoxesByPhoto.collectAsState()-    val people by galleryViewModel.people.collectAsState()      // In-viewer delete: move the current photo to the system trash via the same     // MediaStore IntentSender flow the grid uses. MANAGE_MEDIA (enforced at app@@ -223,10 +224,20 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie                     state = pagerState,                     modifier = Modifier.fillMaxSize().padding(paddingValues),                     beyondViewportPageCount = 1,-                    userScrollEnabled = true+                    userScrollEnabled = true,+                    // Without a key, a list change re-associates pages by index, so+                    // the two neighbours kept composed either side end up holding+                    // the wrong photo.+                    key = { photosSorted[it].id },             ) { pageIndex ->                 val photo = photosSorted[pageIndex]-                val zoomState = zoomStates[photo.id] ?: ZoomState()+                // derivedStateOf rather than a direct map read: reading zoomStates+                // here would recompose this pager item — and all of+                // PhotoDetailView — on every frame of a pinch. The state object is+                // passed down and read only inside draw/layer lambdas.+                val zoomState = remember(photo.id) {+                    derivedStateOf { zoomStates[photo.id] ?: ZoomState() }+                }                  PhotoDetailView(                         photo = photo,@@ -240,9 +251,14 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie                         peopleCount = matchedCounts[photo.id] ?: 0,                         faceBoxes = faceBoxes[photo.id],                         onOpenPerson = { clusterId ->-                            // The same navigation the People grid performs.-                            people.firstOrNull { it.id == clusterId }?.let { cluster ->-                                backStack?.add(Route.PhotoPage(cluster.coverPhoto.id, cluster.photos))+                            // Resolved on demand rather than by collecting the whole+                            // `people` list here, which this screen needed for+                            // nothing else.+                            coroutineScope.launch {+                                val clusterPhotos = galleryViewModel.photosForCluster(clusterId)+                                clusterPhotos.firstOrNull()?.let { first ->+                                    backStack?.add(Route.PhotoPage(first.id, clusterPhotos))+                                }                             }                         },                         onZoomUpdate = { newState -> zoomStates[photo.id] = newState },@@ -303,7 +319,13 @@ fun PhotoDetailView(         pageIndex: Int,         isSettled: Boolean,         isMetadataVisible: Boolean,-        currentZoom: ZoomState,+        /**+         * Live zoom/pan for this page. A [State] rather than a value so the reads+         * happen inside gesture handlers and draw/layer lambdas: a pinch then+         * re-runs the transform without recomposing the image, the overlays or the+         * metadata card.+         */+        currentZoom: State<ZoomState>,         peopleCount: Int = 0,         faceBoxes: PhotoFaceBoxes? = null,         onOpenPerson: (Long) -> Unit = {},@@ -333,7 +355,15 @@ fun PhotoDetailView(     }     var size by remember { mutableStateOf(IntSize.Zero) } -    val updatedZoomState by rememberUpdatedState(currentZoom)+    // The viewer never shows more than screen resolution, so the decode is capped+    // to the screen's longest edge rather than the file's. Constant for the life+    // of the composition, so it can't churn the cache key the way tracking the+    // measured container size would.+    val viewerImageSize = remember(context) {+        val metrics = context.resources.displayMetrics+        maxOf(metrics.widthPixels, metrics.heightPixels)+    }+     val updatedOnZoomUpdate by rememberUpdatedState(onZoomUpdate)     val updatedOnToggleMetadata by rememberUpdatedState(onToggleMetadata) @@ -352,7 +382,7 @@ fun PhotoDetailView(     var ocrClearToken by remember { mutableIntStateOf(0) }     LaunchedEffect(Unit) {         snapshotFlow { pageOffset }.filter { it >= 0.99f }.distinctUntilChanged().collect {-            if (updatedZoomState.scale > 1f) {+            if (currentZoom.value.scale > 1f) {                 updatedOnZoomUpdate(ZoomState())             }             ocrClearToken++@@ -366,7 +396,9 @@ fun PhotoDetailView(     val canHaveOcrText = photo.videoData == null && !photo.isGif     LaunchedEffect(photo.id, isSettled, canHaveOcrText) {         if (isSettled && canHaveOcrText) {-            ocrLayout = OcrBoxStore.layoutFor(context, photo)+            // layoutFor JSON-decodes every recognised line and quad, which is far+            // too much to do on Main.immediate on every swipe.+            ocrLayout = withContext(Dispatchers.Default) { OcrBoxStore.layoutFor(context, photo) }         }     } @@ -391,7 +423,7 @@ fun PhotoDetailView(                                         onTap = { updatedOnToggleMetadata() },                                         onDoubleTap = {                                             val newScale =-                                                    if (updatedZoomState.scale > 1f) 1f else 2.5f+                                                    if (currentZoom.value.scale > 1f) 1f else 2.5f                                             updatedOnZoomUpdate(                                                     ZoomState(                                                             scale = newScale,@@ -410,11 +442,12 @@ fun PhotoDetailView(                                         val panChange = event.calculatePan()                                          val isPinching = zoomChange != 1f-                                        val isZoomed = updatedZoomState.scale > 1.01f+                                        val zoom = currentZoom.value+                                        val isZoomed = zoom.scale > 1.01f                                          if (isZoomed || isPinching) {                                             val newScale =-                                                    (updatedZoomState.scale * zoomChange).coerceIn(+                                                    (zoom.scale * zoomChange).coerceIn(                                                             1f,                                                             5f                                                     )@@ -423,7 +456,7 @@ fun PhotoDetailView(                                                 val maxX = (size.width * (newScale - 1) / 2)                                                 val maxY = (size.height * (newScale - 1) / 2) -                                                val newOffset = updatedZoomState.offset + panChange+                                                val newOffset = zoom.offset + panChange                                                  val isAtLeftEdge =                                                         newOffset.x >= maxX && panChange.x > 0@@ -458,12 +491,15 @@ fun PhotoDetailView(                             }     ) {         // Shared by the image and the OCR text overlay so the two can't drift apart.+        // Reads currentZoom inside the layer block, so a pinch updates the GPU+        // transform without recomposing anything in this subtree.         val zoomModifier =                 Modifier.graphicsLayer {-                    scaleX = currentZoom.scale-                    scaleY = currentZoom.scale-                    translationX = currentZoom.offset.x-                    translationY = currentZoom.offset.y+                    val zoom = currentZoom.value+                    scaleX = zoom.scale+                    scaleY = zoom.scale+                    translationX = zoom.offset.x+                    translationY = zoom.offset.y                 }         if (photo.videoData == null) {             val imageModifier =@@ -483,8 +519,19 @@ fun PhotoDetailView(                         model =                                 ImageRequest.Builder(context)                                         .data(photo.uri.toUri())-                                        .diskCacheKey("thumb_${photo.id}_${photo.dateModified}_$refreshKey")+                                        // refreshKey stays out of the disk key: it bumps on+                                        // every ON_RESUME, so including it there made a+                                        // return from the editor or a share sheet re-fetch+                                        // and re-write the file. The memory key still+                                        // carries it, which is the point — the pixels may+                                        // have been edited.+                                        .diskCacheKey("thumb_${photo.id}_${photo.dateModified}")                                         .memoryCacheKey("thumb_${photo.id}_${photo.dateModified}_$refreshKey")+                                        // Without a size this decodes at full resolution: a+                                        // 12 MP photo is ~48 MB as ARGB_8888, enough for one+                                        // opened photo to evict every grid thumbnail from a+                                        // memory cache measured in tens of MB.+                                        .size(viewerImageSize)                                         .build(),                         contentDescription = null,                         modifier = imageModifier,@@ -509,7 +556,7 @@ fun PhotoDetailView(                         layout = layout,                         containerSize = size,                         showOutlines = isMetadataVisible,-                        zoom = currentZoom.scale,+                        zoom = { currentZoom.value.scale },                         modifier = Modifier.fillMaxSize().then(zoomModifier)                 )             }@@ -531,7 +578,7 @@ fun PhotoDetailView(                 FaceBoxLayer(                         boxes = boxes,                         containerSize = size,-                        zoom = currentZoom.scale,+                        zoom = { currentZoom.value.scale },                         onFaceClick = onOpenPerson,                         modifier = Modifier.fillMaxSize()                 )
photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.ktindex 942b62e5c4..ead9fa73ac 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/SecureFolderPage.kt@@ -27,6 +27,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -141,11 +142,16 @@ fun VaultPhotoItem(     secureFolderViewModel: SecureFolderViewModel,     onClick: () -> Unit, ) {-    val thumbnails by secureFolderViewModel.thumbnails.collectAsState()-    val bitmap = thumbnails[photo.thumbnailPath]+    val bitmap by remember(photo.thumbnailPath) {+        secureFolderViewModel.thumbnailState(photo.thumbnailPath)+    } -    LaunchedEffect(photo.thumbnailPath) {-        secureFolderViewModel.requestThumbnail(photo.thumbnailPath, password)+    // Keyed on emptiness as well as path, so a thumbnail the LRU evicted while this+    // item was still on screen is decrypted again rather than staying a grey box.+    LaunchedEffect(photo.thumbnailPath, bitmap == null) {+        if (bitmap == null) {+            secureFolderViewModel.requestThumbnail(photo.thumbnailPath, password)+        }     }      Box(@@ -162,9 +168,10 @@ fun VaultPhotoItem(         // Guard against recycled bitmaps - defense in depth for the LRU cache bug.         // When column count >=4, more thumbnails are visible and cache eviction         // previously recycled bitmaps still being drawn by Compose.-        if (bitmap != null && !bitmap.isRecycled) {+        val currentBitmap = bitmap+        if (currentBitmap != null && !currentBitmap.isRecycled) {             Image(-                bitmap = bitmap.asImageBitmap(),+                bitmap = currentBitmap.asImageBitmap(),                 contentDescription = null,                 contentScale = ContentScale.Crop,                 modifier = Modifier.fillMaxSize()
photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.ktindex 3e473de573..2c4c674f79 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/TrashPage.kt@@ -27,6 +27,7 @@ import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment@@ -48,6 +49,8 @@ import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.ImageLoader import com.vayunmathur.photos.util.SyncWorker+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext import kotlin.math.roundToInt  @OptIn(ExperimentalMaterial3Api::class)@@ -75,8 +78,17 @@ fun TrashPage(backStack: NavBackStack<Route>, galleryViewModel: GalleryViewModel         }     } -    val photosGroupedByMonth by remember {-        derivedStateOf { groupPhotosByMonth(trashedPhotos, resources) }+    // Grouping is O(N) with a timezone conversion per photo, so it runs on+    // Dispatchers.Default. The seed is computed once so the grid isn't blank on the+    // first frame; produceState's initialValue is eagerly evaluated, hence the+    // remember rather than an inline call.+    val initialGrouping = remember { groupPhotosByMonth(trashedPhotos, resources) }+    val photosGroupedByMonth by produceState(+        initialValue = initialGrouping,+        trashedPhotos,+        resources,+    ) {+        value = withContext(Dispatchers.Default) { groupPhotosByMonth(trashedPhotos, resources) }     }      val closeSelection: (() -> Unit)? = if (isSelectionMode) ({ selectedIds.clear() }) else null
photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.ktindex a6115db57f..7b218f0197 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt@@ -18,8 +18,10 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged+import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update@@ -76,17 +78,19 @@ class GalleryViewModel(      val ocrCount: StateFlow<Int> = photoDao.getOCRCountFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)-    val ocrTargetCount: StateFlow<Int> = photoDao.getOCRTargetCountFlow()++    /**+     * Photos that count toward on-device indexing: the denominator shared by the+     * OCR, CLIP and face progress bars, which all measure progress over the same+     * set of photos. One flow, so one observer and one query per write.+     */+    val indexTargetCount: StateFlow<Int> = photoDao.getIndexTargetCountFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)      /** Photos already embedded with TinyCLIP for semantic search (progress numerator). */     val clipCount: StateFlow<Int> = photoDao.getClipCountFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0) -    /** Photos that count toward semantic indexing (progress denominator). */-    val clipTargetCount: StateFlow<Int> = photoDao.getClipTargetCountFlow()-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)-     /** True while the face-grouping worker is actively indexing. */     val faceIndexing: StateFlow<Boolean> = WorkManager.getInstance(application)         .getWorkInfosForUniqueWorkFlow(FaceWorker.WORK_NAME)@@ -97,10 +101,6 @@ class GalleryViewModel(     val faceScannedCount: StateFlow<Int> = photoDao.getFaceScannedCountFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0) -    /** Photos that need face scanning in total (progress denominator). */-    val faceTargetCount: StateFlow<Int> = photoDao.getFaceTargetCountFlow()-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0)-     /**      * Photos grouped by person-cluster, for the People view.      *@@ -116,44 +116,58 @@ class GalleryViewModel(      * unrelated image.      */     val people: StateFlow<List<PersonCluster>> =-        combine(photoDao.getAllFlow(), faceDao.personsFlow(), faceDao.allFacesFlow()) { allPhotos, persons, faces ->-            val byId = allPhotos.filter { !it.isTrashed }.associateBy { it.id }-            val facesByCluster = faces.groupBy { it.clusterId }-            persons.mapNotNull { person ->-                val clusterFaces = facesByCluster[person.id].orEmpty()-                    .mapNotNull { face -> byId[face.photoId]?.let { face to it } }-                if (clusterFaces.isEmpty()) return@mapNotNull null-                val (bestFace, bestPhoto) = clusterFaces.maxBy { (face, photo) ->-                    (face.right - face.left).toDouble() * (face.bottom - face.top) *-                        photo.width * photo.height-                }-                PersonCluster(-                    id = person.id,-                    name = person.name,-                    coverPhoto = bestPhoto,-                    faceLeft = bestFace.left,-                    faceTop = bestFace.top,-                    faceRight = bestFace.right,-                    faceBottom = bestFace.bottom,-                    photos = clusterFaces.map { it.second }-                        .distinctBy { it.id }-                        .sortedByDescending { it.date },-                )-            }.sortedByDescending { it.photos.size }+        combine(photoDao.getAllFlow(), faceDao.personsFlow(), faceDao.faceGeometryFlow()) { allPhotos, persons, faces ->+            Triple(allPhotos, persons, faces)         }+            // Every per-photo write during indexing re-emits upstream, far faster+            // than the UI can consume. Conflating ahead of the projection means+            // superseded snapshots are dropped instead of projected and thrown away.+            .conflate()+            .map { (allPhotos, persons, faces) ->+                val byId = allPhotos.filter { !it.isTrashed }.associateBy { it.id }+                val facesByCluster = faces.groupBy { it.clusterId }+                persons.mapNotNull { person ->+                    val clusterFaces = facesByCluster[person.id].orEmpty()+                        .mapNotNull { face -> byId[face.photoId]?.let { face to it } }+                    if (clusterFaces.isEmpty()) return@mapNotNull null+                    val (bestFace, bestPhoto) = clusterFaces.maxBy { (face, photo) ->+                        (face.right - face.left).toDouble() * (face.bottom - face.top) *+                            photo.width * photo.height+                    }+                    PersonCluster(+                        id = person.id,+                        name = person.name,+                        coverPhoto = bestPhoto,+                        faceLeft = bestFace.left,+                        faceTop = bestFace.top,+                        faceRight = bestFace.right,+                        faceBottom = bestFace.bottom,+                        photos = clusterFaces.map { it.second }+                            .distinctBy { it.id }+                            .sortedByDescending { it.date },+                    )+                }.sortedByDescending { it.photos.size }+            }             // Per-photo writes during indexing re-emit the source flows constantly;             // drop emissions where the projected cluster list is unchanged (value             // equality of the PersonCluster data class) so the grid doesn't churn.             // The representative can legitimately change mid-scan, so real changes             // still get through.             .distinctUntilChanged()+            // Below flowOn, so the O(library) projection *and* the deep list+            // comparison above both run off the main thread. Without this,+            // stateIn(viewModelScope) runs every one of them on Main.immediate,+            // which is what delayed a freshly-entered name from reaching the grid.+            .flowOn(Dispatchers.Default)             .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())      /** Number of detected faces (i.e. people) per photo, for the photo detail overlay. */     val faceCountByPhoto: StateFlow<Map<Long, Int>> =-        faceDao.allFacesFlow().map { faces ->-            faces.groupBy { it.photoId }.mapValues { (_, list) -> list.size }-        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())+        faceDao.faceGeometryFlow()+            .conflate()+            .map { faces -> faces.groupBy { it.photoId }.mapValues { (_, list) -> list.size } }+            .flowOn(Dispatchers.Default)+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())      /**      * Face geometry per photo, for the viewer's face overlay. Combined with the@@ -161,26 +175,32 @@ class GalleryViewModel(      * not on the face row — which is also why [faceCountByPhoto] can't be reused.      */     val faceBoxesByPhoto: StateFlow<Map<Long, PhotoFaceBoxes>> =-        combine(faceDao.allFacesFlow(), faceDao.personsFlow()) { faces, persons ->-            val nameByCluster = persons.associate { it.id to it.name }-            faces.groupBy { it.photoId }.mapValues { (_, rows) ->-                PhotoFaceBoxes(-                    // Duplicated across a photo's rows, so any one of them serves.-                    srcWidth = rows.first().srcWidth,-                    srcHeight = rows.first().srcHeight,-                    faces = rows.map { row ->-                        FaceBox(-                            clusterId = row.clusterId,-                            name = nameByCluster[row.clusterId],-                            left = row.left,-                            top = row.top,-                            right = row.right,-                            bottom = row.bottom,-                        )-                    },-                )+        combine(faceDao.faceGeometryFlow(), faceDao.personsFlow()) { faces, persons ->+            faces to persons+        }+            .conflate()+            .map { (faces, persons) ->+                val nameByCluster = persons.associate { it.id to it.name }+                faces.groupBy { it.photoId }.mapValues { (_, rows) ->+                    PhotoFaceBoxes(+                        // Duplicated across a photo's rows, so any one of them serves.+                        srcWidth = rows.first().srcWidth,+                        srcHeight = rows.first().srcHeight,+                        faces = rows.map { row ->+                            FaceBox(+                                clusterId = row.clusterId,+                                name = nameByCluster[row.clusterId],+                                left = row.left,+                                top = row.top,+                                right = row.right,+                                bottom = row.bottom,+                            )+                        },+                    )+                }             }-        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())+            .flowOn(Dispatchers.Default)+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())      init {         // Debounced search: re-query whenever the query string changes.@@ -317,9 +337,25 @@ class GalleryViewModel(         SyncWorker.enqueue(getApplication())     } +    /**+     * The library photos a person-cluster appears in, newest first.+     *+     * Resolved on demand so the viewer doesn't have to collect the whole [people]+     * list (and recompute every cluster's cover photo) just to answer this for the+     * one face that was tapped.+     */+    suspend fun photosForCluster(clusterId: Long): List<Photo> {+        val ids = repository.photoIdsForCluster(clusterId).toSet()+        if (ids.isEmpty()) return emptyList()+        return photos.value.filter { it.id in ids && !it.isTrashed }+    }+     /** Name a person-cluster, or clear its name with null. */     fun setPersonName(id: Long, name: String?) {-        viewModelScope.launch(Dispatchers.IO) {+        // No Dispatchers.IO: Room runs suspend DAO functions on its own+        // dispatcher already, so naming an IO dispatcher here only queued the+        // write behind whatever image work was occupying it.+        viewModelScope.launch {             repository.setPersonName(id, name)         }     }
photos/src/main/java/com/vayunmathur/photos/util/ImageLoader.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/ImageLoader.kt b/photos/src/main/java/com/vayunmathur/photos/util/ImageLoader.ktindex 746c963c2a..9b9adef489 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/ImageLoader.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/ImageLoader.kt@@ -36,20 +36,36 @@ import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.R  object ImageLoader {-    private lateinit var imageLoader: LibImageLoader+    @Volatile+    private var instance: LibImageLoader? = null +    /**+     * Built on first use rather than only from `MainActivity.onCreate`.+     *+     * [PhotoItem] is reached from entry points that never run MainActivity — the+     * home-screen widget, the assistant, an incoming ACTION_VIEW — where a+     * `lateinit` field threw `UninitializedPropertyAccessException`.+     */+    private fun loader(context: Context): LibImageLoader =+        instance ?: synchronized(this) {+            instance ?: build(context.applicationContext).also { instance = it }+        }++    /** Warms the loader during app start; not required for correctness. */     fun init(context: Context) {-        imageLoader = LibImageLoader.Builder(context)-            .memoryCache {-                MemoryCache.Builder(context).maxSizePercent(0.25).build()-            }-            .diskCache {-                DiskCache.Builder().directory(context.cacheDir.resolve("image_cache")).maxSizePercent(0.05).build()-            }-            .respectCacheHeaders(false)-            .build()+        loader(context)     } +    private fun build(context: Context): LibImageLoader = LibImageLoader.Builder(context)+        .memoryCache {+            MemoryCache.Builder(context).maxSizePercent(0.25).build()+        }+        .diskCache {+            DiskCache.Builder().directory(context.cacheDir.resolve("image_cache")).maxSizePercent(0.05).build()+        }+        .respectCacheHeaders(false)+        .build()+     @Composable     fun PhotoItem(photo: Photo, modifier: Modifier, onClick: (() -> Unit)? = null) {         val context = LocalContext.current@@ -72,7 +88,7 @@ object ImageLoader {                     .crossfade(true)                     .size(256)                     .build(),-                imageLoader = imageLoader,+                imageLoader = loader(context),                 contentDescription = null,                 contentScale = ContentScale.Crop,                 modifier = Modifier.fillMaxSize()@@ -122,8 +138,8 @@ object ImageLoader {         onClick: () -> Unit,         /**          * How the tile paints its photo. A preview seam: the default decodes a MediaStore-         * URI through [imageLoader], which only exists once MainActivity has initialised it,-         * so the store-listing previews substitute a placeholder here.+         * URI through the shared loader, which Layoutlib cannot do, so the store-listing+         * previews substitute a placeholder here.          */         thumbnail: @Composable (Photo, Modifier) -> Unit = { p, m -> PhotoItem(p, m) },     ) {
photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.ktindex 872fdd023b..798cfee274 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SecureFolderViewModel.kt@@ -3,6 +3,9 @@ package com.vayunmathur.photos.util import android.app.Application import android.graphics.Bitmap import android.util.Log+import androidx.compose.runtime.MutableState+import androidx.compose.runtime.State+import androidx.compose.runtime.mutableStateOf import androidx.fragment.app.FragmentActivity import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModelProvider@@ -58,23 +61,43 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica      private val sfm: SecureFolderManager by lazy { SecureFolderManager(application) } +    /**+     * One observable holder per thumbnail path.+     *+     * A grid item observes only its own entry, so a decrypted thumbnail+     * recomposes that one cell. Publishing a new whole-map identity per decrypt+     * (which is what this replaced) invalidated every visible item instead, so+     * scrolling a vault cost O(visible items) recompositions per decrypt.+     */+    private val thumbStates = mutableMapOf<String, MutableState<Bitmap?>>()+     // Bounded LRU cache for decrypted thumbnails. Cap 64 to prevent unbounded     // bitmap retention while scrolling large vaults.-    // NOTE: Previous implementation recycled bitmaps synchronously in-    // removeEldestEntry while _thumbnails and Compose UI still held references,-    // causing "Canvas: trying to use a recycled bitmap" when column count >=4+    // NOTE: An earlier implementation recycled bitmaps synchronously in+    // removeEldestEntry while the UI still held references, causing+    // "Canvas: trying to use a recycled bitmap" when column count >=4     // (more thumbnails visible -> cache overflow -> recycled while drawing).-    // Fix: No recycling on eviction; let LRU evict without recycle and keep-    // _thumbnails in sync with cache (snapshot). Recycling only happens in-    // onCleared() after _thumbnails is emptied.+    // Nothing is recycled on eviction: the UI's reference is dropped and the+    // bitmap is left to the collector. Recycling only happens in onCleared(),+    // after every state holder has been cleared.     private val thumbCache = object : LinkedHashMap<String, Bitmap>(64, 0.75f, true) {         override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Bitmap>): Boolean {-            return size > 64+            if (size <= 64) return false+            thumbStates[eldest.key]?.value = null+            return true         }     } -    private val _thumbnails = MutableStateFlow<Map<String, Bitmap>>(emptyMap())-    val thumbnails: StateFlow<Map<String, Bitmap>> = _thumbnails.asStateFlow()+    /**+     * Observable holder for one thumbnail, created on first request and kept for the+     * life of the ViewModel: an item has to keep observing the same instance to be+     * told when its thumbnail is re-decrypted after an eviction.+     */+    fun thumbnailState(thumbnailPath: String): State<Bitmap?> = synchronized(thumbCache) {+        thumbStates.getOrPut(thumbnailPath) {+            mutableStateOf(thumbCache[thumbnailPath]?.takeIf { !it.isRecycled })+        }+    }      fun setVault(dao: VaultPhotoDao, password: String) {         _vaultPassword.value = password@@ -105,46 +128,43 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica     }      /**-     * Decrypt a single thumbnail and publish into [thumbnails]. Composables read-     * `thumbnails.collectAsState()` and look up by path. Cached results return-     * immediately without re-decrypting.+     * Decrypt a single thumbnail and publish it into that path's state holder (see+     * [thumbnailState]). Cached results return immediately without re-decrypting.      */     fun requestThumbnail(thumbnailPath: String, password: String) {         synchronized(thumbCache) {             val cached = thumbCache[thumbnailPath]             if (cached != null) {                 if (!cached.isRecycled) {-                    if (_thumbnails.value[thumbnailPath] !== cached) {-                        // Keep _thumbnails in sync with cache snapshot-                        _thumbnails.value = thumbCache.toMap()-                    }+                    thumbStates[thumbnailPath]?.value = cached                     return                 } else {                     // Drop recycled entry if it somehow ended up recycled                     thumbCache.remove(thumbnailPath)+                    thumbStates[thumbnailPath]?.value = null                 }             }         }         viewModelScope.launch(Dispatchers.IO) {             try {                 val bmp = sfm.decryptThumbnail(thumbnailPath, password) ?: return@launch-                val snapshot: Map<String, Bitmap>+                val published: Bitmap                 synchronized(thumbCache) {                     val existing = thumbCache[thumbnailPath]                     if (existing != null && !existing.isRecycled) {                         // Another thread already inserted, recycle the duplicate we just decrypted                         try { bmp.recycle() } catch (e: Exception) { Log.w(TAG, "Failed to recycle duplicate thumbnail", e) }-                        snapshot = thumbCache.toMap()+                        published = existing                     } else {                         if (existing != null) {                             // Existing was recycled, remove it                             thumbCache.remove(thumbnailPath)                         }                         thumbCache[thumbnailPath] = bmp-                        snapshot = thumbCache.toMap()+                        published = bmp                     }+                    thumbStates[thumbnailPath]?.value = published                 }-                _thumbnails.value = snapshot             } catch (e: Exception) {                 Log.e(TAG, "decryptThumbnail failed for $thumbnailPath", e)             }@@ -251,9 +271,11 @@ class SecureFolderViewModel(application: Application) : AndroidViewModel(applica     }      override fun onCleared() {-        // Clear _thumbnails first so Compose no longer holds references, then recycle-        _thumbnails.value = emptyMap()         synchronized(thumbCache) {+            // Clear every holder first so the UI no longer references any bitmap,+            // then recycle. Order matters: this is the one place recycling happens.+            thumbStates.values.forEach { it.value = null }+            thumbStates.clear()             thumbCache.values.forEach { bmp ->                 try { if (!bmp.isRecycled) bmp.recycle() } catch (e: Exception) { Log.w(TAG, "Failed to recycle thumbnail on clear", e) }             }
photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.ktindex c0bf04c428..2d53b0bb1e 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -26,6 +26,9 @@ import androidx.work.WorkerParameters import androidx.work.ListenableWorker.Result as WorkResult import com.vayunmathur.library.ocr.OcrEngine import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.photos.data.ClipResult+import com.vayunmathur.photos.data.ExifResult+import com.vayunmathur.photos.data.OcrResult import com.vayunmathur.photos.data.Person import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.PhotoFace@@ -39,6 +42,7 @@ import android.graphics.Bitmap import android.graphics.ImageDecoder import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope@@ -70,8 +74,7 @@ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c             syncPhotos(applicationContext, repository, null, if (needsMimeBackfill) 0L else lastGeneration)         }         -        val photos = repository.getAll()-        setExifData(photos, repository, applicationContext)+        setExifData(repository, applicationContext)                  // OCR and face grouping are both always on (no opt-in). Each worker is         // inert if its data/model assets are missing.@@ -311,15 +314,25 @@ private fun Context.syncForegroundInfo(     return ForegroundInfo(notificationId, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) } -suspend fun setExifData(photos: List<Photo>, repository: PhotosRepository, context: Context) = coroutineScope {-    val ps = photos.filter { !it.exifSet }.sortedByDescending { it.date }-    ps.chunked(50).forEach { photosChunk ->-        val newPhotos = photosChunk.map { photo ->+/**+ * Parse EXIF/XMP for every photo that hasn't been through it yet and write the+ * geo/panorama columns back.+ *+ * Driven off a projection of the un-parsed rows rather than the whole library:+ * this used to be handed `getAll()` (a `SELECT *` over every photo, embeddings+ * included) and wrote those same blobs straight back via `upsertAll`. The write+ * is column-targeted for the same reason — reconstructing a [Photo] from the+ * projection and upserting it would write NULL over every clipEmbedding.+ */+suspend fun setExifData(repository: PhotosRepository, context: Context) = coroutineScope {+    val targets = repository.getUnscannedForExif()+    targets.chunked(EXIF_CHUNK).forEach { chunk ->+        val results = chunk.map { target ->             async(Dispatchers.IO) {                 try {                     val (latLong, panoData) = context.contentResolver.openInputStream(                         MediaStore.setRequireOriginal(-                            photo.uri.toUri()+                            target.uri.toUri()                         )                     )?.use { inputStream ->                         val exif = ExifInterface(inputStream)@@ -327,21 +340,24 @@ suspend fun setExifData(photos: List<Photo>, repository: PhotosRepository, conte                         val pano = PanoXmpParser.parse(exif.getAttribute(ExifInterface.TAG_XMP))                         Pair(ll, pano)                     } ?: Pair(null, null)-                    photo.copy(-                        exifSet = true,+                    ExifResult(+                        id = target.id,                         lat = latLong?.getOrNull(0),                         long = latLong?.getOrNull(1),-                        panoData = panoData,+                        pano = panoData,                     )                 } catch (_: Exception) {-                    photo.copy(exifSet = true) // Mark as set even on error to avoid retry every time+                    // Mark as set even on error to avoid retry every time.+                    ExifResult(id = target.id, lat = null, long = null, pano = null)                 }             }         }.awaitAll()-        repository.upsertAll(newPhotos)+        repository.setExifResults(results)     } } +private const val EXIF_CHUNK = 50+ /**  * Sustained on-device AI indexing (OCR, CLIP, face models) heats the phone.  * On top of the short per-item pauses, each indexing loop takes a longer@@ -362,7 +378,7 @@ private const val BATCH_COOLDOWN_EVERY = 20 private const val BATCH_COOLDOWN_MS = 5_000L  suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineScope {-    val photos = repository.getUnscannedForOCR().sortedByDescending { it.date }+    val photos = repository.getUnscannedForOCR()     if (photos.isEmpty()) return@coroutineScope      val ocrEngine = OcrEngine(context)@@ -372,6 +388,22 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc         return@coroutineScope     } +    // Accumulated so a scan invalidates the Photo table once per flush rather+    // than once per photo. Flushed in a `finally` so cancellation and errors+    // still persist the work already done.+    val pendingResults = mutableListOf<OcrResult>()+    val pendingSkipped = mutableListOf<Long>()+    suspend fun flush() {+        if (pendingResults.isNotEmpty()) {+            repository.setOcrResults(pendingResults.toList())+            pendingResults.clear()+        }+        if (pendingSkipped.isNotEmpty()) {+            repository.setOcrScanned(pendingSkipped.toList())+            pendingSkipped.clear()+        }+    }+     var processed = 0     try {         for (photo in photos) {@@ -380,7 +412,8 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc             // Skip tiny images (icons/thumbnails); mark scanned so we don't retry.             val largestDim = maxOf(photo.width, photo.height)             if (largestDim in 1 until MIN_OCR_DIM) {-                repository.upsertAll(listOf(photo.copy(ocrScanned = true)))+                pendingSkipped += photo.id+                if (pendingSkipped.size >= INDEX_FLUSH_EVERY) flush()                 continue             } @@ -406,11 +439,12 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc              // Store result and mark scanned regardless of outcome (mirrors faces).             val text = result?.text-            repository.upsertAll(listOf(photo.copy(-                ocrText = text,-                ocrBoxes = result?.takeIf { it.boxes.isNotEmpty() }?.toJson(),-                ocrScanned = true,-            )))+            pendingResults += OcrResult(+                id = photo.id,+                text = text,+                boxes = result?.takeIf { it.boxes.isNotEmpty() }?.toJson(),+            )+            if (pendingResults.size >= INDEX_FLUSH_EVERY) flush()             Log.i("OCRWorker", "OCR for ${photo.id}: ${text?.take(50)?.replace("\n", " ")}")              // Short pause between images keeps sustained CPU/battery use low.@@ -421,9 +455,21 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc         }     } finally {         ocrEngine.close()+        // runCatching so a failed flush cannot replace the exception that unwound us+        // (a CancellationException in particular). Unflushed photos simply stay+        // unscanned and are picked up by the next run.+        withContext(NonCancellable) { runCatching { flush() } }     } } +/**+ * How many indexed photos accumulate before their rows are written. Each flush+ * is one transaction and therefore one Photo-table invalidation, which every+ * gallery flow reacts to — at one write per photo the UI spent a scan+ * recomputing rather than drawing.+ */+private const val INDEX_FLUSH_EVERY = 25+ private const val OCR_INTER_ITEM_DELAY_MS = 250L  class ClipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {@@ -494,40 +540,57 @@ suspend fun runClipIndexing(repository: PhotosRepository, context: Context) = co         dataStore.setString("clip_model_id", modelId)     } -    val photos = repository.getUnscannedForClip().sortedByDescending { it.date }+    val photos = repository.getUnscannedForClip()     if (photos.isEmpty()) return@coroutineScope +    // See INDEX_FLUSH_EVERY: batched so a scan doesn't invalidate the Photo+    // table once per embedded photo.+    val pending = mutableListOf<ClipResult>()+    suspend fun flush() {+        if (pending.isEmpty()) return+        repository.setClipResults(pending.toList())+        pending.clear()+    }+     var processed = 0-    for (photo in photos) {-        ensureActive()--        val t0 = System.currentTimeMillis()-        val embedding = try {-            ClipEmbedder.imageEmbedding(context, photo.uri.toUri())-        } catch (e: ClipEmbedder.ImageFailedException) {-            // The embedder is healthy but this one image couldn't be decoded: mark it scanned-            // with no vector so we skip it rather than blocking the queue on it forever.-            Log.w("ClipWorker", "Skipping un-embeddable photo ${photo.id}: ${e.message}")-            repository.upsertAll(listOf(photo.copy(clipEmbedding = null, clipScanned = true)))-            delay(CLIP_INTER_ITEM_DELAY_MS)-            continue-        } catch (e: CancellationException) {-            throw e-        } catch (e: Exception) {-            // Anything else is systemic (model failed to load): stop the run WITHOUT marking-            // scanned so these photos retry on the next pass.-            Log.w("ClipWorker", "Embedding unavailable; pausing indexing", e)-            return@coroutineScope-        }+    try {+        for (photo in photos) {+            ensureActive()++            val t0 = System.currentTimeMillis()+            val embedding = try {+                ClipEmbedder.imageEmbedding(context, photo.uri.toUri())+            } catch (e: ClipEmbedder.ImageFailedException) {+                // The embedder is healthy but this one image couldn't be decoded: mark it scanned+                // with no vector so we skip it rather than blocking the queue on it forever.+                Log.w("ClipWorker", "Skipping un-embeddable photo ${photo.id}: ${e.message}")+                pending += ClipResult(id = photo.id, embedding = null)+                if (pending.size >= INDEX_FLUSH_EVERY) flush()+                delay(CLIP_INTER_ITEM_DELAY_MS)+                continue+            } catch (e: CancellationException) {+                throw e+            } catch (e: Exception) {+                // Anything else is systemic (model failed to load): stop the run WITHOUT marking+                // scanned so these photos retry on the next pass.+                Log.w("ClipWorker", "Embedding unavailable; pausing indexing", e)+                return@coroutineScope+            } -        Log.d("ClipWorker", "Embedded photo ${photo.id} (${embedding.size}d) in ${System.currentTimeMillis() - t0}ms")-        repository.upsertAll(listOf(photo.copy(clipEmbedding = ClipEmbedder.floatsToBytes(embedding), clipScanned = true)))+            Log.d("ClipWorker", "Embedded photo ${photo.id} (${embedding.size}d) in ${System.currentTimeMillis() - t0}ms")+            pending += ClipResult(id = photo.id, embedding = ClipEmbedder.floatsToBytes(embedding))+            if (pending.size >= INDEX_FLUSH_EVERY) flush() -        // Short pause between images keeps sustained CPU/battery use low.-        delay(CLIP_INTER_ITEM_DELAY_MS)-        // Longer cooling break every batch so the device can shed heat.-        processed++-        coolDownBetweenBatches(processed, "ClipWorker")+            // Short pause between images keeps sustained CPU/battery use low.+            delay(CLIP_INTER_ITEM_DELAY_MS)+            // Longer cooling break every batch so the device can shed heat.+            processed+++            coolDownBetweenBatches(processed, "ClipWorker")+        }+    } finally {+        // Covers the systemic-failure return above as well as cancellation, so+        // photos already embedded in this run are never re-embedded.+        withContext(NonCancellable) { runCatching { flush() } }     } } @@ -605,60 +668,77 @@ suspend fun runFaceIndexing(repository: PhotosRepository, context: Context) {         .map { Cluster(it, FaceRecognizer.bytesToFloats(it.centroid)) }         .toMutableList() -    val photos = repository.getUnscannedForFaces().sortedByDescending { it.date }+    val photos = repository.getUnscannedForFaces()     Log.i("FaceWorker", "Face indexing start: ${photos.size} photos to scan, ${clusters.size} existing clusters")     var facesTotal = 0     var photosWithFaces = 0     var decoded = 0-    for (photo in photos) {-        currentCoroutineContext().ensureActive() -        var didInference = false-        try {-            val bitmap = loadBitmapForFaces(context, photo.uri.toUri())-            if (bitmap != null) {-                decoded++-                didInference = true-                // Read before recycle: the box columns are normalised against-                // this bitmap, so its dimensions have to be stored with them.-                val srcWidth = bitmap.width-                val srcHeight = bitmap.height-                val faces = FaceRecognizer.detectAndEmbed(context, bitmap)-                bitmap.recycle()-                if (faces.isNotEmpty()) {-                    photosWithFaces++; facesTotal += faces.size-                    Log.i("FaceWorker", "photo ${photo.id}: ${faces.size} face(s) (running total: $facesTotal)")-                }-                val rows = faces.map { face ->-                    val clusterId = assignToCluster(face, clusters, repository)-                    PhotoFace(-                        photoId = photo.id,-                        clusterId = clusterId,-                        embedding = FaceRecognizer.floatsToBytes(face.embedding),-                        left = face.left,-                        top = face.top,-                        right = face.right,-                        bottom = face.bottom,-                        srcWidth = srcWidth,-                        srcHeight = srcHeight,-                    )+    // See INDEX_FLUSH_EVERY. Face rows are accumulated alongside the scanned ids and+    // committed with them in one transaction, so a batch is all-or-nothing: a worker+    // killed mid-batch cannot leave rows behind that a re-scan would duplicate.+    val pendingScanned = mutableListOf<Long>()+    val pendingFaces = mutableListOf<PhotoFace>()+    suspend fun flush() {+        if (pendingScanned.isEmpty()) return+        repository.commitFaceScan(pendingScanned.toList(), pendingFaces.toList())+        pendingScanned.clear()+        pendingFaces.clear()+    }++    try {+        for (photo in photos) {+            currentCoroutineContext().ensureActive()++            var didInference = false+            try {+                val bitmap = loadBitmapForFaces(context, photo.uri.toUri())+                if (bitmap != null) {+                    decoded+++                    didInference = true+                    // Read before recycle: the box columns are normalised against+                    // this bitmap, so its dimensions have to be stored with them.+                    val srcWidth = bitmap.width+                    val srcHeight = bitmap.height+                    val faces = FaceRecognizer.detectAndEmbed(context, bitmap)+                    bitmap.recycle()+                    if (faces.isNotEmpty()) {+                        photosWithFaces++; facesTotal += faces.size+                        Log.i("FaceWorker", "photo ${photo.id}: ${faces.size} face(s) (running total: $facesTotal)")+                    }+                    pendingFaces += faces.map { face ->+                        val clusterId = assignToCluster(face, clusters, repository)+                        PhotoFace(+                            photoId = photo.id,+                            clusterId = clusterId,+                            embedding = FaceRecognizer.floatsToBytes(face.embedding),+                            left = face.left,+                            top = face.top,+                            right = face.right,+                            bottom = face.bottom,+                            srcWidth = srcWidth,+                            srcHeight = srcHeight,+                        )+                    }                 }-                if (rows.isNotEmpty()) repository.insertPhotoFaces(rows)+            } catch (e: Exception) {+                Log.e("FaceWorker", "Error scanning faces for photo ${photo.id}", e)             }-        } catch (e: Exception) {-            Log.e("FaceWorker", "Error scanning faces for photo ${photo.id}", e)-        } -        // Mark scanned regardless of outcome so we don't retry forever.-        repository.upsertAll(listOf(photo.copy(faceScanned = true)))+            // Mark scanned regardless of outcome so we don't retry forever.+            pendingScanned += photo.id+            if (pendingScanned.size >= INDEX_FLUSH_EVERY) flush() -        // Face indexing runs two ONNX models per photo (detector + embedder), so-        // pace it like OCR/CLIP: a short pause after each photo we actually ran-        // inference on, plus a longer cooling break every batch.-        if (didInference) {-            delay(FACE_INTER_ITEM_DELAY_MS)-            coolDownBetweenBatches(decoded, "FaceWorker")+            // Face indexing runs two ONNX models per photo (detector + embedder), so+            // pace it like OCR/CLIP: a short pause after each photo we actually ran+            // inference on, plus a longer cooling break every batch.+            if (didInference) {+                delay(FACE_INTER_ITEM_DELAY_MS)+                coolDownBetweenBatches(decoded, "FaceWorker")+            }         }+    } finally 

Diff truncated.