Skip to content

Commit

Permalink
Add support for using local images for the wallpaper changer (closes #43
Browse files Browse the repository at this point in the history
)
  • Loading branch information
Bnyro committed Jan 29, 2023
1 parent f5dc448 commit a266652
Show file tree
Hide file tree
Showing 7 changed files with 112 additions and 29 deletions.
60 changes: 55 additions & 5 deletions app/src/main/java/com/bnyro/wallpaper/ui/pages/SettingsPage.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package com.bnyro.wallpaper.ui.pages

import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
Expand All @@ -22,12 +30,36 @@ import com.bnyro.wallpaper.ui.models.MainModel
import com.bnyro.wallpaper.ui.nav.DrawerScreens
import com.bnyro.wallpaper.util.Preferences
import com.bnyro.wallpaper.util.WorkerHelper
import java.io.File
import java.time.Instant
import kotlinx.coroutines.launch

@Composable
fun SettingsPage(
viewModel: MainModel
) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()

val selectFiles = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenMultipleDocuments()
) {
context.filesDir.listFiles().orEmpty().forEach { file ->
file.delete()
}
scope.launch {
it.parallelStream().forEach { uri ->
context.contentResolver.openInputStream(uri)?.use { inputStream ->
File(context.filesDir, Instant.now().epochSecond.toString()).apply {
createNewFile()
outputStream().use { outputStream ->
inputStream.copyTo(outputStream)
}
}
}
}
}
}

