Skip to content

Commit

Permalink
feat: recursive local wallpapers and filter for images only
Browse files Browse the repository at this point in the history
  • Loading branch information
Bnyro committed Jan 30, 2024
1 parent 7c87b26 commit 53c8e36
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions app/src/main/java/com/bnyro/wallpaper/util/LocalWallpaperHelper.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,45 @@
package com.bnyro.wallpaper.util

import android.content.Context
import android.graphics.BitmapFactory
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
import com.bnyro.wallpaper.enums.WallpaperConfig

object LocalWallpaperHelper {
private fun getAllFilesInCurrentDir(directory: DocumentFile?): List<DocumentFile> {
val files = mutableListOf<DocumentFile>()

val contents = directory?.listFiles().orEmpty()
files.addAll(contents.filter { it.isFile })

contents.filter { it.isDirectory }.forEach {
files.addAll(getAllFilesInCurrentDir(it))
}

return files
}

private fun DocumentFile.isImage(context: Context): Boolean {
val bmOptions = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
return try {
context.contentResolver.openInputStream(uri).use {
BitmapFactory.decodeStream(it, null, bmOptions)
}
bmOptions.outWidth != -1 && bmOptions.outHeight != -1
} catch (_: Exception) {
false
}
}

fun getLocalWalls(context: Context, config: WallpaperConfig): List<DocumentFile> {
return config.localFolderUris.map {
DocumentFile.fromTreeUri(context, it.toUri())?.listFiles().orEmpty().toList()
}.flatten()
val dir = DocumentFile.fromTreeUri(context, it.toUri())
getAllFilesInCurrentDir(dir)
}
.flatten()
.filter { it.isImage(context) }
}
}

0 comments on commit 53c8e36

Please sign in to comment.