Modern Apps git

← Modern-Apps.git

photos: favourite photos and a Favourites album (#912)

Commit
c9351adddf6a50b6750542bc675c3cfb564baad7
Author
Vayun Mathur <[email protected]>
When
2026-11-12 19:27 UTC (23 days ago)
Parents
6eeb9c3
Request (#912): other gallery apps let you favourite photos and see
them together in one album; Photos had neither.

Design
- Source of truth is MediaStore's IS_FAVORITE (API 30+, minSdk is 31),
  not an app-only table, so favourites survive a reinstall and match
  every other gallery on the device. The Photo row mirrors it the same
  way it mirrors IS_TRASHED.
- PhotoDatabase 19 -> 20: hand-written MIGRATION_19_20 adds
  `isFavorite INTEGER NOT NULL DEFAULT 0` (Room's schema for the new
  `isFavorite: Boolean = false` field). getAllFlow's explicit column
  list gains it, and PhotoDao.setFavorite writes it by column.
- Sync: IS_FAVORITE joins the image and video projections. A row whose
  only change is IS_FAVORITE (a heart tapped here or in another app;
  both bump GENERATION_MODIFIED, so the incremental scan sees it) is
  written with the column-targeted update instead of re-upserting the
  rebuilt row, which would drop its CLIP embedding and OCR geometry and
  send it back through indexing. New or otherwise-changed rows carry the
  flag in the upsert.
- One-time rescan: the migration starts every row at 0 and an
  incremental scan only sees rows modified since the last sync, so the
  untriggered sync now runs one full MediaStore pass until a DataStore
  flag (favorites_rescan_done) is set. It is set only after a full pass
  completed, so it runs once after the upgrade (a fresh install's first
  full sync sets it too), and content-triggered syncs never consume it.

Toggling and consent
- platform/FavoriteToggler drives MediaStore.createFavoriteRequest: it
  updates the local rows at once (heart and album react immediately),
  then returns the request's PendingIntent, which the UI launches with
  an activity-result launcher exactly like the trash request. With the
  "manage media" access the app already requires, MediaStore applies it
  without a dialog; without it the system asks, and a refusal (or a
  request MediaStore will not build, which also shows a snackbar)
  reverts the local rows. Selections are sent in requests of at most
  500 URIs, launched one after another. A granted request resyncs.
- domain/FavoriteRule: a toggle unfavourites only when every item is a
  favourite; a mixed selection favourites all. Items already in the
  target state are not sent.
- The toggler lives on GalleryViewModel so a request waiting on the
  system dialog survives a configuration change.

UI
- Viewer: a heart (outlined / filled) in the bottom action row next to
  wallpaper/edit/share/delete. Deviation from the plan: it goes in
  PhotoMetadataCard, not PhotoViewerActions.kt, because
  PhotoViewerActions is not rendered by the viewer at all (only tests
  use it); PhotoMetadataCard holds the viewer's real action row. The
  heart reads the live rows, so it is right even when the viewer was
  opened over an album, person or search snapshot.
- Grid multi-select: a heart action, applied to every selected item
  (filled = "Remove from favorites" only when all are favourites). The
  selection actions moved into GallerySelectionActions, and the
  launcher-backed GalleryActions out of GalleryPage into
  rememberGalleryActions, so the gallery and the Favorites album share
  them unchanged.
- Albums: a Favorites default tile before Trash, with the count and
  the newest favourite as its cover (a heart icon while empty). It
  opens FavoritesScreen: the favourites grid (trashed items excluded)
  with the gallery's month grouping, pinch-zoom, pull-to-refresh,
  selection actions and viewer.
- library/ui: IconFavoriteBorder added; IconFavorite and it take an
  optional contentDescription (as IconBook does) so the heart is
  announced as "Favorite" / "Remove from favorites".
- Sources: every gallery item is a MediaStore image or video (Secure
  Folder items live in the encrypted vault and never reach this grid or
  viewer), so there is no cloud or non-MediaStore item to hide the heart
  for. Videos are favourited like photos. An item deleted elsewhere
  drops out of Favorites on the next sync with the rest of its row.
- Store listing: new 5-albums preview showing the Favorites tile; the
  2-selection preview gains the heart. phone/2.png and the new
  phone/4.png are regenerated by `./gradlew :photos:metadata` in the
  build container (the other three listing images re-rendered
  byte-identical and are unchanged).

User-visible effect: tap the heart in the viewer, or select photos and
tap the heart, to favourite them; Albums shows a Favorites album with
them, and favourites set in any other gallery app appear here too.

Verification (build container, one commit):
- :photos:compileDevKotlin and :library:ui:compileDebugKotlin pass.
- :photos:testDevUnitTest: 612 tests, 1 failure,
  Slice2Pass2LogicTest.exportStartFailureResetsStateAndLeavesNoTempFile
  (video export), which fails the same way on main.
- New tests (29, all passing): migration 19->20 over populated v19 rows
  (column type/default, rows and other columns intact) and setFavorite
  being column-targeted; sync picking up IS_FAVORITE from another app
  via the column update, the flag on new rows and videos, deleted
  favourites dropping out, and the full rescan running exactly once
  (and not consuming the mime backfill); FavoriteToggler against a
  recording request factory (mixed rule, 500-URI batches, busy,
  decline and refusal reverts) and MediaStoreFavoriteRequests against a
  fake MediaStore provider; FavoriteRule; the Favorites list excluding
  trashed items; Compose tests for the viewer heart, the selection
  heart, the Favorites tile and page. Existing tests updated for the
  new migration and store method; the albums empty-copy test now
  scrolls past the extra default tile.
- :photos:lint, :photos:detekt and :library:ui:detekt report only
  findings in lines and files this change does not touch (4 lint
  errors in untouched tests; detekt in ClipEmbedder,
  VideoEditViewModel, IconsSliceTest and four pre-existing long lines
  in GalleryViewModel). Nothing new in library/ui.

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex d417afb903..85b8bda5a9 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -176,6 +176,7 @@ import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.EmojiEvents import androidx.compose.material.icons.filled.Event import androidx.compose.material.icons.filled.Favorite+import androidx.compose.material.icons.filled.FavoriteBorder import androidx.compose.material.icons.filled.FlashAuto import androidx.compose.material.icons.filled.FlashOff import androidx.compose.material.icons.filled.FlashOn@@ -561,9 +562,21 @@ fun IconMarkRead(modifier: Modifier = Modifier, tint: Color = LocalContentColor. fun IconMarkUnread(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Outlined.MailOutline, "Mark Unread", modifier, tint) +/** A filled heart. [contentDescription] defaults to "Favorite"; pass the control's own label. */ @Composable-fun IconFavorite(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =-    AppIcon(Icons.Filled.Favorite, "Favorite", modifier, tint)+fun IconFavorite(+    modifier: Modifier = Modifier,+    tint: Color = LocalContentColor.current,+    contentDescription: String? = "Favorite",+) = AppIcon(Icons.Filled.Favorite, contentDescription, modifier, tint)++/** An outlined heart, the "not a favourite" state of [IconFavorite]. */+@Composable+fun IconFavoriteBorder(+    modifier: Modifier = Modifier,+    tint: Color = LocalContentColor.current,+    contentDescription: String? = "Favorite",+) = AppIcon(Icons.Filled.FavoriteBorder, contentDescription, modifier, tint)  @Composable fun IconFire(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =
metadata_data/photos/photos/phone/2.png
diff --git a/metadata_data/photos/photos/phone/2.png b/metadata_data/photos/photos/phone/2.pngindex 3342a013d5..8b54e1621c 100644Binary files a/metadata_data/photos/photos/phone/2.png and b/metadata_data/photos/photos/phone/2.png differ
metadata_data/photos/photos/phone/4.png
diff --git a/metadata_data/photos/photos/phone/4.png b/metadata_data/photos/photos/phone/4.pngnew file mode 100644index 0000000000..85d3da0884Binary files /dev/null and b/metadata_data/photos/photos/phone/4.png differ
photos/src/main/java/com/vayunmathur/photos/MainActivity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt b/photos/src/main/java/com/vayunmathur/photos/MainActivity.ktindex 3ba7b359e6..8e4a3cf862 100644--- a/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt+++ b/photos/src/main/java/com/vayunmathur/photos/MainActivity.kt@@ -53,6 +53,7 @@ import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.PhotosRepository import com.vayunmathur.photos.glance.PhotoGlanceWidgetReceiver import com.vayunmathur.photos.ui.AlbumDetailPage+import com.vayunmathur.photos.ui.FavoritesPage import com.vayunmathur.photos.ui.AlbumsPage import com.vayunmathur.photos.ui.GalleryPage import com.vayunmathur.photos.ui.MapPage@@ -165,6 +166,10 @@ sealed interface Route: NavKey {     @Serializable     data class AlbumDetail(val albumName: String): Route +    /** The Favorites album: every MediaStore favorite, opened from its Albums tile. */+    @Serializable+    data object Favorites: Route+     @Serializable     data object Trash: Route @@ -268,8 +273,12 @@ fun Navigation(         }          // Built-in collections, opened from the Albums grid's default tiles-        // (Trash, Secure Folder). Detail pages: they push over Albums and show-        // a back arrow instead of the bottom bar.+        // (Favorites, Trash, Secure Folder). Detail pages: they push over Albums+        // and show a back arrow instead of the bottom bar.+        entry<Route.Favorites> {+            FavoritesPage(backStack, galleryViewModel, secureFolderViewModel)+        }+         entry<Route.Trash> {             TrashPage(backStack, galleryViewModel)         }
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 58712b4f09..3f36f48e0d 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt@@ -82,6 +82,10 @@ data class Photo(     // in. Null only on rows written before the column existed, which the next     // sync backfills; the Albums view shows those as Unknown meanwhile.     val album: String? = null,+    // MediaStore IS_FAVORITE, mirrored like [isTrashed]: MediaStore owns the+    // flag (so favourites survive a reinstall and match other gallery apps),+    // the sync copies it here, and the Favourites album reads it from here.+    val isFavorite: Boolean = false, ) : DatabaseItem {     /** True for an animated image, which plays rather than showing a single frame. */     val isGif: Boolean get() = mimeType.equals("image/gif", ignoreCase = true)
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 859846e873..28366e678e 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -28,7 +28,7 @@ interface PhotoDao {     @Query(         "SELECT id, name, uri, date, width, height, dateModified, exifSet, lat, `long`, duration, " +             "fullWidth, fullHeight, croppedWidth, croppedHeight, croppedLeft, croppedTop, projectionType, " +-            "isTrashed, faceScanned, ocrScanned, clipScanned, mimeType, album FROM Photo ORDER BY date DESC"+            "isTrashed, faceScanned, ocrScanned, clipScanned, mimeType, album, isFavorite FROM Photo ORDER BY date DESC"     )     fun getAllFlow(): Flow<List<Photo>> @@ -61,6 +61,14 @@ interface PhotoDao {     @Query("UPDATE Photo SET album = :album WHERE id IN (:ids)")     suspend fun setAlbum(ids: List<Long>, album: String?) +    /**+     * Mirror MediaStore's IS_FAVORITE for [ids]. Column-targeted, like [setAlbum],+     * so neither the optimistic toggle nor the sync's favourite-only diff+     * rewrites (and nulls) the clipEmbedding BLOB.+     */+    @Query("UPDATE Photo SET isFavorite = :value WHERE id IN (:ids)")+    suspend fun setFavorite(ids: List<Long>, value: Boolean)+     @Query(         "SELECT * FROM Photo WHERE isTrashed = 0 AND " +             "(ocrText LIKE '%' || :query || '%' OR name LIKE '%' || :query || '%') ORDER BY date DESC"@@ -284,7 +292,7 @@ data class ExifResult(     val pano: PanoData?, ) -@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 19, exportSchema = false)+@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 20, exportSchema = false) abstract class PhotoDatabase : RoomDatabase() {     abstract fun photoDao(): PhotoDao     abstract fun photoScanDao(): PhotoScanDao@@ -295,7 +303,7 @@ abstract class PhotoDatabase : RoomDatabase() {             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, MIGRATION_17_18, MIGRATION_18_19,+            MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20,         )     } }@@ -403,6 +411,14 @@ val MIGRATION_18_19 = Migration(18, 19) {     it.execSQL("UPDATE Photo SET faceScanned = 0") } +val MIGRATION_19_20 = Migration(19, 20) {+    // Mirror MediaStore's IS_FAVORITE (#912). Existing rows start as not+    // favourite; SyncWorker runs one full MediaStore rescan after this upgrade+    // (see FAVORITES_RESCAN_DONE_KEY) so items already favourited in another+    // gallery app show up. SQL mirrors Room's generated schema exactly.+    it.execSQL("ALTER TABLE Photo ADD COLUMN isFavorite INTEGER NOT NULL DEFAULT 0")+}+ 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 0e9475b969..8715bb35c3 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -38,6 +38,7 @@ open class PhotosRepository internal constructor(context: Context) :     open suspend fun deleteByIds(ids: List<Long>) = photoDao.deleteByIds(ids)     suspend fun setTrashed(id: Long) = photoDao.setTrashed(id)     suspend fun setAlbum(ids: List<Long>, album: String?) = photoDao.setAlbum(ids, album)+    open suspend fun setFavorite(ids: List<Long>, value: Boolean) = photoDao.setFavorite(ids, value)     suspend fun searchPhotos(query: String): List<Photo> = photoDao.searchPhotos(query)      companion object {
photos/src/main/java/com/vayunmathur/photos/domain/FavoriteRule.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/FavoriteRule.kt b/photos/src/main/java/com/vayunmathur/photos/domain/FavoriteRule.ktnew file mode 100644index 0000000000..6e2c0b3cc9--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/FavoriteRule.kt@@ -0,0 +1,22 @@+package com.vayunmathur.photos.domain++/**+ * What a favourite toggle does to a set of items (#912), shared by the viewer's+ * heart and the grid's multi-select action so both follow one rule.+ */+object FavoriteRule {++    /**+     * Most URIs sent in one MediaStore favourite request. The URIs travel as+     * ClipData through a binder call, so a selection of the whole library is+     * split into requests of this size and run one after another.+     */+    const val MAX_URIS_PER_REQUEST = 500++    /**+     * The value a toggle applies to items whose current favourite flags are+     * [current]: unfavourite only when every item already is a favourite;+     * a mixed (or empty) selection favourites everything.+     */+    fun targetValue(current: Collection<Boolean>): Boolean = current.isEmpty() || !current.all { it }+}
photos/src/main/java/com/vayunmathur/photos/platform/FavoriteToggler.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/platform/FavoriteToggler.kt b/photos/src/main/java/com/vayunmathur/photos/platform/FavoriteToggler.ktnew file mode 100644index 0000000000..47695d505c--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/platform/FavoriteToggler.kt@@ -0,0 +1,145 @@+package com.vayunmathur.photos.platform++import android.app.PendingIntent+import android.content.ContentResolver+import android.net.Uri+import android.provider.MediaStore+import androidx.core.net.toUri+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.FavoriteRule+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * Builds the MediaStore request that sets IS_FAVORITE on [uris]. An interface+ * so tests can count and inspect requests; production is+ * [MediaStoreFavoriteRequests].+ */+fun interface FavoriteRequestFactory {+    fun create(uris: List<Uri>, value: Boolean): PendingIntent+}++/** [FavoriteRequestFactory] over [MediaStore.createFavoriteRequest]. */+class MediaStoreFavoriteRequests(private val resolver: ContentResolver) : FavoriteRequestFactory {+    override fun create(uris: List<Uri>, value: Boolean): PendingIntent =+        MediaStore.createFavoriteRequest(resolver, uris, value)+}++/**+ * Favourites and unfavourites photos through MediaStore (#912), which owns+ * IS_FAVORITE; the local Photo rows only mirror it.+ *+ * A toggle updates the local rows at once (so the heart and the Favourites+ * album react immediately), then hands back the request's PendingIntent for+ * the caller to launch with an activity-result launcher, exactly like the+ * trash flow. With the app's "manage media" access granted, MediaStore applies+ * it without a dialog; without it, the system asks the user, and a refusal+ * reverts the local rows. Selections over [FavoriteRule.MAX_URIS_PER_REQUEST]+ * go out as consecutive requests, each launched when the previous one+ * succeeded. Once every request succeeded, [onApplied] runs (a resync), which+ * reconciles anything else that changed.+ *+ * Not thread-safe: call it from the main thread, as the composables do.+ */+class FavoriteToggler(+    private val writeLocal: suspend (ids: List<Long>, value: Boolean) -> Unit,+    private val requests: FavoriteRequestFactory,+    private val scope: CoroutineScope,+    private val onApplied: () -> Unit = {},+) {+    /** What the caller does next. */+    sealed interface Step {+        /** Launch [intent] and report its result to [onResult]. */+        data class Launch(val intent: PendingIntent) : Step++        /** Everything requested is applied (or there was nothing to change). */+        data object Done : Step++        /** The user declined; the local rows were reverted. */+        data object Cancelled : Step++        /** MediaStore refused to build the request; the local rows were reverted. */+        data object Failed : Step++        /** A previous toggle is still waiting for its result; nothing was done. */+        data object Busy : Step+    }++    private val pending = ArrayDeque<List<Photo>>()+    private var inFlight: List<Photo>? = null+    private var value = false++    // Local writes run in order: a revert must never land before the+    // optimistic write it undoes. Mutex is FIFO.+    private val writes = Mutex()++    /** Toggle [photos] together by [FavoriteRule.targetValue]: a mixed selection is favourited. */+    fun toggle(photos: List<Photo>): Step =+        setFavorite(photos, FavoriteRule.targetValue(photos.map { it.isFavorite }))++    /** Set IS_FAVORITE to [value] on every photo in [photos]. */+    fun setFavorite(photos: List<Photo>, value: Boolean): Step {+        if (inFlight != null) return Step.Busy+        val changing = photos.filter { it.isFavorite != value }+        if (changing.isEmpty()) return Step.Done+        this.value = value+        write(changing, value)+        pending.addAll(changing.chunked(FavoriteRule.MAX_URIS_PER_REQUEST))+        return next()+    }++    /** Report the launched request's result; returns the next step. */+    fun onResult(granted: Boolean): Step {+        val batch = inFlight ?: return Step.Done+        inFlight = null+        if (!granted) {+            abandon(batch)+            return Step.Cancelled+        }+        return next()+    }++    private fun next(): Step {+        val batch = pending.removeFirstOrNull()+        if (batch == null) {+            onApplied()+            return Step.Done+        }+        val intent = try {+            requests.create(batch.map { it.uri.toUri() }, value)+        } catch (_: SecurityException) {+            null+        } catch (_: IllegalArgumentException) {+            null+        }+        if (intent == null) {+            abandon(batch)+            return Step.Failed+        }+        inFlight = batch+        return Step.Launch(intent)+    }++    /** Revert [batch] and every batch not yet sent; already-applied batches stay. */+    private fun abandon(batch: List<Photo>) {+        val reverted = batch + pending.flatten()+        pending.clear()+        write(reverted, !value)+    }++    private fun write(photos: List<Photo>, value: Boolean) {+        val ids = photos.map { it.id }+        scope.launch {+            writes.withLock {+                ids.chunked(LOCAL_WRITE_CHUNK).forEach { writeLocal(it, value) }+            }+        }+    }++    private companion object {+        /** SQLite bind-variable ceiling for the `id IN (...)` update. */+        const val LOCAL_WRITE_CHUNK = 900+    }+}
photos/src/main/java/com/vayunmathur/photos/ui/AlbumsPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsPage.ktindex 83da77891e..7840a8eb1f 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsPage.kt@@ -23,6 +23,7 @@ fun AlbumsPage(     val albums by galleryViewModel.albums.collectAsState()     val allPhotos by galleryViewModel.photos.collectAsState()     val trashCount by remember { derivedStateOf { allPhotos.count { it.isTrashed } } }+    val favorites by galleryViewModel.favorites.collectAsState()     val vaultPhotos by secureFolderViewModel.photos.collectAsState()     val vaultDao by secureFolderViewModel.vaultPhotoDao.collectAsState() @@ -31,6 +32,8 @@ fun AlbumsPage(         state = AlbumsUiState(             albums = albums,             defaultAlbums = listOf(+                // Covered by the newest favorite (the list is newest first).+                DefaultAlbum(DefaultAlbumKind.FAVORITES, favorites.size, cover = favorites.firstOrNull()),                 DefaultAlbum(DefaultAlbumKind.TRASH, trashCount),                 // The vault size stays private while locked: hide the count line.                 DefaultAlbum(DefaultAlbumKind.SECURE_FOLDER, vaultPhotos.size.takeIf { vaultDao != null }),
photos/src/main/java/com/vayunmathur/photos/ui/AlbumsScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsScreen.ktindex af46b99066..86ab9f4b90 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/AlbumsScreen.kt@@ -16,6 +16,7 @@ import androidx.compose.foundation.lazy.grid.items import androidx.compose.ui.res.pluralStringResource import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconFavoriteBorder import com.vayunmathur.library.ui.IconLock import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text@@ -49,8 +50,9 @@ import com.vayunmathur.photos.util.DefaultAlbumKind  * The albums grid, with no dependency on the ViewModel so it can be rendered from a  * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.  *- * Built-in collections (Trash, Secure Folder) render first as icon tiles with no- * cover photo; they open the same pages the bottom nav used to hold.+ * Built-in collections (Favorites, Trash, Secure Folder) render first as icon+ * tiles; Favorites shows its newest photo as the cover once it has one. Trash+ * and the Secure Folder open the same pages the bottom nav used to hold.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -80,9 +82,11 @@ fun AlbumsScreen(             items(state.defaultAlbums, key = { it.kind }) { album ->                 DefaultAlbumTile(                     album = album,+                    thumbnail = thumbnail,                     onClick = {                         backStack.add(                             when (album.kind) {+                                DefaultAlbumKind.FAVORITES -> Route.Favorites                                 DefaultAlbumKind.TRASH -> Route.Trash                                 DefaultAlbumKind.SECURE_FOLDER -> Route.SecureFolder                             }@@ -135,15 +139,18 @@ fun AlbumsScreen( }  /**- * A built-in collection tile: the collection's icon on a tonal surface- * instead of a cover photo, with the same name/count caption as an album.+ * A built-in collection tile: the collection's icon on a tonal surface (or its+ * [DefaultAlbum.cover], when it has one), with the same name/count caption as+ * an album.  */ @Composable private fun DefaultAlbumTile(     album: DefaultAlbum,+    thumbnail: @Composable (Photo, Modifier) -> Unit,     onClick: () -> Unit, ) {     val title = when (album.kind) {+        DefaultAlbumKind.FAVORITES -> stringResource(R.string.label_favorites)         DefaultAlbumKind.TRASH -> stringResource(R.string.label_trash)         DefaultAlbumKind.SECURE_FOLDER -> stringResource(R.string.label_secure_folder)     }@@ -157,12 +164,19 @@ private fun DefaultAlbumTile(                 .invisibleClickable(onClick = onClick),             contentAlignment = Alignment.Center,         ) {-            when (album.kind) {-                DefaultAlbumKind.TRASH -> IconDelete(+            val cover = album.cover+            when {+                cover != null -> thumbnail(cover, Modifier.fillMaxSize())+                album.kind == DefaultAlbumKind.FAVORITES -> IconFavoriteBorder(                     modifier = Modifier.size(64.dp),                     tint = MaterialTheme.colorScheme.onSurfaceVariant,+                    contentDescription = null,                 )-                DefaultAlbumKind.SECURE_FOLDER -> IconLock(+                album.kind == DefaultAlbumKind.TRASH -> IconDelete(+                    modifier = Modifier.size(64.dp),+                    tint = MaterialTheme.colorScheme.onSurfaceVariant,+                )+                else -> IconLock(                     modifier = Modifier.size(64.dp),                     tint = MaterialTheme.colorScheme.onSurfaceVariant,                 )
photos/src/main/java/com/vayunmathur/photos/ui/FavoritesPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesPage.ktnew file mode 100644index 0000000000..76bd8deb2d--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesPage.kt@@ -0,0 +1,42 @@+package com.vayunmathur.photos.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.util.GalleryUiState+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.SecureFolderViewModel++/** Binds [GalleryViewModel] to the stateless [FavoritesScreen]. */+@Composable+fun FavoritesPage(+    backStack: NavBackStack<Route>,+    galleryViewModel: GalleryViewModel,+    secureFolderViewModel: SecureFolderViewModel,+) {+    val favorites by galleryViewModel.favorites.collectAsState()+    val albums by galleryViewModel.albums.collectAsState()+    val allSelected by galleryViewModel.selectedIds.collectAsState()+    val isRefreshing by galleryViewModel.isRefreshing.collectAsState()++    // Only selection among the favorites counts here, so a selection left over+    // from the gallery grid doesn't leak into this page's action bar.+    val selectedIds by remember {+        derivedStateOf { allSelected.intersect(favorites.mapTo(HashSet()) { it.id }) }+    }++    FavoritesScreen(+        backStack = backStack,+        state = GalleryUiState(+            photos = favorites,+            selectedIds = selectedIds,+            isRefreshing = isRefreshing,+            albums = albums,+        ),+        actions = rememberGalleryActions(galleryViewModel, secureFolderViewModel, favorites, selectedIds),+    )+}
photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.ktnew file mode 100644index 0000000000..c8f6217c5e--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/FavoritesScreen.kt@@ -0,0 +1,161 @@+package com.vayunmathur.photos.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.GridItemSpan+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalResources+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppPullToRefreshBox+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.R+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.FavoriteRule+import com.vayunmathur.photos.pushPhoto+import com.vayunmathur.photos.util.GalleryActions+import com.vayunmathur.photos.util.GalleryUiState+import com.vayunmathur.photos.util.ImageLoader+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlin.math.roundToInt++/**+ * The Favorites album (#912): every MediaStore favorite, newest first, with no+ * dependency on the ViewModel so it can be rendered from a `@Preview`.+ *+ * The grid matches the gallery's: month grouping, pinch-to-zoom columns+ * (shared through [LocalColumnCount]), pull-to-refresh, the same multi-select+ * actions ([GallerySelectionActions]) and the same viewer, opened over this+ * list. [state] carries the favorites as its photos; search fields are unused.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun FavoritesScreen(+    backStack: NavBackStack<Route>,+    state: GalleryUiState,+    actions: GalleryActions,+    /**+     * How a grid tile paints its photo. Previews pass a placeholder, because+     * Layoutlib has neither MediaStore nor the [ImageLoader] singleton+     * MainActivity initialises.+     */+    thumbnail: @Composable (Photo, Modifier) -> Unit = { photo, modifier -> ImageLoader.PhotoItem(photo, modifier) },+) {+    val photos = state.photos+    val isSelectionMode = state.selectedIds.isNotEmpty()+    val allFavorite = remember(photos, state.selectedIds) {+        !FavoriteRule.targetValue(photos.filter { it.id in state.selectedIds }.map { it.isFavorite })+    }+    var showAlbumPicker by remember { mutableStateOf(false) }+    var columnCount by LocalColumnCount.current+    val resources = LocalResources.current++    // Same off-main-thread grouping as the album and gallery grids; the seed+    // keeps the first frame (and a preview) populated.+    val initialGrouping = remember { groupPhotosByMonth(photos, resources) }+    val photosGroupedByMonth by produceState(initialValue = initialGrouping, photos, resources) {+        value = withContext(Dispatchers.Default) { groupPhotosByMonth(photos, resources) }+    }++    AppScaffold(+        title = if (isSelectionMode) {+            stringResource(R.string.items_selected, state.selectedIds.size)+        } else {+            stringResource(R.string.label_favorites)+        },+        onNavigateBack = if (isSelectionMode) null else ({ backStack.pop() }),+        onClose = if (isSelectionMode) ({ actions.clearSelection() }) else null,+        scrollBehavior = appBarScrollBehavior(),+        actions = {+            if (isSelectionMode) {+                GallerySelectionActions(allFavorite, actions, onAddToAlbum = { showAlbumPicker = true })+            }+        },+    ) { padding ->+        if (photos.isEmpty()) {+            EmptyState(+                title = stringResource(R.string.favorites_empty),+                modifier = Modifier.fillMaxSize().padding(padding),+            )+        } else {+            AppPullToRefreshBox(+                isRefreshing = state.isRefreshing,+                onRefresh = { actions.runSync() },+                modifier = Modifier.fillMaxSize(),+                topClearance = padding.calculateTopPadding(),+            ) {+                Box(+                    modifier = Modifier+                        .fillMaxSize()+                        .padding(padding)+                        .pinchToZoomColumns({ columnCount }, { columnCount = it })+                ) {+                    LazyVerticalGrid(+                        columns = GridCells.Fixed(columnCount.roundToInt().coerceIn(2, 8)),+                        modifier = Modifier.fillMaxSize().padding(4.dp),+                        horizontalArrangement = Arrangement.spacedBy(4.dp),+                        verticalArrangement = Arrangement.spacedBy(4.dp),+                    ) {+                        photosGroupedByMonth.forEach { (month, photosInMonth) ->+                            item(span = { GridItemSpan(maxLineSpan) }) {+                                Text(+                                    month,+                                    Modifier.padding(top = 16.dp, bottom = 8.dp, start = 16.dp),+                                    style = MaterialTheme.typography.titleLarge+                                )+                            }+                            items(photosInMonth, key = { it.id }, contentType = { "photo_thumbnail" }) { photo ->+                                ImageLoader.SelectablePhotoItem(+                                    photo = photo,+                                    isSelected = photo.id in state.selectedIds,+                                    isSelectionMode = isSelectionMode,+                                    onToggleSelection = { actions.toggleSelection(photo.id) },+                                    onClick = {+                                        if (isSelectionMode) {+                                            actions.toggleSelection(photo.id)+                                        } else {+                                            backStack.pushPhoto(Route.PhotoPage(photo.id, photos))+                                        }+                                    },+                                    thumbnail = thumbnail,+                                    sharedKey = photo.id,+                                )+                            }+                        }+                    }+                }+            }+        }+    }++    if (showAlbumPicker) {+        AlbumPickerDialog(+            existingAlbums = state.albums.map { it.name },+            onDismiss = { showAlbumPicker = false },+            onConfirm = { name ->+                showAlbumPicker = false+                actions.addSelectionToAlbum(name)+            },+        )+    }+}
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 846e2bcf6a..783a3e4272 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryPage.kt@@ -1,12 +1,9 @@ package com.vayunmathur.photos.ui -import android.app.Activity-import android.content.ActivityNotFoundException import android.content.Intent import android.provider.MediaStore import android.provider.Settings import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect@@ -14,14 +11,10 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalContext import androidx.core.net.toUri-import androidx.fragment.app.FragmentActivity-import com.vayunmathur.library.log.Log import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.Route-import com.vayunmathur.photos.util.GalleryActions import com.vayunmathur.photos.util.GalleryUiState import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.SecureFolderViewModel@@ -57,18 +50,6 @@ fun GalleryPage(         enqueueSyncWork(context)     } -    val mediaResultLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->-        if (result.resultCode == Activity.RESULT_OK) {-            // A pending album move consumes the grant and does its own refresh; the-            // trash/delete/secure-folder paths that share this launcher fall through-            // to the plain clear-and-resync.-            if (!galleryViewModel.consumePendingMove()) {-                galleryViewModel.clearSelection()-                galleryViewModel.runSync()-            }-        }-    }-     // Helper to request MANAGE_MEDIA permission     val manageMediaLauncher = rememberLauncherForActivityResult(         ActivityResultContracts.StartActivityForResult()@@ -86,76 +67,7 @@ fun GalleryPage(         }     } -    // 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 }--                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: SecurityException) {-                                Log.error("GalleryPage", "MediaStore delete request failed", e)-                                // Fallback: clear selection and refresh anyway-                                galleryViewModel.clearSelection()-                                galleryViewModel.runSync()-                            } catch (e: ActivityNotFoundException) {-                                Log.error("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())-            }--            override fun addSelectionToAlbum(name: String) {-                val album = com.vayunmathur.photos.util.AlbumMediaStore.sanitizeAlbumName(name)-                if (album.isBlank()) return-                val selected = currentPhotos.filter { it.id in currentSelectedIds }-                if (selected.isEmpty()) return-                galleryViewModel.requestAlbumMove(selected, album)-                val pendingIntent = MediaStore.createWriteRequest(-                    context.contentResolver,-                    com.vayunmathur.photos.util.AlbumMediaStore.urisOf(selected),-                )-                mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())-            }-        }-    }+    val actions = rememberGalleryActions(galleryViewModel, secureFolderViewModel, photos, selectedIds)      GalleryScreen(         backStack = backStack,
photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.ktindex 8be09ac85a..f686230713 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GalleryScreen.kt@@ -23,7 +23,6 @@ import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.IconLock import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme@@ -52,8 +51,6 @@ import androidx.compose.ui.unit.dp import androidx.core.net.toUri import androidx.fragment.app.FragmentActivity import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconAlbum import com.vayunmathur.library.ui.IconSearch import com.vayunmathur.library.ui.invisibleClickable import com.vayunmathur.library.util.NavBackStack@@ -64,6 +61,7 @@ import com.vayunmathur.photos.pushPhoto import com.vayunmathur.photos.R import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.FavoriteRule import com.vayunmathur.photos.util.GalleryActions import com.vayunmathur.photos.util.GalleryUiState import com.vayunmathur.photos.util.GalleryViewModel@@ -103,6 +101,9 @@ fun GalleryScreen(     var searchActive by remember { mutableStateOf(initialSearchActive) }     var showAlbumPicker by remember { mutableStateOf(false) }     val isSelectionMode = state.selectedIds.isNotEmpty()+    val allFavorite = remember(state.photos, state.selectedIds) {+        !FavoriteRule.targetValue(state.photos.filter { it.id in state.selectedIds }.map { it.isFavorite })+    }      // 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@@ -148,15 +149,7 @@ fun GalleryScreen(                             }                         },                         actions = {-                            IconButton(onClick = { showAlbumPicker = true }) {-                                IconAlbum()-                            }-                            IconButton(onClick = { actions.moveSelectionToSecureFolder() }) {-                                IconLock()-                            }-                            IconButton(onClick = { actions.trashSelection() }) {-                                IconDelete()-                            }+                            GallerySelectionActions(allFavorite, actions, onAddToAlbum = { showAlbumPicker = true })                         }                     )                 } else {
photos/src/main/java/com/vayunmathur/photos/ui/GallerySelectionActions.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/GallerySelectionActions.kt b/photos/src/main/java/com/vayunmathur/photos/ui/GallerySelectionActions.ktnew file mode 100644index 0000000000..eb471acbb9--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/GallerySelectionActions.kt@@ -0,0 +1,44 @@+package com.vayunmathur.photos.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.IconAlbum+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.IconFavorite+import com.vayunmathur.library.ui.IconFavoriteBorder+import com.vayunmathur.library.ui.IconLock+import com.vayunmathur.photos.R+import com.vayunmathur.photos.util.GalleryActions++/**+ * The multi-select top bar actions shared by the gallery and the Favorites+ * album: favorite, add to album, move to the Secure Folder, trash.+ *+ * The heart shows what tapping it does: filled ("remove from favorites") only+ * when every selected item already is a favorite, outlined ("favorite")+ * otherwise, matching [com.vayunmathur.photos.domain.FavoriteRule].+ */+@Composable+fun GallerySelectionActions(+    allFavorite: Boolean,+    actions: GalleryActions,+    onAddToAlbum: () -> Unit,+) {+    IconButton(onClick = { actions.toggleFavoriteSelection() }) {+        if (allFavorite) {+            IconFavorite(contentDescription = stringResource(R.string.action_unfavorite))+        } else {+            IconFavoriteBorder(contentDescription = stringResource(R.string.action_favorite))+        }+    }+    IconButton(onClick = onAddToAlbum) {+        IconAlbum()+    }+    IconButton(onClick = { actions.moveSelectionToSecureFolder() }) {+        IconLock()+    }+    IconButton(onClick = { actions.trashSelection() }) {+        IconDelete()+    }+}
photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.ktindex 46f2d10e06..9e75b128f5 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailSection.kt@@ -63,6 +63,8 @@ fun BoxScope.PhotoDetailSection(      * taps then toggle (restore) as usual.      */     onMetadataLayout: (IntSize) -> Unit = {},+    isFavorite: Boolean = false,+    onToggleFavorite: (Photo) -> Unit = {}, ) {     ocrLayout?.takeIf { isSettled && size != IntSize.Zero }?.let { layout ->         key(ocrClearToken) {@@ -108,6 +110,8 @@ fun BoxScope.PhotoDetailSection(             onSetWallpaper = onSetWallpaper,             onEditPhoto = onEditPhoto,             onDelete = onDelete,+            isFavorite = isFavorite,+            onToggleFavorite = onToggleFavorite,         )     } 
photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.ktindex f75e94f4d3..b69c28a41e 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoDetailView.kt@@ -69,6 +69,9 @@ fun PhotoDetailView(     onEditPhoto: () -> Unit,     onSetWallpaper: (Photo) -> Unit = {},     onDelete: (Photo) -> Unit = {},+    /** Whether this photo is a MediaStore favorite (drives the heart). */+    isFavorite: Boolean = false,+    onToggleFavorite: (Photo) -> Unit = {},     /**      * Non-null makes this page the destination of the container transform out of the grid      * tile. Null for a page the pager keeps composed either side of the current one: they@@ -238,6 +241,8 @@ fun PhotoDetailView(             onSetWallpaper = onSetWallpaper,             onEditPhoto = onEditPhoto,             onDelete = onDelete,+            isFavorite = isFavorite,+            onToggleFavorite = onToggleFavorite,             onShowImmersive = { showImmersive = it },             onMetadataLayout = { metadataSize = it },             onMotionClick = {
photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.ktindex 73b053897b..14a36be41d 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoMetadataCard.kt@@ -23,6 +23,8 @@ import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconEdit+import com.vayunmathur.library.ui.IconFavorite+import com.vayunmathur.library.ui.IconFavoriteBorder import com.vayunmathur.library.ui.IconShare import com.vayunmathur.library.ui.IconWallpaper import com.vayunmathur.library.ui.MaterialTheme@@ -34,7 +36,7 @@ import kotlin.time.Instant  /**  * Bottom metadata overlay: name, date, location, resolution, size, people count,- * and the wallpaper/edit/share/delete actions. Fades with the pager swipe distance.+ * and the favorite/wallpaper/edit/share/delete actions. Fades with the pager swipe distance.  */ @Composable internal fun PhotoMetadataCard(@@ -49,6 +51,8 @@ internal fun PhotoMetadataCard(     onSetWallpaper: (Photo) -> Unit = {},     onEditPhoto: () -> Unit,     onDelete: (Photo) -> Unit = {},+    isFavorite: Boolean = false,+    onToggleFavorite: (Photo) -> Unit = {}, ) {     Column(         modifier =@@ -117,6 +121,13 @@ internal fun PhotoMetadataCard(             modifier = Modifier.align(Alignment.End),             verticalAlignment = Alignment.CenterVertically         ) {+            IconButton(onClick = { onToggleFavorite(photo) }) {+                if (isFavorite) {+                    IconFavorite(tint = Color.White, contentDescription = stringResource(R.string.action_unfavorite))+                } else {+                    IconFavoriteBorder(tint = Color.White, contentDescription = stringResource(R.string.action_favorite))+                }+            }             IconButton(onClick = { onSetWallpaper(photo) }) {                 IconWallpaper(tint = Color.White)             }
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 faac974172..1a6a1ced35 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -56,6 +56,10 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie         val source = overridePhotosList ?: photosAll.filter { !it.isTrashed }         source.filter { it.id !in locallyDeleted }     }+    // Favorite state from the live rows: overridePhotosList (an album, person or+    // search snapshot) does not see a heart tapped after it was taken.+    val favoriteIds = remember(photosAll) { photosAll.filter { it.isFavorite }.mapTo(HashSet()) { it.id } }+    val toggleFavorite = rememberFavoriteToggle(galleryViewModel.favoriteToggler)     val matchedCounts by galleryViewModel.faceCountByPhoto.collectAsState()     val faceBoxes by galleryViewModel.faceBoxesByPhoto.collectAsState() @@ -216,6 +220,8 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie                             }                         },                         onDelete = onDeletePhoto,+                        isFavorite = photo.id in favoriteIds,+                        onToggleFavorite = { p -> toggleFavorite(listOf(p.copy(isFavorite = p.id in favoriteIds))) },                         // The route's own photo, not whichever page the pager has settled on:                         // after a swipe those differ, and back would then morph into a grid tile                         // the user never tapped.
photos/src/main/java/com/vayunmathur/photos/ui/RememberFavoriteToggle.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/RememberFavoriteToggle.kt b/photos/src/main/java/com/vayunmathur/photos/ui/RememberFavoriteToggle.ktnew file mode 100644index 0000000000..1053cadd8e--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/RememberFavoriteToggle.kt@@ -0,0 +1,77 @@+package com.vayunmathur.photos.ui++import android.app.Activity+import android.content.ActivityNotFoundException+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.ActivityResultLauncher+import androidx.activity.result.IntentSenderRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.runtime.SideEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.photos.R+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.platform.FavoriteToggler++/**+ * Wires a [FavoriteToggler] to an activity-result launcher and returns the+ * function that toggles a set of photos (#912) — the viewer's heart passes+ * one photo, the grids pass their selection.+ *+ * Each MediaStore request is launched like the trash request: silently+ * applied when the app holds "manage media", otherwise behind the system+ * dialog. A request MediaStore will not build shows a message. [onApplied]+ * runs once everything asked for is applied (the grids clear their selection+ * there); a declined dialog leaves the selection as it was.+ */+@Composable+fun rememberFavoriteToggle(toggler: FavoriteToggler, onApplied: () -> Unit = {}): (List<Photo>) -> Unit {+    val messenger = rememberMessenger()+    val failedMessage = stringResource(R.string.favorite_failed)+    val currentOnApplied by rememberUpdatedState(onApplied)+    val driver = remember(toggler) { FavoriteRequestDriver(toggler) }+    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->+        driver.handle(toggler.onResult(result.resultCode == Activity.RESULT_OK))+    }+    SideEffect {+        driver.launcher = launcher+        driver.onFailed = { messenger.show(failedMessage) }+        driver.onApplied = { currentOnApplied() }+    }+    return remember(driver) { { photos -> driver.handle(toggler.toggle(photos)) } }+}++/** Turns each [FavoriteToggler.Step] into a launch, a message or a callback. */+private class FavoriteRequestDriver(private val toggler: FavoriteToggler) {+    var launcher: ActivityResultLauncher<IntentSenderRequest>? = null+    var onFailed: () -> Unit = {}+    var onApplied: () -> Unit = {}++    fun handle(step: FavoriteToggler.Step) {+        when (step) {+            is FavoriteToggler.Step.Launch -> launch(step)+            FavoriteToggler.Step.Done -> onApplied()+            FavoriteToggler.Step.Failed -> onFailed()+            FavoriteToggler.Step.Cancelled, FavoriteToggler.Step.Busy -> Unit+        }+    }++    private fun launch(step: FavoriteToggler.Step.Launch) {+        val target = launcher+        if (target == null) {+            toggler.onResult(granted = false)+            return+        }+        try {+            target.launch(IntentSenderRequest.Builder(step.intent.intentSender).build())+        } catch (_: ActivityNotFoundException) {+            // Nothing can show the request: undo the optimistic change.+            toggler.onResult(granted = false)+            onFailed()+        }+    }+}
photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt b/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.ktnew file mode 100644index 0000000000..8efbd7cf1d--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/RememberGalleryActions.kt@@ -0,0 +1,132 @@+package com.vayunmathur.photos.ui++import android.app.Activity+import android.content.ActivityNotFoundException+import android.provider.MediaStore+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.IntentSenderRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.platform.LocalContext+import androidx.core.net.toUri+import androidx.fragment.app.FragmentActivity+import com.vayunmathur.library.log.Log+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.util.GalleryActions+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.SecureFolderViewModel++/**+ * The [GalleryActions] behind a selectable photo grid: the ViewModel's own+ * callbacks plus the MediaStore operations that need activity-result+ * launchers (trash, Secure Folder, add to album, favorite). Shared by the+ * gallery and the Favorites album so both grids select and act alike.+ *+ * [photos] and [selectedIds] are the grid's own items and selection; every+ * action applies to the selected items among [photos] only.+ */+@Composable+fun rememberGalleryActions(+    galleryViewModel: GalleryViewModel,+    secureFolderViewModel: SecureFolderViewModel,+    photos: List<Photo>,+    selectedIds: Set<Long>,+): GalleryActions {+    val context = LocalContext.current++    val mediaResultLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->+        if (result.resultCode == Activity.RESULT_OK) {+            // A pending album move consumes the grant and does its own refresh; the+            // trash/delete/secure-folder paths that share this launcher fall through+            // to the plain clear-and-resync.+            if (!galleryViewModel.consumePendingMove()) {+                galleryViewModel.clearSelection()+                galleryViewModel.runSync()+            }+        }+    }++    // A favorite request that went through clears the selection, like trash.+    val toggleFavorite = rememberFavoriteToggle(+        galleryViewModel.favoriteToggler,+        onApplied = { galleryViewModel.clearSelection() },+    )++    // 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)++    return remember(galleryViewModel, secureFolderViewModel, context, toggleFavorite) {+        // 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 }++                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: SecurityException) {+                                Log.error("GalleryPage", "MediaStore delete request failed", e)+                                // Fallback: clear selection and refresh anyway+                                galleryViewModel.clearSelection()+                                galleryViewModel.runSync()+                            } catch (e: ActivityNotFoundException) {+                                Log.error("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())+            }++            override fun toggleFavoriteSelection() {+                toggleFavorite(currentPhotos.filter { it.id in currentSelectedIds })+            }++            override fun addSelectionToAlbum(name: String) {+                val album = com.vayunmathur.photos.util.AlbumMediaStore.sanitizeAlbumName(name)+                if (album.isBlank()) return+                val selected = currentPhotos.filter { it.id in currentSelectedIds }+                if (selected.isEmpty()) return+                galleryViewModel.requestAlbumMove(selected, album)+                val pendingIntent = MediaStore.createWriteRequest(+                    context.contentResolver,+                    com.vayunmathur.photos.util.AlbumMediaStore.urisOf(selected),+                )+                mediaResultLauncher.launch(IntentSenderRequest.Builder(pendingIntent.intentSender).build())+            }+        }+    }+}
photos/src/main/java/com/vayunmathur/photos/util/GalleryUiContract.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/GalleryUiContract.kt b/photos/src/main/java/com/vayunmathur/photos/util/GalleryUiContract.ktindex e6fc80d28d..3ddccf4070 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/GalleryUiContract.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/GalleryUiContract.kt@@ -62,10 +62,13 @@ data class DefaultAlbum(      * the vault is locked, so its size stays private).      */     val count: Int? = null,+    /** Cover photo drawn instead of the icon (Favorites: its newest item), if any. */+    val cover: Photo? = null, )  /** Which built-in collection a [DefaultAlbum] tile opens. */ enum class DefaultAlbumKind {+    FAVORITES,     TRASH,     SECURE_FOLDER, }@@ -90,6 +93,13 @@ interface GalleryActions {     /** Ask MediaStore to trash the current selection. */     fun trashSelection() {} +    /**+     * Favorite the current selection, or unfavorite it when every selected item+     * already is one (a mixed selection is favorited). Goes through a MediaStore+     * request launcher, so the binder supplies it.+     */+    fun toggleFavoriteSelection() {}+     /**      * Move the current selection into album [name] (created on first use),      * through the MediaStore folder mechanism. Needs a write-consent launcher, so
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 bafd97bab7..a2bb8c5349 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt@@ -15,6 +15,8 @@ import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.PhotoScanRepository import com.vayunmathur.photos.data.PhotosRepository import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.photos.platform.FavoriteToggler+import com.vayunmathur.photos.platform.MediaStoreFavoriteRequests import java.io.IOException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.FlowPreview@@ -97,6 +99,18 @@ class GalleryViewModel(     private val _selectedIds = MutableStateFlow<Set<Long>>(emptySet())     val selectedIds: StateFlow<Set<Long>> = _selectedIds.asStateFlow() +    /**+     * Favourites through MediaStore's IS_FAVORITE (#912), shared by the viewer+     * and the grids. Held here so a request waiting on its system dialog+     * survives a configuration change; a granted request resyncs.+     */+    val favoriteToggler = FavoriteToggler(+        writeLocal = { ids, value -> repository.setFavorite(ids, value) },+        requests = MediaStoreFavoriteRequests(application.contentResolver),+        scope = viewModelScope,+        onApplied = { runSync() },+    )+     /** True while a media sync is enqueued or running (drives pull-to-refresh). */     val isRefreshing: StateFlow<Boolean> = workInfosFlow(application, SyncWorker.WORK_NAME)         .map { infos -> infos.any { it.state == WorkInfo.State.RUNNING } }@@ -239,6 +253,17 @@ class GalleryViewModel(             .flowOn(Dispatchers.Default)             .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) +    /**+     * The Favourites album (#912): items favourited in MediaStore, newest first+     * (getAllFlow is ORDER BY date DESC). Trashed items are left out, like every+     * other album; MediaStore keeps their flag, so a restored favourite returns.+     */+    val favorites: StateFlow<List<Photo>> = repository.getAllFlow()+        .map { all -> all.filter { it.isFavorite && !it.isTrashed } }+        .distinctUntilChanged()+        .flowOn(Dispatchers.Default)+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())+     /**      * Face geometry per photo, for the viewer's face overlay. Combined with the      * clusters because the label text lives on [com.vayunmathur.photos.data.Person],@@ -550,6 +575,7 @@ interface PhotoStore {     suspend fun delete(photo: Photo): Int     suspend fun setTrashed(id: Long)     suspend fun setAlbum(ids: List<Long>, album: String?)+    suspend fun setFavorite(ids: List<Long>, value: Boolean)     suspend fun getByUri(uri: String): List<Photo>     suspend fun getAll(): List<Photo> }@@ -576,6 +602,7 @@ private class PhotoStoreRepository(application: Application, val delegate: Photo     override suspend fun delete(photo: Photo): Int = repository.delete(photo)     override suspend fun setTrashed(id: Long) = repository.setTrashed(id)     override suspend fun setAlbum(ids: List<Long>, album: String?) = repository.setAlbum(ids, album)+    override suspend fun setFavorite(ids: List<Long>, value: Boolean) = repository.setFavorite(ids, value)     override suspend fun getByUri(uri: String): List<Photo> = repository.getByUri(uri)     override suspend fun getAll(): List<Photo> = repository.getAll() }
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 f215b75be8..dd3fe6f547 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -77,7 +77,10 @@ class SyncWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c             // scan (their GENERATION_MODIFIED hasn't moved), so scan everything             // until they're all backfilled.             val needsMimeBackfill = scanRepository.countMissingMimeType() > 0-            syncPhotos(applicationContext, repository, null, if (needsMimeBackfill) 0L else lastGeneration)+            syncLibrary(+                applicationContext, repository, lastGeneration, needsMimeBackfill,+                DataStoreOneTimeFlag(dataStore, FAVORITES_RESCAN_DONE_KEY),+            )         }                  setExifData(scanRepository, applicationContext)@@ -172,6 +175,51 @@ class OCRWorker(context: Context, params: WorkerParameters) : CoroutineWorker(co     } } +/**+ * A persisted "has this one-off job run yet" bit. An interface so the+ * once-only behaviour of [syncLibrary] is testable without DataStore.+ */+internal interface OneTimeFlag {+    suspend fun isSet(): Boolean+    suspend fun set()+}++private class DataStoreOneTimeFlag(+    private val dataStore: DataStoreUtils,+    private val key: String,+) : OneTimeFlag {+    override suspend fun isSet(): Boolean = dataStore.getBooleanAwait(key)+    override suspend fun set() = dataStore.setBoolean(key, true)+}++/**+ * Set once the post-upgrade full rescan for IS_FAVORITE (#912) has run.+ * MIGRATION_19_20 adds the column as 0 everywhere, and an incremental scan+ * only sees rows whose GENERATION_MODIFIED moved since the last sync, so+ * photos favourited in another app before the upgrade would never show up+ * without one full pass.+ */+internal const val FAVORITES_RESCAN_DONE_KEY = "favorites_rescan_done"++/**+ * The untriggered library sync: incremental from [lastGeneration], unless a+ * full scan is owed — rows still missing their mimeType, or the one-time+ * favourites rescan behind [favoritesRescan] has not run yet. The flag is set+ * only after a full scan completed, so it runs exactly once.+ */+internal suspend fun syncLibrary(+    context: Context,+    repository: PhotosRepository,+    lastGeneration: Long,+    needsMimeBackfill: Boolean,+    favoritesRescan: OneTimeFlag,+) {+    val needsFavoritesRescan = !favoritesRescan.isSet()+    val fullScan = needsMimeBackfill || needsFavoritesRescan+    syncPhotos(context, repository, null, if (fullScan) 0L else lastGeneration)+    if (needsFavoritesRescan) favoritesRescan.set()+}+ suspend fun syncPhotos(     context: Context,     repository: PhotosRepository,@@ -225,11 +273,17 @@ suspend fun syncPhotos(     if (newOrUpdatedPhotos.isNotEmpty()) {         repository.upsertAll(newOrUpdatedPhotos)     }+    // Favourite-only diffs (a toggle here or in another gallery app) are written+    // by column: an upsert of the row rebuilt above would drop its CLIP+    // embedding and OCR geometry and send it back through indexing.+    for ((value, ids) in cursorScope.favoriteChanges.entries.groupBy({ it.value }, { it.key })) {+        ids.chunked(DELETE_ID_CHUNK_SIZE).forEach { chunk -> repository.setFavorite(chunk, value) }+    } }  private const val MILLIS_PER_SECOND = 1000L -/** SQLite bind-variable ceiling; deletions are chunked under it. */+/** SQLite bind-variable ceiling; deletions and favourite writes are chunked under it. */ private const val DELETE_ID_CHUNK_SIZE = 900  /** OCR preview length in the worker log line. */@@ -271,6 +325,7 @@ private class CursorColumns(cursor: android.database.Cursor, isVideo: Boolean) {     val isTrashed: Int = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.IS_TRASHED)     val mimeType: Int = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE)     val album: Int = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.BUCKET_DISPLAY_NAME)+    val isFavorite: Int = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.IS_FAVORITE)     val duration: Int = if (isVideo) cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION) else -1 } @@ -278,6 +333,8 @@ private class CursorColumns(cursor: android.database.Cursor, isVideo: Boolean) { private class CursorScope(     val existingPhotos: Map<Long, Photo>,     val newOrUpdatedPhotos: MutableList<Photo>,+    /** Rows whose only difference is IS_FAVORITE: id -> new value. */+    val favoriteChanges: MutableMap<Long, Boolean> = mutableMapOf(), )  private fun processCursor(cursor: android.database.Cursor, isVideo: Boolean, scope: CursorScope) {@@ -319,6 +376,7 @@ private fun readCursorRow(     val isTrashed = cursor.getInt(cols.isTrashed) == 1     val mimeType = cursor.getString(cols.mimeType)     val album = cursor.getString(cols.album)+    val isFavorite = cursor.getInt(cols.isFavorite) == 1     val contentUri = ContentUris.withAppendedId(baseUri, id).toString()     val videoData = if (isVideo) VideoData(cursor.getLong(cols.duration)) else null @@ -334,8 +392,10 @@ private fun readCursorRow(             existing?.panoData, isTrashed,             faceScanned = existing?.faceScanned ?: false,             ocrText = existing?.ocrText, ocrScanned = existing?.ocrScanned ?: false,-            mimeType = mimeType, album = album,+            mimeType = mimeType, album = album, isFavorite = isFavorite,         )+    } else if (existing != null && existing.isFavorite != isFavorite) {+        scope.favoriteChanges[id] = isFavorite     } } @@ -414,6 +474,7 @@ private val IMAGE_PROJECTION = arrayOf(     MediaStore.Images.Media.IS_TRASHED,     MediaStore.Images.Media.MIME_TYPE,     MediaStore.Images.Media.BUCKET_DISPLAY_NAME,+    MediaStore.Images.Media.IS_FAVORITE, )  private val VIDEO_PROJECTION = arrayOf(@@ -428,6 +489,7 @@ private val VIDEO_PROJECTION = arrayOf(     MediaStore.Video.Media.IS_TRASHED,     MediaStore.Video.Media.MIME_TYPE,     MediaStore.Video.Media.BUCKET_DISPLAY_NAME,+    MediaStore.Video.Media.IS_FAVORITE, )  internal fun Context.syncForegroundInfo(
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex 7eb060132f..44ed0567b8 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -41,6 +41,16 @@         <item quantity="one"><xliff:g id="count" example="12">%1$d</xliff:g> photo</item>         <item quantity="other"><xliff:g id="count" example="12">%1$d</xliff:g> photos</item>     </plurals>+    <!-- Album tile and page title for the built-in Favorites collection (photos marked with the heart). Noun plural -->+    <string name="label_favorites">Favorites</string>+    <!-- Content description of the outlined heart: marks the photo (or selected photos) as favorites. Verb -->+    <string name="action_favorite">Favorite</string>+    <!-- Content description of the filled heart: removes the photo (or selected photos) from favorites. Verb phrase -->+    <string name="action_unfavorite">Remove from favorites</string>+    <!-- Empty state of the Favorites album. Sentence -->+    <string name="favorites_empty">No favorites yet. Tap the heart on a photo to add it here.</string>+    <!-- Snackbar when the system refuses to change a photo's favorite state. Sentence -->+    <string name="favorite_failed">Couldn\'t update favorites</string>     <!-- Title of the selection action / dialog to add the chosen photos to an album. Verb phrase -->     <string name="label_add_to_album">Add to album</string>     <!-- Text field label/hint for entering an album name. Noun -->
photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt
diff --git a/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt b/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.ktindex afac9a9122..a905a5a5ce 100644--- a/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt+++ b/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt@@ -20,6 +20,10 @@ import com.vayunmathur.photos.LocalColumnCount import com.vayunmathur.photos.Route import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.VideoData+import com.vayunmathur.photos.util.Album+import com.vayunmathur.photos.util.AlbumsUiState+import com.vayunmathur.photos.util.DefaultAlbum+import com.vayunmathur.photos.util.DefaultAlbumKind import com.vayunmathur.photos.util.GalleryActions import com.vayunmathur.photos.util.GalleryUiState import com.vayunmathur.photos.util.PeopleUiState@@ -107,6 +111,33 @@ class MetadataPreviews {             )         }     }++    @PreviewTest+    @Preview(name = "5-albums", device = PHONE, group = "phone", showSystemUi = true)+    @Composable+    fun Preview5Albums() {+        val photos = samplePhotos()+        DynamicTheme(darkTheme = true) {+            AlbumsScreen(+                backStack = NavBackStack(arrayOf<Route>(Route.Albums)),+                state = AlbumsUiState(+                    albums = listOf(+                        Album("Camera", photos[0], photos.take(14)),+                        Album("Screenshots", photos[14], photos.drop(14)),+                        Album("Trip", photos[4], photos.slice(4..9)),+                        Album("WhatsApp Images", photos[18], photos.takeLast(3)),+                    ),+                    defaultAlbums = listOf(+                        // The Favorites tile takes its newest favorite as the cover.+                        DefaultAlbum(DefaultAlbumKind.FAVORITES, count = 6, cover = photos[2]),+                        DefaultAlbum(DefaultAlbumKind.TRASH, count = 3),+                        DefaultAlbum(DefaultAlbumKind.SECURE_FOLDER, count = null),+                    ),+                ),+                thumbnail = { photo, modifier -> PlaceholderTile(photo, modifier) },+            )+        }+    } }  /**
photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.ktnew file mode 100644index 0000000000..1b3fc05b34--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/PhotosFavoritesDataTest.kt@@ -0,0 +1,149 @@+package com.vayunmathur.photos.data++import androidx.room3.Room+import androidx.sqlite.execSQL+import androidx.test.core.app.ApplicationProvider+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * #912 data layer: MIGRATION_19_20 against a populated v19 Photo table, and the+ * column-targeted favourite write the toggle and the sync both rely on.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosFavoritesDataTest {++    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+    private val db: PhotoDatabase = Room.inMemoryDatabaseBuilder(context, PhotoDatabase::class.java)+        .allowMainThreadQueries()+        .build()++    @AfterTest+    fun closeDb() {+        db.close()+    }++    @Test+    fun migration19To20AddsIsFavoriteAndKeepsExistingRows() = runBlocking<Unit> {+        val connection = androidx.sqlite.driver.bundled.BundledSQLiteDriver().open(":memory:")+        try {+            // The v19 Photo table as Room generated it (all columns, no isFavorite),+            // holding rows with scan state that must survive the upgrade.+            connection.execSQL(+                "CREATE TABLE IF NOT EXISTS `Photo` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++                    "`name` TEXT NOT NULL, `uri` TEXT NOT NULL, `date` INTEGER NOT NULL, " ++                    "`width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `dateModified` INTEGER NOT NULL, " ++                    "`exifSet` INTEGER NOT NULL, `lat` REAL, `long` REAL, `duration` INTEGER, " ++                    "`fullWidth` INTEGER, `fullHeight` INTEGER, `croppedWidth` INTEGER, " ++                    "`croppedHeight` INTEGER, `croppedLeft` INTEGER, `croppedTop` INTEGER, " ++                    "`projectionType` TEXT, `isTrashed` INTEGER NOT NULL, `faceScanned` INTEGER NOT NULL, " ++                    "`ocrText` TEXT, `ocrScanned` INTEGER NOT NULL, `clipEmbedding` BLOB, " ++                    "`clipScanned` INTEGER NOT NULL, `mimeType` TEXT, `ocrBoxes` TEXT, `album` TEXT)",+            )+            connection.execSQL(+                "INSERT INTO Photo (id, name, uri, date, width, height, dateModified, exifSet, " ++                    "isTrashed, faceScanned, ocrScanned, clipScanned, ocrText, album) VALUES " ++                    "(1, 'a', 'content://media/1', 10, 1, 1, 1, 1, 0, 1, 1, 1, 'hello', 'Camera'), " ++                    "(2, 'b', 'content://media/2', 20, 1, 1, 1, 1, 1, 0, 0, 0, NULL, NULL)",+            )++            MIGRATION_19_20.migrate(connection)++            data class Column(val type: String, val notNull: Boolean, val default: String?)+            val columns = connection.prepare("PRAGMA table_info(Photo)").use { statement ->+                val byName = mutableMapOf<String, Column>()+                while (statement.step()) {+                    byName[statement.getText(1)] = Column(+                        type = statement.getText(2),+                        notNull = statement.getLong(3) == 1L,+                        default = if (statement.isNull(4)) null else statement.getText(4),+                    )+                }+                byName+            }+            // Room's entity column for `val isFavorite: Boolean = false`.+            assertEquals(Column("INTEGER", notNull = true, default = "0"), columns["isFavorite"])++            val rows = connection.prepare(+                "SELECT id, isFavorite, ocrText, album, faceScanned FROM Photo ORDER BY id",+            ).use { statement ->+                val out = mutableListOf<List<Any?>>()+                while (statement.step()) {+                    out += listOf(+                        statement.getLong(0),+                        statement.getLong(1),+                        if (statement.isNull(2)) null else statement.getText(2),+                        if (statement.isNull(3)) null else statement.getText(3),+                        statement.getLong(4),+                    )+                }+                out+            }+            // Both rows survive, start as not favourite, and keep their other columns.+            assertEquals<List<List<Any?>>>(+                listOf(+                    listOf(1L, 0L, "hello", "Camera", 1L),+                    listOf(2L, 0L, null, null, 0L),+                ),+                rows,+            )+        } finally {+            connection.close()+        }+    }++    @Test+    fun migrationListEndsAtVersion20() {+        val last = PhotoDatabase.migrations.last()+        assertEquals(19 to 20, last.startVersion to last.endVersion)+    }++    private fun photo(name: String, date: Long, trashed: Boolean = false) = Photo(+        name = name,+        uri = "content://media/$name",+        date = date,+        width = 100,+        height = 100,+        dateModified = date,+        exifSet = true,+        lat = null,+        long = null,+        videoData = null,+        panoData = null,+        isTrashed = trashed,+        clipEmbedding = byteArrayOf(1, 2, 3),+        clipScanned = true,+    )++    @Test+    fun setFavoriteFlipsOnlyThatColumnAndReachesTheGalleryFlow() = runTest {+        val dao = db.photoDao()+        dao.upsertAll(listOf(photo("a", 100L), photo("b", 200L)))+        val ids = dao.getAll().associate { it.name to it.id }++        dao.setFavorite(listOf(ids.getValue("a")), true)++        // getAllFlow lists its columns explicitly: isFavorite must be among them.+        val flow = dao.getAllFlow().first().associateBy { it.name }+        assertTrue(flow.getValue("a").isFavorite)+        assertFalse(flow.getValue("b").isFavorite)+        // Column-targeted: the embedding written above is untouched.+        val a = dao.getAll().single { it.name == "a" }+        assertContentEquals(byteArrayOf(1, 2, 3), a.clipEmbedding)+        assertTrue(a.clipScanned)++        dao.setFavorite(listOf(ids.getValue("a")), false)+        assertFalse(dao.getAllFlow().first().single { it.name == "a" }.isFavorite)+    }+}
photos/src/test/java/com/vayunmathur/photos/domain/FavoriteRuleTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/domain/FavoriteRuleTest.kt b/photos/src/test/java/com/vayunmathur/photos/domain/FavoriteRuleTest.ktnew file mode 100644index 0000000000..7d63463533--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/domain/FavoriteRuleTest.kt@@ -0,0 +1,30 @@+package com.vayunmathur.photos.domain++import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** #912: which way a favourite toggle goes for a selection. */+class FavoriteRuleTest {++    @Test+    fun noneFavoriteFavorites() {+        assertTrue(FavoriteRule.targetValue(listOf(false, false)))+    }++    @Test+    fun mixedSelectionFavoritesAll() {+        assertTrue(FavoriteRule.targetValue(listOf(true, false, true)))+    }++    @Test+    fun allFavoriteUnfavorites() {+        assertFalse(FavoriteRule.targetValue(listOf(true, true)))+        assertFalse(FavoriteRule.targetValue(listOf(true)))+    }++    @Test+    fun emptySelectionFavorites() {+        assertTrue(FavoriteRule.targetValue(emptyList()))+    }+}
photos/src/test/java/com/vayunmathur/photos/platform/FavoriteTogglerTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/platform/FavoriteTogglerTest.kt b/photos/src/test/java/com/vayunmathur/photos/platform/FavoriteTogglerTest.ktnew file mode 100644index 0000000000..9b6e92fd90--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/platform/FavoriteTogglerTest.kt@@ -0,0 +1,227 @@+package com.vayunmathur.photos.platform++import android.app.PendingIntent+import android.content.ClipData+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Context+import android.content.Intent+import android.content.pm.ProviderInfo+import android.database.Cursor+import android.net.Uri+import android.os.Bundle+import android.provider.MediaStore+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.FavoriteRule+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.TestScope+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver++/**+ * #912 toggle: the mixed-selection rule, request batching, the optimistic+ * local write and its revert. The toggler runs against a recording request+ * factory (the resolver seam); [MediaStoreFavoriteRequests] itself is checked+ * against a fake MediaStore provider that answers createFavoriteRequest the+ * way MediaProvider does, with a PendingIntent.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class FavoriteTogglerTest {++    private val context: Context = ApplicationProvider.getApplicationContext()++    /** Records each favourite request (URIs + value) and returns a PendingIntent for it. */+    private class FakeMediaProvider(private val context: Context) : ContentProvider() {+        val requests = mutableListOf<Pair<List<Uri>, Boolean>>()++        override fun onCreate(): Boolean = true++        override fun call(authority: String, method: String, arg: String?, extras: Bundle?): Bundle =+            call(method, arg, extras)++        override fun call(method: String, arg: String?, extras: Bundle?): Bundle {+            val bundle = extras ?: Bundle()+            val clip = bundle.keySet().firstNotNullOf { bundle.get(it) as? ClipData }+            val values = bundle.keySet().firstNotNullOf { bundle.get(it) as? ContentValues }+            val uris = (0 until clip.itemCount).map { clip.getItemAt(it).uri }+            requests += uris to (values.getAsInteger(MediaStore.MediaColumns.IS_FAVORITE) == 1)+            val intent = PendingIntent.getActivity(+                context, requests.size, Intent("favorite-${requests.size}"), PendingIntent.FLAG_IMMUTABLE,+            )+            return Bundle().apply { putParcelable("result", intent) }+        }++        override fun query(+            uri: Uri, projection: Array<out String>?, selection: String?,+            selectionArgs: Array<out String>?, sortOrder: String?,+        ): Cursor? = null+        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+        override fun update(+            uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+        ): Int = 0+    }++    private fun photo(id: Long, favorite: Boolean) = Photo(+        id = id, name = "p$id", uri = "content://media/external/images/media/$id",+        date = 1_000L, width = 100, height = 100, dateModified = 1L,+        exifSet = true, lat = null, long = null, videoData = null, panoData = null,+        isFavorite = favorite,+    )++    /** Records each request like the provider does, without going through MediaStore. */+    private class RecordingRequests(private val context: Context) : FavoriteRequestFactory {+        val requests = mutableListOf<Pair<List<Uri>, Boolean>>()+        var refuse = false+        override fun create(uris: List<Uri>, value: Boolean): PendingIntent {+            if (refuse) throw SecurityException("refused")+            requests += uris to value+            return PendingIntent.getActivity(+                context, requests.size, Intent("favorite-${requests.size}"), PendingIntent.FLAG_IMMUTABLE,+            )+        }+    }++    private class Harness(scope: TestScope, val provider: RecordingRequests) {+        val writes = mutableListOf<Pair<List<Long>, Boolean>>()+        var applied = 0+        val toggler = FavoriteToggler(+            writeLocal = { ids, value -> writes += ids to value },+            requests = provider,+            scope = scope,+            onApplied = { applied++ },+        )+    }++    private fun register(): RecordingRequests = RecordingRequests(context)++    @Test+    fun mediaStoreRequestCarriesTheUrisAndTheValue() {+        // Attached under the media authority: ContentResolver.call validates it.+        val provider = FakeMediaProvider(context).apply {+            attachInfo(context, ProviderInfo().apply { authority = MediaStore.AUTHORITY })+        }+        ShadowContentResolver.registerProviderInternal(MediaStore.AUTHORITY, provider)+        val uris = listOf(Uri.parse(photo(1, false).uri), Uri.parse(photo(2, false).uri))++        val result = runCatching { MediaStoreFavoriteRequests(context.contentResolver).create(uris, true) }+        val error = result.exceptionOrNull()+        assertNull(error, error?.stackTraceToString())+        runCatching { MediaStoreFavoriteRequests(context.contentResolver).create(uris.take(1), false) }++        assertEquals(listOf(uris to true, uris.take(1) to false), provider.requests)+    }++    @Test+    fun mixedSelectionFavoritesOnlyTheItemsThatAreNotYet() = runTest {+        val provider = register()+        val h = Harness(this, provider)++        val step = h.toggler.toggle(listOf(photo(1, true), photo(2, false), photo(3, false)))+        testScheduler.advanceUntilIdle()++        assertIs<FavoriteToggler.Step.Launch>(step)+        // One request, value true, for the two that change; photo 1 is untouched.+        assertEquals(+            listOf(listOf(Uri.parse(photo(2, false).uri), Uri.parse(photo(3, false).uri)) to true),+            provider.requests,+        )+        assertEquals(listOf(listOf(2L, 3L) to true), h.writes)++        assertIs<FavoriteToggler.Step.Done>(h.toggler.onResult(granted = true))+        assertEquals(1, h.applied)+    }++    @Test+    fun allFavoriteSelectionUnfavorites() = runTest {+        val provider = register()+        val h = Harness(this, provider)++        assertIs<FavoriteToggler.Step.Launch>(h.toggler.toggle(listOf(photo(1, true), photo(2, true))))+        testScheduler.advanceUntilIdle()++        assertEquals(false, provider.requests.single().second)+        assertEquals(listOf(listOf(1L, 2L) to false), h.writes)+    }++    @Test+    fun largeSelectionsGoOutInSequentialBatches() = runTest {+        val provider = register()+        val h = Harness(this, provider)+        val photos = (1L..(FavoriteRule.MAX_URIS_PER_REQUEST + 20L)).map { photo(it, false) }++        assertIs<FavoriteToggler.Step.Launch>(h.toggler.toggle(photos))+        assertEquals(1, provider.requests.size)+        assertEquals(FavoriteRule.MAX_URIS_PER_REQUEST, provider.requests[0].first.size)+        // A second toggle while the first request is out is refused.+        assertIs<FavoriteToggler.Step.Busy>(h.toggler.toggle(listOf(photo(9_999, false))))++        assertIs<FavoriteToggler.Step.Launch>(h.toggler.onResult(granted = true))+        assertEquals(2, provider.requests.size)+        assertEquals(20, provider.requests[1].first.size)+        assertEquals(0, h.applied)++        assertIs<FavoriteToggler.Step.Done>(h.toggler.onResult(granted = true))+        assertEquals(1, h.applied)+        testScheduler.advanceUntilIdle()+        // One optimistic write covering all of them, never reverted.+        assertEquals(photos.map { it.id }.toSet(), h.writes.flatMap { it.first }.toSet())+        assertTrue(h.writes.all { it.second })+    }++    @Test+    fun declinedRequestRevertsItAndEveryUnsentBatch() = runTest {+        val provider = register()+        val h = Harness(this, provider)+        val photos = (1L..(FavoriteRule.MAX_URIS_PER_REQUEST + 5L)).map { photo(it, false) }++        h.toggler.toggle(photos)+        assertIs<FavoriteToggler.Step.Cancelled>(h.toggler.onResult(granted = false))+        testScheduler.advanceUntilIdle()++        assertEquals(1, provider.requests.size)+        assertEquals(0, h.applied)+        // Optimistic true for all, then false for all of them (in that order).+        val allIds = photos.map { it.id }.toSet()+        val (optimistic, reverted) = h.writes.partition { it.second }+        assertEquals(allIds, optimistic.flatMap { it.first }.toSet())+        assertEquals(allIds, reverted.flatMap { it.first }.toSet())+        assertTrue(h.writes.indexOfFirst { !it.second } > h.writes.indexOfLast { it.second })+        // The toggler is free again.+        assertIs<FavoriteToggler.Step.Launch>(h.toggler.toggle(listOf(photo(1, false))))+    }++    @Test+    fun requestThatMediaStoreRefusesIsReverted() = runTest {+        val provider = register().apply { refuse = true }+        val h = Harness(this, provider)++        assertIs<FavoriteToggler.Step.Failed>(h.toggler.toggle(listOf(photo(1, false))))+        testScheduler.advanceUntilIdle()++        assertEquals(listOf(listOf(1L) to true, listOf(1L) to false), h.writes)+        assertEquals(0, h.applied)+    }++    @Test+    fun nothingToChangeIsDoneWithoutARequest() = runTest {+        val provider = register()+        val h = Harness(this, provider)++        assertIs<FavoriteToggler.Step.Done>(h.toggler.setFavorite(listOf(photo(1, true)), true))+        testScheduler.advanceUntilIdle()++        assertTrue(provider.requests.isEmpty())+        assertTrue(h.writes.isEmpty())+    }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesAlbumTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesAlbumTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesAlbumTest.ktnew file mode 100644index 0000000000..220d554c0d--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesAlbumTest.kt@@ -0,0 +1,104 @@+package com.vayunmathur.photos.util++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.FaceGeometry+import com.vayunmathur.photos.data.Person+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoDatabase+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** #912: what the Favorites album holds, read through [GalleryViewModel.favorites]. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosFavoritesAlbumTest {++    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()++    private var nextId = 1L++    private fun photo(name: String, date: Long, favorite: Boolean = false, trashed: Boolean = false) = Photo(+        id = nextId++,+        name = name,+        uri = "content://media/external/images/media/$name",+        date = date,+        width = 100,+        height = 100,+        dateModified = date,+        exifSet = false,+        lat = null,+        long = null,+        videoData = null,+        panoData = null,+        isTrashed = trashed,+        isFavorite = favorite,+    )++    // ---- Favorites album contents ----++    @Test+    fun favoritesAreFavoritedUntrashedItemsNewestFirst() = runTest {+        workInfosOverride = { _, _ -> flowOf(emptyList<androidx.work.WorkInfo>()) }+        val db = Room.inMemoryDatabaseBuilder(context, PhotoDatabase::class.java)+            .allowMainThreadQueries()+            .build()+        db.photoDao().upsertAll(+            listOf(+                photo("old-fav", 100L, favorite = true),+                photo("new-fav", 300L, favorite = true),+                photo("trashed-fav", 400L, favorite = true, trashed = true),+                photo("plain", 500L),+            ),+        )+        val vm = GalleryViewModel(+            context.applicationContext as Application,+            FakePhotos(db),+            FakeScans(db),+            FakeFaces(db),+        ).also { it.runSyncHook = {} }++        val favorites = vm.favorites.first { it.isNotEmpty() }++        assertEquals(listOf("new-fav", "old-fav"), favorites.map { it.name })+    }++    // ---- Store fakes (same shape as the gallery tests) ----++    private class FakePhotos(db: PhotoDatabase) : PhotoStore {+        private val dao = db.photoDao()+        override fun getAllFlow(): Flow<List<Photo>> = dao.getAllFlow()+        override fun getOCRCountFlow(): Flow<Int> = dao.getOCRCountFlow()+        override fun getClipCountFlow(): Flow<Int> = dao.getClipCountFlow()+        override fun getFaceScannedCountFlow(): Flow<Int> = dao.getFaceScannedCountFlow()+        override fun getIndexTargetCountFlow(): Flow<Int> = dao.getIndexTargetCountFlow()+        override suspend fun getByUri(uri: String): List<Photo> = dao.getByUri(uri)+        override suspend fun searchPhotos(query: String): List<Photo> = dao.searchPhotos(query)+        override suspend fun delete(photo: Photo): Int = dao.delete(photo)+        override suspend fun setTrashed(id: Long) = dao.setTrashed(id)+        override suspend fun setAlbum(ids: List<Long>, album: String?) = dao.setAlbum(ids, album)+        override suspend fun setFavorite(ids: List<Long>, value: Boolean) = dao.setFavorite(ids, value)+        override suspend fun getAll(): List<Photo> = dao.getAll()+    }++    private class FakeScans(db: PhotoDatabase) : PhotoScanStore {+        private val dao = db.photoScanDao()+        override suspend fun getClipEmbeddings() = dao.getClipEmbeddings()+    }++    private class FakeFaces(db: PhotoDatabase) : FaceStore {+        private val dao = db.faceDao()+        override fun personsFlow(): Flow<List<Person>> = dao.personsFlow()+        override fun faceGeometryFlow(): Flow<List<FaceGeometry>> = dao.faceGeometryFlow()+        override suspend fun photoIdsForCluster(clusterId: Long) = dao.photoIdsForCluster(clusterId)+        override suspend fun setPersonName(id: Long, name: String?) = dao.setPersonName(id, name)+    }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.ktnew file mode 100644index 0000000000..8ed5a7bf41--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesSyncTest.kt@@ -0,0 +1,247 @@+package com.vayunmathur.photos.util++import android.content.ContentProvider+import android.content.ContentResolver+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.os.Bundle+import android.provider.MediaStore+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotosRepository+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver++/**+ * #912 sync: IS_FAVORITE flows from MediaStore into the Photo rows (including a+ * change made in another gallery app), favourite-only diffs are written by+ * column instead of re-upserting the row, and the post-upgrade full rescan+ * runs exactly once.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosFavoritesSyncTest {++    private val context: Context = ApplicationProvider.getApplicationContext()++    private class FakePhotosRepository(context: Context) : PhotosRepository(context) {+        var all: List<Photo> = emptyList()+        val deletedBatches = mutableListOf<List<Long>>()+        val upsertedBatches = mutableListOf<List<Photo>>()+        val favoriteWrites = mutableListOf<Pair<List<Long>, Boolean>>()+        override suspend fun getAll(): List<Photo> = all+        override suspend fun deleteByIds(ids: List<Long>) {+            deletedBatches += ids+        }+        override suspend fun upsertAll(photos: List<Photo>) {+            upsertedBatches += photos+        }+        override suspend fun setFavorite(ids: List<Long>, value: Boolean) {+            favoriteWrites += ids to value+        }+    }++    private fun photo(id: Long, favorite: Boolean = false, dateModified: Long = 100L) = Photo(+        id = id, name = "p$id", uri = "content://media/external/images/media/$id",+        date = 1_000L, width = 100, height = 100, dateModified = dateModified,+        exifSet = true, lat = null, long = null, videoData = null, panoData = null,+        isTrashed = false, mimeType = "image/jpeg", album = "Camera",+        clipEmbedding = byteArrayOf(9), clipScanned = true, isFavorite = favorite,+    )++    /** MediaStore stand-in serving rows with IS_FAVORITE and recording each query's selection. */+    private class FakeMediaProvider(+        private val imageRows: List<Array<Any?>>,+        private val videoRows: List<Array<Any?>> = emptyList(),+    ) : ContentProvider() {+        val selections = mutableListOf<String?>()++        override fun onCreate(): Boolean = true++        override fun query(+            uri: Uri, projection: Array<out String>?, selection: String?,+            selectionArgs: Array<out String>?, sortOrder: String?,+        ): Cursor = throw UnsupportedOperationException("bundle query only")++        override fun query(+            uri: Uri, projection: Array<out String>?, queryArgs: Bundle?,+            cancellationSignal: android.os.CancellationSignal?,+        ): Cursor {+            val columns = projection ?: COLUMNS+            // The id-only deletion scan has no selection; record the content queries.+            if (columns.size > 1) selections += queryArgs?.getString(ContentResolver.QUERY_ARG_SQL_SELECTION)+            val rows = if (uri.toString().contains("/video/")) videoRows else imageRows+            val cursor = MatrixCursor(columns)+            for (row in rows) {+                val byName = COLUMNS.zip(row).toMap()+                cursor.addRow(columns.map { byName[it] })+            }+            return cursor+        }++        override fun getType(uri: Uri): String? = null+        override fun insert(uri: Uri, values: ContentValues?): Uri? = null+        override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+        override fun update(+            uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?,+        ): Int = 0++        companion object {+            val COLUMNS = arrayOf(+                MediaStore.MediaColumns._ID,+                MediaStore.MediaColumns.DISPLAY_NAME,+                MediaStore.MediaColumns.DATE_TAKEN,+                MediaStore.MediaColumns.DATE_ADDED,+                MediaStore.MediaColumns.DATE_MODIFIED,+                MediaStore.MediaColumns.WIDTH,+                MediaStore.MediaColumns.HEIGHT,+                MediaStore.MediaColumns.IS_TRASHED,+                MediaStore.MediaColumns.MIME_TYPE,+                MediaStore.MediaColumns.BUCKET_DISPLAY_NAME,+                MediaStore.MediaColumns.IS_FAVORITE,+                MediaStore.Video.Media.DURATION,+            )+        }+    }++    private fun row(id: Long, favorite: Boolean, dateModified: Long = 100L, duration: Long? = null): Array<Any?> =+        arrayOf(+            id, "p$id", 1_000L, 1L, dateModified, 100, 100, 0, "image/jpeg", "Camera",+            if (favorite) 1 else 0, duration,+        )++    private fun register(provider: FakeMediaProvider): FakeMediaProvider {+        ShadowContentResolver.registerProviderInternal(MediaStore.AUTHORITY, provider)+        return provider+    }++    @Test+    fun favoriteSetInAnotherAppIsWrittenByColumnNotUpserted() = runBlocking<Unit> {+        // Photo 1 was favourited elsewhere, photo 2 unfavourited; nothing else moved.+        register(FakeMediaProvider(listOf(row(1, favorite = true), row(2, favorite = false))))+        val repository = FakePhotosRepository(context).apply {+            all = listOf(photo(1, favorite = false), photo(2, favorite = true))+        }++        syncPhotos(context, repository, null, 0L)++        // No row rebuild (which would drop the CLIP embedding); one targeted write each way.+        assertTrue(repository.upsertedBatches.isEmpty(), repository.upsertedBatches.toString())+        assertEquals(+            setOf(listOf(1L) to true, listOf(2L) to false),+            repository.favoriteWrites.toSet(),+        )+    }++    @Test+    fun newAndOtherwiseChangedRowsCarryTheirFavoriteFlag() = runBlocking<Unit> {+        register(+            FakeMediaProvider(+                imageRows = listOf(row(1, favorite = true, dateModified = 999L), row(3, favorite = true)),+                videoRows = listOf(row(5, favorite = true, duration = 4_000L)),+            ),+        )+        val repository = FakePhotosRepository(context).apply { all = listOf(photo(1, favorite = false)) }++        syncPhotos(context, repository, null, 0L)++        val upserted = repository.upsertedBatches.single().associateBy { it.id }+        assertEquals(setOf(1L, 3L, 5L), upserted.keys)+        // Videos are favourited the same way as photos.+        assertTrue(upserted.values.all { it.isFavorite })+        assertTrue(repository.favoriteWrites.isEmpty())+    }++    @Test+    fun unchangedFavoriteIsLeftAlone() = runBlocking<Unit> {+        register(FakeMediaProvider(listOf(row(1, favorite = true))))+        val repository = FakePhotosRepository(context).apply { all = listOf(photo(1, favorite = true)) }++        syncPhotos(context, repository, null, 0L)++        assertTrue(repository.upsertedBatches.isEmpty())+        assertTrue(repository.favoriteWrites.isEmpty())+    }++    @Test+    fun favoriteDeletedElsewhereDropsOut() = runBlocking<Unit> {+        register(FakeMediaProvider(listOf(row(1, favorite = false))))+        val repository = FakePhotosRepository(context).apply {+            all = listOf(photo(1), photo(2, favorite = true))+        }++        syncPhotos(context, repository, null, 0L)++        assertEquals(listOf(listOf(2L)), repository.deletedBatches)+    }++    private class FakeFlag : OneTimeFlag {+        var value = false+        var sets = 0+        override suspend fun isSet(): Boolean = value+        override suspend fun set() {+            value = true+            sets+++        }+    }++    @Test+    fun favoritesRescanIsFullOnceThenIncremental() = runBlocking<Unit> {+        val provider = register(FakeMediaProvider(listOf(row(1, favorite = true))))+        val repository = FakePhotosRepository(context).apply { all = listOf(photo(1, favorite = false)) }+        val flag = FakeFlag()++        // First sync after the upgrade: full scan despite a stored generation, so+        // the favourite made before the upgrade is picked up.+        syncLibrary(context, repository, lastGeneration = 42L, needsMimeBackfill = false, favoritesRescan = flag)+        assertTrue(provider.selections.isNotEmpty())+        assertTrue(provider.selections.all { it == null }, provider.selections.toString())+        assertEquals(listOf(listOf(1L) to true), repository.favoriteWrites)+        assertTrue(flag.value)++        // Every later sync is incremental again, and the flag is not rewritten.+        provider.selections.clear()+        syncLibrary(context, repository, lastGeneration = 42L, needsMimeBackfill = false, favoritesRescan = flag)+        assertTrue(provider.selections.isNotEmpty())+        assertTrue(+            provider.selections.all { it == "${MediaStore.MediaColumns.GENERATION_MODIFIED} > 42" },+            provider.selections.toString(),+        )+        assertEquals(1, flag.sets)+    }++    @Test+    fun mimeBackfillStillForcesAFullScanAfterTheRescan() = runBlocking<Unit> {+        val provider = register(FakeMediaProvider(listOf(row(1, favorite = false))))+        val repository = FakePhotosRepository(context).apply { all = listOf(photo(1)) }+        val flag = FakeFlag().apply { value = true }++        syncLibrary(context, repository, lastGeneration = 42L, needsMimeBackfill = true, favoritesRescan = flag)++        assertTrue(provider.selections.all { it == null })+        assertEquals(0, flag.sets)+    }++    @Test+    fun freshInstallFullScanAlsoMarksTheRescanDone() = runBlocking<Unit> {+        val provider = register(FakeMediaProvider(emptyList()))+        val flag = FakeFlag()++        syncLibrary(context, FakePhotosRepository(context), 0L, needsMimeBackfill = false, favoritesRescan = flag)++        assertNull(provider.selections.firstOrNull())+        assertTrue(flag.value)+        assertFalse(provider.selections.any { it != null })+    }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.ktnew file mode 100644index 0000000000..29e688daa6--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosFavoritesUiTest.kt@@ -0,0 +1,225 @@+package com.vayunmathur.photos.util++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.R+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.ui.AlbumsScreen+import com.vayunmathur.photos.ui.FavoritesScreen+import com.vayunmathur.photos.ui.GalleryScreen+import com.vayunmathur.photos.ui.PhotoMetadataCard+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * #912 Compose tests: the viewer's heart, the grid's multi-select heart and+ * the Favorites tile and page.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosFavoritesUiTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context = ApplicationProvider.getApplicationContext<android.content.Context>()++    private var nextId = 1L++    private fun photo(name: String, date: Long, favorite: Boolean = false, trashed: Boolean = false) = Photo(+        id = nextId++,+        name = name,+        uri = "content://media/external/images/media/$name",+        date = date,+        width = 100,+        height = 100,+        dateModified = date,+        exifSet = false,+        lat = null,+        long = null,+        videoData = null,+        panoData = null,+        isTrashed = trashed,+        isFavorite = favorite,+    )++    private fun str(id: Int, vararg args: Any): String = context.getString(id, *args)++    private fun stubThumbnail(): @Composable (Photo, Modifier) -> Unit =+        { photo, modifier -> Box(modifier.background(Color.Gray).testTag("thumb-" + photo.id)) }++    // ---- Viewer heart ----++    @Test+    fun viewerHeartShowsStateAndToggles() {+        val target = photo("p", 100L)+        val toggled = mutableListOf<Long>()+        var favorite by mutableStateOf(false)+        composeRule.setContent {+            PhotoMetadataCard(+                photo = target,+                context = context,+                countryName = null,+                fileSize = null,+                pageOffset = 0f,+                onEditPhoto = {},+                isFavorite = favorite,+                onToggleFavorite = { toggled += it.id },+            )+        }++        composeRule.onNodeWithContentDescription(str(R.string.action_favorite)).performClick()+        assertEquals(listOf(target.id), toggled)++        favorite = true+        composeRule.onNodeWithContentDescription(str(R.string.action_unfavorite)).assertIsDisplayed()+    }++    // ---- Grid multi-select heart ----++    @Test+    fun gallerySelectionHeartFavoritesAMixedSelection() {+        val fav = photo("fav", 100L, favorite = true)+        val plain = photo("plain", 200L)+        var toggles = 0+        val actions = object : GalleryActions {+            override fun toggleFavoriteSelection() {+                toggles+++            }+        }+        val columns = mutableFloatStateOf(3f)+        composeRule.setContent {+            CompositionLocalProvider(LocalColumnCount provides columns) {+                GalleryScreen(+                    backStack = NavBackStack(arrayOf<Route>(Route.Gallery)),+                    state = GalleryUiState(photos = listOf(fav, plain), selectedIds = setOf(fav.id, plain.id)),+                    actions = actions,+                    thumbnail = stubThumbnail(),+                )+            }+        }++        // Mixed: the outlined heart, i.e. "Favorite" (favourite them all).+        composeRule.onNodeWithContentDescription(str(R.string.action_favorite)).performClick()+        assertEquals(1, toggles)+    }++    // ---- Albums tile ----++    @Test+    fun favoritesTileShowsCountAndCoverAndOpensFavorites() {+        val cover = photo("cover", 100L, favorite = true)+        val stack = NavBackStack<Route>(arrayOf(Route.Albums))+        composeRule.setContent {+            AlbumsScreen(+                backStack = stack,+                state = AlbumsUiState(+                    defaultAlbums = listOf(+                        DefaultAlbum(DefaultAlbumKind.FAVORITES, count = 4, cover = cover),+                        DefaultAlbum(DefaultAlbumKind.TRASH, count = 1),+                    ),+                ),+                thumbnail = stubThumbnail(),+            )+        }++        composeRule.onNodeWithText(str(R.string.label_favorites)).assertIsDisplayed()+        composeRule.onNodeWithText(+            context.resources.getQuantityString(R.plurals.album_photo_count, 4, 4),+        ).assertIsDisplayed()+        composeRule.onNodeWithTag("thumb-" + cover.id, useUnmergedTree = true).performClick()+        assertEquals(Route.Favorites, stack.backStack.last())+    }++    @Test+    fun emptyFavoritesTileShowsTheLabelWithoutACover() {+        composeRule.setContent {+            AlbumsScreen(+                backStack = NavBackStack(arrayOf<Route>(Route.Albums)),+                state = AlbumsUiState(defaultAlbums = listOf(DefaultAlbum(DefaultAlbumKind.FAVORITES, count = 0))),+                thumbnail = stubThumbnail(),+            )+        }+        composeRule.onNodeWithText(str(R.string.label_favorites)).assertIsDisplayed()+        composeRule.onNodeWithText(+            context.resources.getQuantityString(R.plurals.album_photo_count, 0, 0),+        ).assertIsDisplayed()+    }++    // ---- Favorites page ----++    private fun setFavorites(state: GalleryUiState, actions: GalleryActions, stack: NavBackStack<Route>) {+        val columns = mutableFloatStateOf(3f)+        composeRule.setContent {+            CompositionLocalProvider(LocalColumnCount provides columns) {+                FavoritesScreen(backStack = stack, state = state, actions = actions, thumbnail = stubThumbnail())+            }+        }+    }++    @Test+    fun favoritesPageEmptyState() {+        setFavorites(GalleryUiState(), GalleryActions.Noop, NavBackStack(arrayOf<Route>(Route.Favorites)))+        composeRule.onNodeWithText(str(R.string.favorites_empty)).assertIsDisplayed()+    }++    @Test+    fun favoritesPageOpensTheViewerOverTheFavorites() {+        val a = photo("a", 200L, favorite = true)+        val b = photo("b", 100L, favorite = true)+        val stack = NavBackStack<Route>(arrayOf(Route.Favorites))+        setFavorites(GalleryUiState(photos = listOf(a, b)), GalleryActions.Noop, stack)++        composeRule.onNodeWithTag("thumb-" + b.id, useUnmergedTree = true).performClick()++        val last = stack.backStack.last()+        assertTrue(last is Route.PhotoPage)+        last as Route.PhotoPage+        assertEquals(b.id, last.id)+        assertEquals(listOf(a.id, b.id), last.overridePhotosList?.map { it.id })+    }++    @Test+    fun favoritesPageSelectionUnfavorites() {+        val a = photo("a", 200L, favorite = true)+        var toggles = 0+        val actions = object : GalleryActions {+            override fun toggleFavoriteSelection() {+                toggles+++            }+        }+        setFavorites(+            GalleryUiState(photos = listOf(a), selectedIds = setOf(a.id)),+            actions,+            NavBackStack(arrayOf<Route>(Route.Favorites)),+        )++        // Every selected item is a favourite: the filled heart removes them.+        composeRule.onNodeWithContentDescription(str(R.string.action_unfavorite)).performClick()+        assertEquals(1, toggles)+    }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.ktindex 2ef41e0762..17d21c48a9 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1WorkersTest.kt@@ -16,6 +16,7 @@ import com.vayunmathur.photos.data.MIGRATION_15_16 import com.vayunmathur.photos.data.MIGRATION_16_17 import com.vayunmathur.photos.data.MIGRATION_17_18 import com.vayunmathur.photos.data.MIGRATION_18_19+import com.vayunmathur.photos.data.MIGRATION_19_20 import com.vayunmathur.photos.data.MIGRATION_1_2 import com.vayunmathur.photos.data.MIGRATION_2_3 import com.vayunmathur.photos.data.MIGRATION_3_4@@ -68,7 +69,7 @@ class PhotosSlice1WorkersTest {         throw AssertionError("no work enqueued under $name")     } -    // ---- Migration chain v1 -> v19 ----+    // ---- Migration chain v1 -> v20 ----      @Test     fun fullMigrationChainUpgradesV1Schema() = runBlocking<Unit> {@@ -86,9 +87,9 @@ class PhotosSlice1WorkersTest {                 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, MIGRATION_17_18, MIGRATION_18_19,+                MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20,             )-            assertEquals(18, PhotoDatabase.migrations.size)+            assertEquals(19, PhotoDatabase.migrations.size)             for (migration in migrations) migration.migrate(connection)              fun queryStrings(sql: String): List<String> = connection.prepare(sql).use { statement ->@@ -116,6 +117,7 @@ class PhotosSlice1WorkersTest {             for (column in listOf(                 "dateModified", "isTrashed", "faceScanned", "ocrText", "ocrScanned",                 "clipEmbedding", "clipScanned", "mimeType", "ocrBoxes", "album", "projectionType",+                "isFavorite",             )) {                 assertTrue(column in columnNames, "missing $column in $columnNames")             }@@ -129,9 +131,9 @@ class PhotosSlice1WorkersTest {     }      @Test-    fun migrationListIsContiguousFrom1To19() {+    fun migrationListIsContiguousFrom1To20() {         val versions = PhotoDatabase.migrations.map { it.startVersion to it.endVersion }-        assertEquals((1..18).map { it to it + 1 }, versions)+        assertEquals((1..19).map { it to it + 1 }, versions)     }      // ---- Worker scheduling ----
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3GalleryTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3GalleryTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3GalleryTest.ktindex 378b533c9b..aeb44ec68f 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3GalleryTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3GalleryTest.kt@@ -425,6 +425,7 @@ class PhotosSlice3GalleryTest {         override suspend fun delete(value: Photo): Int = dao.delete(value)         override suspend fun setTrashed(id: Long) = dao.setTrashed(id)         override suspend fun setAlbum(ids: List<Long>, album: String?) = dao.setAlbum(ids, album)+        override suspend fun setFavorite(ids: List<Long>, value: Boolean) = dao.setFavorite(ids, value)         override suspend fun getAll(): List<Photo> = dao.getAll()     } 
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.ktindex 7aaaa19f55..85e0dd8767 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice3PagesTest.kt@@ -10,6 +10,9 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.performScrollToNode import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick@@ -137,6 +140,9 @@ class PhotosSlice3PagesTest {                 )             }         }+        // The default tiles (Favorites, Trash, Secure Folder) fill the first+        // rows of the grid, so bring the empty copy below them into view.+        composeRule.onNode(hasScrollAction()).performScrollToNode(hasText(str(R.string.albums_empty)))         composeRule.onNodeWithText(str(R.string.albums_empty), substring = false)             .assertIsDisplayed()     }@@ -354,6 +360,7 @@ class PhotosSlice3PagesTest {         override suspend fun delete(value: Photo): Int = dao.delete(value)         override suspend fun setTrashed(id: Long) = dao.setTrashed(id)         override suspend fun setAlbum(ids: List<Long>, album: String?) = dao.setAlbum(ids, album)+        override suspend fun setFavorite(ids: List<Long>, value: Boolean) = dao.setFavorite(ids, value)         override suspend fun getAll(): List<Photo> = dao.getAll()     }