Column(
modifier = Modifier
Expand Down Expand Up @@ -109,13 +141,31 @@ fun SettingsPage(
) {
WorkerHelper.enqueue(context, true)
}
val apis = listOf(DrawerScreens.Wallhaven, DrawerScreens.Picsum, DrawerScreens.OWalls)
BlockPreference(
preferenceKey = Preferences.wallpaperChangerApiKey,
entries = apis.map { stringResource(it.titleResource) },
values = apis.map { it.route }
var useLocalWallpapers by remember {
mutableStateOf(Preferences.getBoolean(Preferences.autoChangerLocal, false))
}
CheckboxPref(
prefKey = Preferences.autoChangerLocal,
title = stringResource(R.string.local_walls),
summary = stringResource(R.string.local_walls_summary)
) {
WorkerHelper.enqueue(context, true)
useLocalWallpapers = it
if (it) selectFiles.launch(arrayOf("image/*"))
}
Spacer(
modifier = Modifier
.height(10.dp)
)
val apis = listOf(DrawerScreens.Wallhaven, DrawerScreens.Picsum, DrawerScreens.OWalls)
AnimatedVisibility(visible = !useLocalWallpapers) {
BlockPreference(
preferenceKey = Preferences.wallpaperChangerApiKey,
entries = apis.map { stringResource(it.titleResource) },
values = apis.map { it.route }
) {
WorkerHelper.enqueue(context, true)
}
}
ListPreference(
prefKey = Preferences.wallpaperChangerIntervalKey,
Expand Down
47 changes: 32 additions & 15 deletions app/src/main/java/com/bnyro/wallpaper/util/BackgroundWorker.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.bnyro.wallpaper.util

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import androidx.work.Worker
import androidx.work.WorkerParameters
import kotlinx.coroutines.Dispatchers
Expand All @@ -11,26 +13,41 @@ class BackgroundWorker(
workerParameters: WorkerParameters
) : Worker(applicationContext, workerParameters) {
override fun doWork(): Result {
var success = true
runBlocking(Dispatchers.IO) {
val bitmap = if (Preferences.getBoolean(Preferences.autoChangerLocal, false)) {
getLocalWallpaper()
} else {
getOnlineWallpaper()
} ?: return Result.failure()

WallpaperHelper.setWallpaper(
applicationContext,
BitmapProcessor.processBitmapByPrefs(bitmap),
Preferences.getString(
Preferences.wallpaperChangerTargetKey,
Preferences.defaultWallpaperChangerTarget.toString()
)?.toInt() ?: Preferences.defaultWallpaperChangerTarget
)

return Result.success()
}

private fun getOnlineWallpaper(): Bitmap? {
return runBlocking(Dispatchers.IO) {
val url = try {
Preferences.getWallpaperChangerApi().getRandomWallpaperUrl()
} catch (e: Exception) {
success = false
return@runBlocking
return@runBlocking null
}

ImageHelper.getBlocking(applicationContext, url, true)?.let {
WallpaperHelper.setWallpaper(
applicationContext,
BitmapProcessor.processBitmapByPrefs(it),
Preferences.getString(
Preferences.wallpaperChangerTargetKey,
Preferences.defaultWallpaperChangerTarget.toString()
)?.toInt() ?: Preferences.defaultWallpaperChangerTarget
)
}
return@runBlocking ImageHelper.getBlocking(applicationContext, url, true)
}
return if (success) Result.success() else Result.retry()
}

private fun getLocalWallpaper(): Bitmap? {
return runCatching {
val wallpaperDir = applicationContext.filesDir
val randomFile = wallpaperDir.listFiles().orEmpty().toList().shuffled().firstOrNull() ?: return null
ImageHelper.getLocalImage(applicationContext, Uri.fromFile(randomFile))
}.getOrNull()
}
}
9 changes: 9 additions & 0 deletions app/src/main/java/com/bnyro/wallpaper/util/ImageHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package com.bnyro.wallpaper.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.core.graphics.drawable.toBitmap
import coil.ImageLoader
import coil.annotation.ExperimentalCoilApi
Expand Down Expand Up @@ -45,4 +47,11 @@ object ImageHelper {
.data(url)
.allowHardware(false)
}

fun getLocalImage(context: Context, imagePath: Uri): Bitmap? {
context.contentResolver.openInputStream(imagePath)?.use {
return BitmapFactory.decodeStream(it)
}
return null
}
}
1 change: 1 addition & 0 deletions app/src/main/java/com/bnyro/wallpaper/util/Preferences.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ object Preferences {
const val autoAddToFavoritesKey = "autoAddToFavorites"
const val grayscaleKey = "grayscale"
const val blurKey = "blur"
const val autoChangerLocal = "autoChangerLocal"

const val defaultDiskCacheSize = 128L * 1024 * 1024
const val defaultWallpaperChangeInterval = 15L
Expand Down
16 changes: 9 additions & 7 deletions app/src/main/java/com/bnyro/wallpaper/util/WallpaperHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,15 @@ object WallpaperHelper {
// prevent crashes due to wrong aspect ratio
if (bitmapGapX <= 0 || bitmapGapY <= 0) return resizedBitmap

return Bitmap.createBitmap(
resizedBitmap,
bitmapGapX,
bitmapGapY,
screenWidth,
screenHeight
)
return runCatching {
Bitmap.createBitmap(
resizedBitmap,
bitmapGapX,
bitmapGapY,
screenWidth,
screenHeight
)
}.getOrDefault(resizedBitmap)
}

private fun getResizedBitmap(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
Expand Down
6 changes: 4 additions & 2 deletions app/src/main/java/com/bnyro/wallpaper/util/WorkerHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ object WorkerHelper {
TimeUnit.MINUTES
).setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiredNetworkType(
if (Preferences.getBoolean(Preferences.autoChangerLocal, false)) NetworkType.NOT_REQUIRED else NetworkType.CONNECTED
)
.build()
).build()

Expand All @@ -34,7 +36,7 @@ object WorkerHelper {
.enqueueUniquePeriodicWork(JOB_NAME, policy, job)
}

fun cancel(context: Context) {
private fun cancel(context: Context) {
WorkManager.getInstance(context)
.cancelUniqueWork(JOB_NAME)
}
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
<string name="home">Home</string>
<string name="lockscreen">Lockscreen</string>
<string name="applying_random">Applying random wallpaper</string>
<string name="local_walls">Local wallpapers</string>
<string name="local_walls_summary">Use local instead of online wallpapers</string>

<!-- Image Filters -->
<string name="blur">Blur</string>
Expand Down

0 comments on commit a266652

Please sign in to comment.