-
-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: recursive local wallpapers and filter for images only
- Loading branch information
Showing
3 changed files
with
36 additions
and
4 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
35 changes: 33 additions & 2 deletions
35
app/src/main/java/com/bnyro/wallpaper/util/LocalWallpaperHelper.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) } | ||
} | ||
} |