feat: show live import progress when adding folders/wallpapers

Adding a large folder previously gave no feedback at all (the FAB's
isLoading hook was hardcoded false), so a long import looked frozen.

Surface an ImportProgress state from AlbumViewViewModel and show a modal
dialog with a live count: a counting-up 'Scanning... N found' during the
folder walk, then a determinate 'Saving X / total' bar while rows are
written. scanFolderImages now reports discovery progress (throttled), and
inserts run in chunks that report saved/total - which also avoids
materializing the full entity list at once.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
malteishandClaude Opus 4.8 authored and Anthony La committed 2026-07-28 22:03:50 -07:00
1 parent e2e9d6f4f9
commit ade1fd4673
8 files changed
+204 -13

No files matched your search

@@ -58,8 +58,11 @@ data class ScannedImage(
*
* Returned URIs are built from the same tree document id used by [DocumentFile], so they
* are byte-for-byte identical to the previous implementation and remain stable across the app.
*
* [onProgress] is invoked with the running number of images found, throttled to roughly once
* per [PROGRESS_REPORT_INTERVAL] discoveries so callers can show a live count without flooding.
*/
fun Uri.scanFolderImages(context: Context): List<ScannedImage> {
fun Uri.scanFolderImages(context: Context, onProgress: ((found: Int) -> Unit)? = null): List<ScannedImage> {
val rootDocumentId = try {
DocumentsContract.getTreeDocumentId(this)
} catch (_: IllegalArgumentException) {
@@ -74,6 +77,7 @@ fun Uri.scanFolderImages(context: Context): List<ScannedImage> {
)
val results = mutableListOf<ScannedImage>()
var lastReported = 0
val pendingDirs = ArrayDeque<String>()
pendingDirs.addLast(rootDocumentId)
@@ -102,6 +106,10 @@ fun Uri.scanFolderImages(context: Context): List<ScannedImage> {
lastModified = if (cursor.isNull(modifiedColumn)) 0L else cursor.getLong(modifiedColumn)
)
)
if (onProgress != null && results.size - lastReported >= PROGRESS_REPORT_INTERVAL) {
lastReported = results.size
onProgress(results.size)
}
}
}
}
@@ -110,9 +118,13 @@ fun Uri.scanFolderImages(context: Context): List<ScannedImage> {
// Skip directories that can't be read and continue with the rest of the tree.
}
}
onProgress?.invoke(results.size)
return results
}
/** Report scan progress at most once per this many discovered images. */
private const val PROGRESS_REPORT_INTERVAL = 512
/**
* UUID generation
*/
@@ -43,6 +43,11 @@ class AlbumRepositoryImpl @Inject constructor(
private val wallpaperRepository: dagger.Lazy<com.anthonyla.paperize.domain.repository.WallpaperRepository>
) : AlbumRepository {
companion object {
/** Number of wallpapers written per insert/progress step during an import. */
private const val WALLPAPER_INSERT_CHUNK_SIZE = 500
}
override fun getAlbumSummaries(): Flow<List<AlbumSummary>> =
albumDao.getAlbumSummaries().map { it.toDomainModelsFromSummaries() }
@@ -115,12 +120,13 @@ class AlbumRepositoryImpl @Inject constructor(
override suspend fun addWallpapersToAlbum(
albumId: String,
wallpapers: List<Wallpaper>
wallpapers: List<Wallpaper>,
onProgress: (saved: Int, total: Int) -> Unit
): Result<Unit> {
return try {
// Atomic transaction - insert wallpapers, update timestamp, and update cover
database.withTransaction {
wallpaperDao.insertWallpapers(wallpapers.toEntities())
insertWallpapersChunked(wallpapers, onProgress)
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
// Update album cover if it doesn't have one
@@ -132,13 +138,17 @@ class AlbumRepositoryImpl @Inject constructor(
}
}
override suspend fun addFolderToAlbum(albumId: String, folder: Folder): Result<Unit> {
override suspend fun addFolderToAlbum(
albumId: String,
folder: Folder,
onProgress: (saved: Int, total: Int) -> Unit
): Result<Unit> {
return try {
// Atomic transaction - folder, wallpapers, timestamp, and cover all succeed or all fail
database.withTransaction {
folderDao.insertFolder(folder.toEntity())
// Insert folder wallpapers
wallpaperDao.insertWallpapers(folder.wallpapers.toEntities())
insertWallpapersChunked(folder.wallpapers, onProgress)
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
// Update album cover if it doesn't have one
@@ -150,6 +160,24 @@ class AlbumRepositoryImpl @Inject constructor(
}
}
/**
* Insert [wallpapers] in chunks, mapping each chunk to entities only as it is written so the
* full entity list is never materialized at once, and reporting progress after each chunk.
* Must be called inside a transaction so the overall insert stays atomic.
*/
private suspend fun insertWallpapersChunked(
wallpapers: List<Wallpaper>,
onProgress: (saved: Int, total: Int) -> Unit
) {
val total = wallpapers.size
var saved = 0
wallpapers.chunked(WALLPAPER_INSERT_CHUNK_SIZE).forEach { chunk ->
wallpaperDao.insertWallpapers(chunk.toEntities())
saved += chunk.size
onProgress(saved, total)
}
}
override suspend fun updateFolder(folder: Folder): Result<Unit> {
return try {
folderDao.updateFolder(folder.toEntity())
@@ -64,17 +64,28 @@ interface AlbumRepository {
suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result<Unit>
/**
* Add wallpapers to album
* Add wallpapers to album.
*
* [onProgress] is invoked as rows are written, with the number saved so far and the total,
* so callers can show import progress.
*/
suspend fun addWallpapersToAlbum(
albumId: String,
wallpapers: List<Wallpaper>
wallpapers: List<Wallpaper>,
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Result<Unit>
/**
* Add folder to album
* Add folder to album.
*
* [onProgress] is invoked as the folder's wallpapers are written, with the number saved so far
* and the total, so callers can show import progress.
*/
suspend fun addFolderToAlbum(albumId: String, folder: Folder): Result<Unit>
suspend fun addFolderToAlbum(
albumId: String,
folder: Folder,
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Result<Unit>
/**
* Update folder
@@ -37,6 +37,7 @@ import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.presentation.common.components.AddAlbumAnimatedFab
import com.anthonyla.paperize.presentation.screens.album_view.components.AlbumViewTopBar
import com.anthonyla.paperize.presentation.screens.album_view.components.FolderItem
import com.anthonyla.paperize.presentation.screens.album_view.components.ImportProgressDialog
import com.anthonyla.paperize.presentation.screens.album_view.components.SortBottomSheet
import com.anthonyla.paperize.presentation.screens.album_view.components.SortOption
import com.anthonyla.paperize.presentation.screens.album_view.components.WallpaperItem
@@ -62,6 +63,7 @@ fun AlbumViewScreen(
val selectedWallpapers by viewModel.selectedWallpapers.collectAsStateWithLifecycle()
val selectedFolders by viewModel.selectedFolders.collectAsStateWithLifecycle()
val isSelectionMode by viewModel.isSelectionMode.collectAsStateWithLifecycle()
val importProgress by viewModel.importProgress.collectAsStateWithLifecycle()
val selectedCount = selectedWallpapers.size + selectedFolders.size
// Check if all items are selected
@@ -157,7 +159,7 @@ fun AlbumViewScreen(
// Hide FAB when in selection mode
if (!isSelectionMode) {
AddAlbumAnimatedFab(
isLoading = false,
isLoading = importProgress !is ImportProgress.Idle,
onImageClick = { imagePickerLauncher.launch(arrayOf("image/*")) },
onFolderClick = { folderPickerLauncher.launch(null) }
)
@@ -248,6 +250,9 @@ fun AlbumViewScreen(
)
}
// Import progress (add folder / add wallpapers)
ImportProgressDialog(progress = importProgress)
// Delete Album Confirmation Dialog
if (showDeleteAlbumDialog) {
AlertDialog(
@@ -80,8 +80,12 @@ class AlbumViewViewModel @Inject constructor(
private val _isSelectionMode = MutableStateFlow(false)
val isSelectionMode: StateFlow<Boolean> = _isSelectionMode.asStateFlow()
private val _importProgress = MutableStateFlow<ImportProgress>(ImportProgress.Idle)
val importProgress: StateFlow<ImportProgress> = _importProgress.asStateFlow()
fun addWallpapers(uris: List<String>) {
viewModelScope.launch {
_importProgress.value = ImportProgress.Saving(saved = 0, total = uris.size)
val existingCount = wallpapers.value.size
val newWallpapers = uris.mapIndexed { index, uri ->
val parsedUri = uri.toUri()
@@ -98,7 +102,10 @@ class AlbumViewViewModel @Inject constructor(
mediaType = mediaType
)
}
when (val result = albumRepository.addWallpapersToAlbum(albumId, newWallpapers)) {
val result = albumRepository.addWallpapersToAlbum(albumId, newWallpapers) { saved, total ->
_importProgress.value = ImportProgress.Saving(saved, total)
}
when (result) {
is com.anthonyla.paperize.core.Result.Success -> {
// Clear queues so the new wallpapers are included on the next cycle
wallpaperRepository.clearQueuesForAlbum(albumId)
@@ -108,15 +115,19 @@ class AlbumViewViewModel @Inject constructor(
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
_importProgress.value = ImportProgress.Idle
}
}
fun addFolder(uri: String) {
viewModelScope.launch {
_importProgress.value = ImportProgress.Scanning(found = 0)
// Scan folder for images on IO dispatcher. The scan already returns each file's
// name and modified time, so no per-file follow-up query is needed below.
val images = withContext(Dispatchers.IO) {
uri.toUri().scanFolderImages(context).sortedBy { it.uri.toString() }
uri.toUri().scanFolderImages(context) { found ->
_importProgress.value = ImportProgress.Scanning(found)
}.sortedBy { it.uri.toString() }
}
// Create folder with scanned wallpapers
@@ -133,6 +144,7 @@ class AlbumViewViewModel @Inject constructor(
mediaType = WallpaperMediaType.fromExtension(image.name.substringAfterLast('.', "")) ?: WallpaperMediaType.IMAGE
)
}
_importProgress.value = ImportProgress.Saving(saved = 0, total = wallpapers.size)
val folder = Folder(
id = folderId,
@@ -145,7 +157,10 @@ class AlbumViewViewModel @Inject constructor(
wallpapers = wallpapers
)
when (val result = albumRepository.addFolderToAlbum(albumId, folder)) {
val result = albumRepository.addFolderToAlbum(albumId, folder) { saved, total ->
_importProgress.value = ImportProgress.Saving(saved, total)
}
when (result) {
is com.anthonyla.paperize.core.Result.Success -> {
// Clear queues so the new folder's wallpapers are included on the next cycle
wallpaperRepository.clearQueuesForAlbum(albumId)
@@ -155,6 +170,7 @@ class AlbumViewViewModel @Inject constructor(
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
_importProgress.value = ImportProgress.Idle
}
}
@@ -0,0 +1,16 @@
package com.anthonyla.paperize.presentation.screens.album_view
/**
* Progress of an ongoing add-folder / add-wallpapers import, surfaced to the UI so it can
* show a live count instead of a bare spinner.
*/
sealed interface ImportProgress {
/** No import running. */
data object Idle : ImportProgress
/** Walking the folder tree; the total is not yet known. */
data class Scanning(val found: Int) : ImportProgress
/** Writing the discovered images to the database. */
data class Saving(val saved: Int, val total: Int) : ImportProgress
}
@@ -0,0 +1,99 @@
package com.anthonyla.paperize.presentation.screens.album_view.components
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.screens.album_view.ImportProgress
/**
* Non-dismissable modal shown while a folder/wallpaper import is running, displaying a live count
* (and a determinate bar once the total is known) instead of a bare spinner.
*
* Renders nothing when [progress] is [ImportProgress.Idle].
*/
@Composable
fun ImportProgressDialog(progress: ImportProgress) {
if (progress is ImportProgress.Idle) return
Dialog(
onDismissRequest = { /* Block dismissal while importing */ },
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
val titleRes = when (progress) {
is ImportProgress.Scanning -> R.string.import_adding_folder
else -> R.string.import_adding_wallpapers
}
Text(
text = stringResource(titleRes),
style = MaterialTheme.typography.titleMedium
)
when (progress) {
is ImportProgress.Scanning -> {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
Text(
text = stringResource(R.string.import_scanning, progress.found),
style = MaterialTheme.typography.bodyMedium
)
}
}
is ImportProgress.Saving -> {
Text(
text = stringResource(R.string.import_saving, progress.saved, progress.total),
style = MaterialTheme.typography.bodyMedium
)
val fraction by animateFloatAsState(
targetValue = if (progress.total > 0) progress.saved.toFloat() / progress.total else 0f,
label = "importProgress"
)
LinearProgressIndicator(
progress = { fraction },
modifier = Modifier
.fillMaxWidth()
.height(6.dp)
)
}
ImportProgress.Idle -> Unit // unreachable, guarded above
}
}
}
}
}
+4
View File
@@ -1,6 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Paperize</string>
<string name="import_adding_folder">Adding folder…</string>
<string name="import_adding_wallpapers">Adding wallpapers…</string>
<string name="import_scanning">Scanning… %1$d found</string>
<string name="import_saving">Saving %1$d / %2$d</string>
<string name="home">Home</string>
<string name="settings_screen">Settings</string>
<string name="wallpaper">Wallpaper</string>