From ade1fd467395aa7382f64c1185818acee01621e2 Mon Sep 17 00:00:00 2001 From: malteish Date: Sat, 27 Jun 2026 21:27:43 +0200 Subject: [PATCH] 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 --- .../paperize/core/util/Extensions.kt | 14 ++- .../data/repository/AlbumRepositoryImpl.kt | 36 ++++++- .../domain/repository/AlbumRepository.kt | 19 +++- .../screens/album_view/AlbumViewScreen.kt | 7 +- .../screens/album_view/AlbumViewViewModel.kt | 22 ++++- .../screens/album_view/ImportProgress.kt | 16 +++ .../components/ImportProgressDialog.kt | 99 +++++++++++++++++++ app/src/main/res/values/strings.xml | 4 + 8 files changed, 204 insertions(+), 13 deletions(-) create mode 100644 app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/ImportProgressDialog.kt diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt b/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt index 0280212..aacf7d9 100644 --- a/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt +++ b/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt @@ -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 { +fun Uri.scanFolderImages(context: Context, onProgress: ((found: Int) -> Unit)? = null): List { val rootDocumentId = try { DocumentsContract.getTreeDocumentId(this) } catch (_: IllegalArgumentException) { @@ -74,6 +77,7 @@ fun Uri.scanFolderImages(context: Context): List { ) val results = mutableListOf() + var lastReported = 0 val pendingDirs = ArrayDeque() pendingDirs.addLast(rootDocumentId) @@ -102,6 +106,10 @@ fun Uri.scanFolderImages(context: Context): List { 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 { // 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 */ diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt index 47bfcca..9279349 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt @@ -43,6 +43,11 @@ class AlbumRepositoryImpl @Inject constructor( private val wallpaperRepository: dagger.Lazy ) : 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> = albumDao.getAlbumSummaries().map { it.toDomainModelsFromSummaries() } @@ -115,12 +120,13 @@ class AlbumRepositoryImpl @Inject constructor( override suspend fun addWallpapersToAlbum( albumId: String, - wallpapers: List + wallpapers: List, + onProgress: (saved: Int, total: Int) -> Unit ): Result { 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 { + override suspend fun addFolderToAlbum( + albumId: String, + folder: Folder, + onProgress: (saved: Int, total: Int) -> Unit + ): Result { 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, + 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 { return try { folderDao.updateFolder(folder.toEntity()) diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt index 3677e79..3e21eb8 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt @@ -64,17 +64,28 @@ interface AlbumRepository { suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result /** - * 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 + wallpapers: List, + onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> } ): Result /** - * 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 + suspend fun addFolderToAlbum( + albumId: String, + folder: Folder, + onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> } + ): Result /** * Update folder diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt index 4eddad5..e263442 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt @@ -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( diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt index e01d995..90b30d9 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt @@ -80,8 +80,12 @@ class AlbumViewViewModel @Inject constructor( private val _isSelectionMode = MutableStateFlow(false) val isSelectionMode: StateFlow = _isSelectionMode.asStateFlow() + private val _importProgress = MutableStateFlow(ImportProgress.Idle) + val importProgress: StateFlow = _importProgress.asStateFlow() + fun addWallpapers(uris: List) { 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 } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt new file mode 100644 index 0000000..ad87d92 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt @@ -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 +} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/ImportProgressDialog.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/ImportProgressDialog.kt new file mode 100644 index 0000000..0ef226b --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/ImportProgressDialog.kt @@ -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 + } + } + } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4e7a46e..ddb5a18 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,6 +1,10 @@ Paperize + Adding folder… + Adding wallpapers… + Scanning… %1$d found + Saving %1$d / %2$d Home Settings Wallpaper