perf: scan folders via DocumentsContract cursor instead of DocumentFile

Adding a folder walked the tree with DocumentFile.listFiles(), which issues
a separate ContentResolver IPC for every file and for every attribute access
(name, isDirectory, lastModified). For folders with tens of thousands of
images this dominates the add/refresh time and risks ANRs.

Replace it with a single DocumentsContract cursor query per directory that
returns document id, name, mime type and last-modified in one round-trip, and
traverse directories iteratively to avoid deep-recursion stack overflow. The
album-view add path additionally dropped its per-file getFileName() and
detectMediaType() lookups by reusing the name returned from the scan.

Returned URIs are built from the same tree document id as before, so existing
wallpaper URIs remain stable. Both folder-scan call sites now share one helper.

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 9c8fbaf1cc
commit e2e9d6f4f9
3 files changed
+91 -68

No files matched your search

@@ -3,7 +3,9 @@ package com.anthonyla.paperize.core.util
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.core.constants.Constants
import java.util.UUID
/**
@@ -34,30 +36,81 @@ fun Uri.getFileName(context: Context): String? {
}
/**
* Scan a folder URI and return all image file URIs
* One image file discovered while scanning a folder tree.
*
* [name] and [lastModified] are read from the same cursor row as [uri], so callers
* do not need a follow-up per-file query to obtain them.
*/
fun Uri.scanFolderForImages(context: Context): List<Uri> {
val documentFile = DocumentFile.fromTreeUri(context, this) ?: return emptyList()
if (!documentFile.isDirectory) return emptyList()
data class ScannedImage(
val uri: Uri,
val name: String,
val lastModified: Long
)
val imageUris = mutableListOf<Uri>()
/**
* Recursively scan a tree [Uri] for image files.
*
* Uses a single [DocumentsContract] cursor query per directory instead of
* [DocumentFile.listFiles], which issues a separate IPC round-trip for every file and
* for every attribute access (name, isDirectory, lastModified). For folders with tens of
* thousands of files that difference is the dominant cost. Directories are traversed
* iteratively to avoid deep-recursion stack overflow on heavily nested trees.
*
* 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.
*/
fun Uri.scanFolderImages(context: Context): List<ScannedImage> {
val rootDocumentId = try {
DocumentsContract.getTreeDocumentId(this)
} catch (_: IllegalArgumentException) {
return emptyList() // Not a tree URI
}
fun scanDirectory(directory: DocumentFile) {
directory.listFiles().forEach { file ->
when {
file.isDirectory -> scanDirectory(file) // Recursively scan subdirectories
file.isFile -> {
val ext = file.name?.substringAfterLast('.', "")?.lowercase() ?: ""
if (ext in com.anthonyla.paperize.core.constants.Constants.SUPPORTED_IMAGE_EXTENSIONS) {
imageUris.add(file.uri)
val projection = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED
)
val results = mutableListOf<ScannedImage>()
val pendingDirs = ArrayDeque<String>()
pendingDirs.addLast(rootDocumentId)
while (pendingDirs.isNotEmpty()) {
val parentDocumentId = pendingDirs.removeLast()
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(this, parentDocumentId)
try {
context.contentResolver.query(childrenUri, projection, null, null, null)?.use { cursor ->
val idColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val nameColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val modifiedColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
val documentId = cursor.getString(idColumn) ?: continue
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
pendingDirs.addLast(documentId)
} else {
val name = cursor.getString(nameColumn) ?: continue
val extension = name.substringAfterLast('.', "").lowercase()
if (extension in Constants.SUPPORTED_IMAGE_EXTENSIONS) {
results.add(
ScannedImage(
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId),
name = name,
lastModified = if (cursor.isNull(modifiedColumn)) 0L else cursor.getLong(modifiedColumn)
)
)
}
}
}
}
} catch (_: Exception) {
// Skip directories that can't be read and continue with the rest of the tree.
}
}
scanDirectory(documentFile)
return imageUris.sortedBy { it.toString() } // Sort for consistency
return results
}
/**
@@ -4,13 +4,12 @@ import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperSourceType
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.util.generateId
import com.anthonyla.paperize.core.util.isValid
import com.anthonyla.paperize.core.util.scanFolderImages
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
import com.anthonyla.paperize.data.database.dao.WallpaperDao
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
@@ -261,51 +260,23 @@ class WallpaperRepositoryImpl @Inject constructor(
override suspend fun scanFolderForWallpapers(folderUri: Uri): Result<List<Wallpaper>> {
return try {
val documentFile = DocumentFile.fromTreeUri(context, folderUri)
?: return Result.Error(Exception("Invalid folder URI"))
val wallpapers = mutableListOf<Wallpaper>()
scanDirectoryRecursive(documentFile, wallpapers)
val wallpapers = folderUri.scanFolderImages(context).map { image ->
Wallpaper(
id = generateId(),
albumId = "",
folderId = null,
uri = image.uri.toString(),
fileName = image.name,
dateModified = image.lastModified,
sourceType = WallpaperSourceType.FOLDER
)
}
Result.Success(wallpapers)
} catch (e: Exception) {
Result.Error(e)
}
}
private fun scanDirectoryRecursive(directory: DocumentFile, result: MutableList<Wallpaper>) {
directory.listFiles().forEach { file ->
if (file.isDirectory) {
scanDirectoryRecursive(file, result)
} else if (file.isFile && file.name?.let { name -> isImageFile(name) } == true) {
try {
val uri = file.uri.toString()
val fileName = file.name ?: return@forEach
val dateModified = file.lastModified()
result.add(
Wallpaper(
id = generateId(),
albumId = "",
folderId = null,
uri = uri,
fileName = fileName,
dateModified = dateModified,
sourceType = WallpaperSourceType.FOLDER
)
)
} catch (_: Exception) {
// Skip failed items
}
}
}
}
private fun isImageFile(fileName: String): Boolean {
val extension = fileName.substringAfterLast('.', "").lowercase()
return extension in Constants.SUPPORTED_IMAGE_EXTENSIONS
}
override suspend fun isWallpaperInAlbum(albumId: String, uri: String): Boolean =
wallpaperDao.getWallpaperByUri(uri)?.let { it.albumId == albumId } ?: false
@@ -11,7 +11,7 @@ import androidx.navigation.toRoute
import com.anthonyla.paperize.core.util.detectMediaType
import com.anthonyla.paperize.core.util.generateId
import com.anthonyla.paperize.core.util.getFileName
import com.anthonyla.paperize.core.util.scanFolderForImages
import com.anthonyla.paperize.core.util.scanFolderImages
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.Folder
@@ -113,25 +113,24 @@ class AlbumViewViewModel @Inject constructor(
fun addFolder(uri: String) {
viewModelScope.launch {
// Scan folder for images on IO dispatcher
val imageUris = withContext(Dispatchers.IO) {
uri.toUri().scanFolderForImages(context)
// 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() }
}
// Create folder with scanned wallpapers
val folderId = generateId()
val wallpapers = imageUris.mapIndexed { index, imageUri ->
val mediaType = imageUri.detectMediaType(context) ?: WallpaperMediaType.IMAGE
val wallpapers = images.mapIndexed { index, image ->
Wallpaper(
id = generateId(),
albumId = albumId,
folderId = folderId,
uri = imageUri.toString(),
fileName = imageUri.getFileName(context) ?: imageUri.lastPathSegment ?: imageUri.toString().substringAfterLast('/'),
dateModified = System.currentTimeMillis(),
uri = image.uri.toString(),
fileName = image.name,
dateModified = image.lastModified,
displayOrder = index,
mediaType = mediaType
mediaType = WallpaperMediaType.fromExtension(image.name.substringAfterLast('.', "")) ?: WallpaperMediaType.IMAGE
)
}