Added wallpaper brightness feature and wallpaper scaling options (fill, stretch, fit)

Enable compiler strong skipping
Updated compose dependencies to 1.7.0-beta01
Added detection for live wallpaper causing wallpaper not to change
Fixed restarting service when opening the app
Fixed content scaling of wallpaper item
Fixed orientation change causing a black screen due to splash screen
Updated translations
This commit is contained in:
Anthonyy232 committed 2024-05-17 22:52:44 -07:00
1 parent 9a5b40ba7f
commit 5d9e87ff63
72 files changed
+2070 -704

No files matched your search

@@ -0,0 +1,7 @@
package com.anthonyla.paperize.core
enum class ScalingConstants {
FIT,
FILL,
STRETCH
}
@@ -12,8 +12,10 @@ object SettingsConstants {
const val WALLPAPER_CHANGE_INTERVAL_DEFAULT = 15
const val SET_LOCK_WITH_HOME = "set_lock_with_home"
const val FIRST_LAUNCH = "first_launch"
const val FIRST_ALBUM_SET = "first_album_set"
const val LAST_SET_TIME = "last_set_time"
const val NEXT_SET_TIME = "next_set_time"
const val ENABLE_CHANGER = "enable_changer"
const val DARKEN_PERCENTAGE = "darken_percentage"
const val DARKEN = "darken"
const val WALLPAPER_SCALING = "wallpaper_scaling"
}
@@ -0,0 +1,118 @@
package com.anthonyla.paperize.core
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.net.Uri
import android.util.Log
import android.util.Size
import androidx.compose.ui.util.fastRoundToInt
import androidx.exifinterface.media.ExifInterface
/**
* Get the dimensions of the image from the uri
*/
fun Uri.getImageDimensions(context: Context): Size {
val inputStream = context.contentResolver.openInputStream(this)!!
val exif = ExifInterface(inputStream)
var width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
var height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
if (width == 0 || height == 0) {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(context.contentResolver.openInputStream(this), null, options)
width = options.outWidth
height = options.outHeight
}
return Size(width, height)
}
/**
* Calculate the inSampleSize for the image
*/
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
return if (imageSize.width <= width && imageSize.height <= height) { 1 }
else { (imageSize.width/ width.toFloat()).fastRoundToInt() }
}
/**
* Scale a bitmap using the fit width method
* The bitmap will fit into the given width while maintaining the same aspect ratio
*/
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
val aspectRatio = source.height.toFloat() / source.width.toFloat()
val newHeight = (width * aspectRatio).toInt()
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
val bitmap = Bitmap.createScaledBitmap(source, width, newHeight, true)
val top = (height - newHeight) / 2f
canvas.drawBitmap(bitmap, 0f, top, null)
return newBitmap
}
/**
* Scale a bitmap using the fill height method
*/
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
try {
val aspectRatio = source.width.toFloat() / source.height.toFloat()
var newWidth = width
var newHeight = (newWidth / aspectRatio).toInt()
if (newHeight < height) {
newHeight = height
newWidth = (newHeight * aspectRatio).toInt()
}
val scaledBitmap = Bitmap.createScaledBitmap(source, newWidth, newHeight, true)
val x = (width - newWidth) / 2f
val y = (height - newHeight) / 2f
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
canvas.drawBitmap(scaledBitmap, x, y, null)
return bitmap
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error filling bitmap: $e")
return source
}
}
/**
* Stretch the bitmap to fit the given width and height
*/
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
try {
val newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(newBitmap)
val bitmap = Bitmap.createScaledBitmap(source, width, height, true)
canvas.drawBitmap(bitmap, 0f, 0f, null)
return newBitmap
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error stretching bitmap: $e")
return source
}
}
/**
* Darken the bitmap by a certain percentage - 0 is darkest, 100 is original
*/
fun darkenBitmap(source: Bitmap, percent: Int, width: Int, height: Int): Bitmap {
try {
val safePercentage = (100 - percent).coerceIn(0, 100)
val factor = 1 - safePercentage / 100f
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paint = Paint().apply {
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
setScale(factor, factor, factor, 1f)
})
}
canvas.drawBitmap(source, 0f, 0f, paint)
return bitmap
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error darkening bitmap: $e")
return source
}
}
@@ -3,6 +3,7 @@ package com.anthonyla.paperize.feature.wallpaper.presentation
import android.Manifest
import android.animation.ObjectAnimator
import android.app.Activity
import android.app.ActivityManager
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
@@ -19,16 +20,24 @@ import androidx.core.animation.doOnEnd
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.themes.PaperizeTheme
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperScreenViewModel
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val settingsViewModel: SettingsViewModel by viewModels()
@@ -52,11 +61,11 @@ class MainActivity : ComponentActivity() {
fadeOut.start()
}
}
splashScreen.setKeepOnScreenCondition { settingsViewModel.setKeepOnScreenCondition }
setContent {
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
val selectedState = wallpaperScreenViewModel.state.collectAsStateWithLifecycle()
splashScreen.setKeepOnScreenCondition { settingsState.value.isDataLoaded && selectedState.value.isDataLoaded }
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
if (isFirstLaunch) {
val contentResolver = context.contentResolver
@@ -65,11 +74,40 @@ class MainActivity : ComponentActivity() {
contentResolver.releasePersistableUriPermission(permission.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
}
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
lifecycleScope.launch {
val serviceIntent = Intent(this@MainActivity, WallpaperService::class.java)
val isAlreadyRunning = withContext(Dispatchers.IO) {5
val activityManager = getSystemService(ACTIVITY_SERVICE) as? ActivityManager
activityManager?.getRunningServices(Integer.MAX_VALUE)?.any {
it.service == serviceIntent.component
} ?: false
}
if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
if (!isAlreadyRunning) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
}
context.startForegroundService(intent)
}
} else {
if (isAlreadyRunning) {
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
}
}
}
}
PaperizeTheme(settingsState) {
Surface(tonalElevation = 5.dp) {
PaperizeApp(isFirstLaunch)
}
}
}
}
}
@@ -6,6 +6,11 @@ import android.content.pm.PackageManager
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.core.content.ContextCompat
@@ -50,9 +55,12 @@ import com.anthonyla.paperize.feature.wallpaper.util.navigation.Startup
import com.anthonyla.paperize.feature.wallpaper.util.navigation.WallpaperView
import com.anthonyla.paperize.feature.wallpaper.util.navigation.sharedXTransitionIn
import com.anthonyla.paperize.feature.wallpaper.util.navigation.sharedXTransitionOut
import com.anthonyla.paperize.feature.wallpaper.wallpaperservice.WallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.net.URLEncoder
@@ -71,6 +79,8 @@ fun PaperizeApp(
val selectedState = wallpaperScreenViewModel.state.collectAsStateWithLifecycle()
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
val context = LocalContext.current
var job by remember { mutableStateOf<Job?>(null) }
val scope = rememberCoroutineScope()
// React to albumState changes and change selectedAlbum's details to keep it from being stale
LaunchedEffect(albumState.value.albumsWithWallpapers) {
@@ -108,13 +118,6 @@ fun PaperizeApp(
)
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(newSelectedAlbum, null))
settingsViewModel.onEvent(SettingsEvent.SetWallpaperInterval(settingsState.value.interval))
if (settingsState.value.enableChanger) { // Not ideal but no other option to check if service is running (thanks Android)
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", settingsState.value.interval)
}
context.startForegroundService(intent)
}
} ?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
Intent(context, WallpaperService::class.java).also {
@@ -229,9 +232,21 @@ fun PaperizeApp(
nextSetTime = settingsState.value.nextSetTime,
onSetLockWithHome = {
settingsViewModel.onEvent(SettingsEvent.SetLockWithHome(it))
job?.cancel()
job = scope.launch {
delay(2000)
if (settingsState.value.enableChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
}
}
},
selectedAlbum = selectedState.value.selectedAlbum,
enableChanger = settingsState.value.enableChanger,
darkenPercentage = settingsState.value.darkenPercentage,
darken = settingsState.value.darken,
onToggleChanger = { enableWallpaperChanger ->
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
if (enableWallpaperChanger) {
@@ -256,6 +271,48 @@ fun PaperizeApp(
putExtra("timeInMinutes", settingsState.value.interval)
}
context.startForegroundService(intent)
},
onDarkenPercentage = {
settingsViewModel.onEvent(SettingsEvent.SetDarkenPercentage(it))
job?.cancel()
job = scope.launch {
delay(2000)
if (settingsState.value.enableChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
}
}
},
onDarkCheck = {
settingsViewModel.onEvent(SettingsEvent.SetDarken(it))
job?.cancel()
job = scope.launch {
delay(2000)
if (settingsState.value.enableChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
}
}
},
scaling = settingsState.value.wallpaperScaling,
onScalingChange = {
if (settingsState.value.wallpaperScaling != it) {
settingsViewModel.onEvent(SettingsEvent.SetWallpaperScaling(it))
job?.cancel()
job = scope.launch {
delay(2000)
if (settingsState.value.enableChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.UPDATE.toString()
}
context.startForegroundService(intent)
}
}
}
}
)
}
@@ -284,7 +341,7 @@ fun PaperizeApp(
},
onShowFolderView = { folderName, wallpapers ->
/*navController.navigate(
com.anthonyla.paperize.feature.wallpaper.util.navigation.FolderView(
FolderView(
folderName,
wallpapers
)
@@ -24,8 +24,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -72,12 +70,6 @@ fun AlbumItem(
contentScale = ContentScale.Crop,
alignment = Alignment.Center
),
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.transition(BitmapTransitionOptions.withCrossFade())
},
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
@@ -43,8 +43,6 @@ import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -124,12 +122,6 @@ fun FolderItem(
contentScale = ContentScale.Crop,
alignment = Alignment.Center
),
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.transition(BitmapTransitionOptions.withCrossFade())
},
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
@@ -1,9 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.ExperimentalFoundationApi
@@ -27,7 +24,9 @@ import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
@@ -35,10 +34,11 @@ import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.exifinterface.media.ExifInterface
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.getImageDimensions
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.bumptech.glide.load.DecodeFormat
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -55,10 +55,12 @@ fun WallpaperItem(
onItemSelection: () -> Unit,
onWallpaperViewClick: () -> Unit,
modifier: Modifier = Modifier,
wallpaperDrawable : Bitmap? = null,
aspectRatio: Float? = null,
clickable: Boolean = true,
animate: Boolean = true
animate: Boolean = true,
darken: Boolean = false,
darkenPercentage: Int? = null,
scaling: ScalingConstants? = null
) {
val context = LocalContext.current
val haptics = LocalHapticFeedback.current
@@ -89,8 +91,11 @@ fun WallpaperItem(
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.combinedClickable(
onClick = {
if (!selectionMode) { onWallpaperViewClick() }
else { onItemSelection() }
if (!selectionMode) {
onWallpaperViewClick()
} else {
onItemSelection()
}
},
onLongClick = {
if (!selectionMode) {
@@ -107,20 +112,26 @@ fun WallpaperItem(
}
Box(modifier = boxModifier) {
if (showUri) {
val dimension = wallpaperDrawable?.let { Pair(it.width, it.height) } ?: wallpaperUri.toUri().getImageDimensions(context)
val imageAspectRatio = aspectRatio ?: (dimension.first.toFloat() / dimension.second.toFloat())
val dimension = wallpaperUri.toUri().getImageDimensions(context)
val imageAspectRatio = aspectRatio ?: (dimension.width.toFloat() / dimension.height.toFloat())
GlideImage(
imageModel = { wallpaperDrawable ?: wallpaperUri.toUri() },
imageModel = { wallpaperUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center
contentScale = if (scaling != null) {
when (scaling) {
ScalingConstants.FILL -> ContentScale.FillHeight
ScalingConstants.FIT -> ContentScale.FillWidth
ScalingConstants.STRETCH -> ContentScale.FillBounds
}
} else { ContentScale.Crop },
alignment = Alignment.Center,
colorFilter = if (darken && darkenPercentage != null && darkenPercentage < 100) {
ColorFilter.tint(
Color.Black.copy(alpha = (100 - darkenPercentage).toFloat().div(100f)),
BlendMode.Darken
)
} else { null }
),
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.transition(BitmapTransitionOptions.withCrossFade())
},
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
@@ -128,7 +139,13 @@ fun WallpaperItem(
}
}
},
modifier = Modifier.aspectRatio(imageAspectRatio)
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.format(DecodeFormat.PREFER_RGB_565)
},
modifier = Modifier.aspectRatio(imageAspectRatio).background(if (scaling != null) Color.Black else Color.Transparent),
)
}
if (selectionMode) {
@@ -153,23 +170,4 @@ fun WallpaperItem(
}
}
}
}
fun Uri.getImageDimensions(context: Context): Pair<Int, Int> {
val inputStream = context.contentResolver.openInputStream(this)!!
val exif = ExifInterface(inputStream)
var width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
var height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
if (width == 0 || height == 0) {
val options = BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
BitmapFactory.decodeStream(context.contentResolver.openInputStream(this), null, options)
width = options.outWidth
height = options.outHeight
}
return Pair(width, height)
}
@@ -22,6 +22,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumDialog
@@ -46,7 +47,13 @@ fun HomeScreen(
lastSetTime: String?,
nextSetTime: String?,
selectedAlbum: SelectedAlbum?,
enableChanger: Boolean
enableChanger: Boolean,
darkenPercentage: Int,
onDarkenPercentage: (Int) -> Unit,
darken: Boolean,
onDarkCheck: (Boolean) -> Unit,
scaling: ScalingConstants,
onScalingChange: (ScalingConstants) -> Unit
) {
var tabIndex by rememberSaveable { mutableIntStateOf(0) }
val tabItems = getTabItems()
@@ -132,7 +139,13 @@ fun HomeScreen(
selectedAlbum = selectedAlbum,
enableChanger = enableChanger,
onToggleChanger = onToggleChanger,
onSelectAlbum = onSelectAlbum
onSelectAlbum = onSelectAlbum,
darkenPercentage = darkenPercentage,
onDarkenPercentage = onDarkenPercentage,
darken = darken,
onDarkCheck = onDarkCheck,
scaling = scaling,
onScalingChange = onScalingChange
)
1 -> LibraryScreen(
onAddNewAlbumClick = { addAlbumDialog = true },
@@ -1,5 +1,7 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen
import com.anthonyla.paperize.core.ScalingConstants
sealed class SettingsEvent {
data object Refresh: SettingsEvent()
@@ -8,7 +10,10 @@ sealed class SettingsEvent {
data class SetDarkMode(val darkMode: Boolean?): SettingsEvent()
data class SetDynamicTheming(val dynamicTheming: Boolean): SettingsEvent()
data class SetAnimate(val animate: Boolean): SettingsEvent()
data class SetDarken(val darken: Boolean): SettingsEvent()
data class SetWallpaperInterval(val interval: Int): SettingsEvent()
data class SetDarkenPercentage(val darkenPercentage: Int): SettingsEvent()
data class SetLockWithHome(val lockWithHome: Boolean): SettingsEvent()
data class SetChangerToggle(val toggle: Boolean): SettingsEvent()
data class SetWallpaperScaling(val scaling: ScalingConstants): SettingsEvent()
}
@@ -1,8 +1,8 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
data class SettingsState (
val isDataLoaded: Boolean = false,
data class SettingsState(
val firstLaunch: Boolean = true,
val darkMode: Boolean? = null,
val dynamicTheming: Boolean = false,
@@ -11,5 +11,8 @@ data class SettingsState (
val setLockWithHome: Boolean = false,
val lastSetTime: String? = null,
val nextSetTime: String? = null,
val enableChanger: Boolean = false
val enableChanger: Boolean = false,
val darkenPercentage: Int = 100,
val darken: Boolean = false,
val wallpaperScaling: ScalingConstants = ScalingConstants.FILL
)
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import dagger.hilt.android.lifecycle.HiltViewModel
@@ -29,6 +30,7 @@ class SettingsViewModel @Inject constructor (
)
private var currentGetJob: Job? = null
var setKeepOnScreenCondition: Boolean = true
init {
currentGetJob = viewModelScope.launch(Dispatchers.IO) {
@@ -41,6 +43,9 @@ class SettingsViewModel @Inject constructor (
val nextSetTime = async { settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME) }
val animate = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ANIMATE_TYPE) ?: true }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false }
val darkenPercentage = async { settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100 }
val darken = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false }
val wallpaperScaling = async { ScalingConstants.valueOf(settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING) ?: ScalingConstants.FILL.name) }
_state.update {
it.copy(
@@ -53,9 +58,12 @@ class SettingsViewModel @Inject constructor (
nextSetTime = nextSetTime.await(),
animate = animate.await(),
enableChanger = enableChanger.await(),
isDataLoaded = true
darkenPercentage = darkenPercentage.await(),
darken = darken.await(),
wallpaperScaling = wallpaperScaling.await(),
)
}
setKeepOnScreenCondition = false
}
}
@@ -97,6 +105,8 @@ class SettingsViewModel @Inject constructor (
val nextSetTime = async { settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME) }
val animate = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ANIMATE_TYPE) ?: true }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false }
val darkenPercentage = async { settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 0 }
val darken = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false }
_state.update {
it.copy(
@@ -108,7 +118,9 @@ class SettingsViewModel @Inject constructor (
lastSetTime = lastSetTime.await(),
nextSetTime = nextSetTime.await(),
animate = animate.await(),
enableChanger = enableChanger.await()
enableChanger = enableChanger.await(),
darkenPercentage = darkenPercentage.await(),
darken = darken.await()
)
}
}
@@ -176,6 +188,31 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.SetDarkenPercentage -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putInt(SettingsConstants.DARKEN_PERCENTAGE, event.darkenPercentage)
_state.update {
it.copy(
darkenPercentage = event.darkenPercentage
)
}
}
}
is SettingsEvent.SetDarken -> {
viewModelScope.launch(Dispatchers.IO) {
when (event.darken) {
true -> { settingsDataStoreImpl.putBoolean(SettingsConstants.DARKEN, true) }
false -> { settingsDataStoreImpl.putBoolean(SettingsConstants.DARKEN, false) }
}
_state.update {
it.copy(
darken = event.darken
)
}
}
}
is SettingsEvent.SetLockWithHome -> {
viewModelScope.launch(Dispatchers.IO) {
when (event.lockWithHome) {
@@ -190,6 +227,17 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.SetWallpaperScaling -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putString(SettingsConstants.WALLPAPER_SCALING, event.scaling.name)
_state.update {
it.copy(
wallpaperScaling = event.scaling
)
}
}
}
is SettingsEvent.Reset -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.deleteBoolean(SettingsConstants.DARK_MODE_TYPE)
@@ -201,6 +249,10 @@ class SettingsViewModel @Inject constructor (
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ANIMATE_TYPE)
settingsDataStoreImpl.deleteInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ENABLE_CHANGER)
settingsDataStoreImpl.deleteInt(SettingsConstants.DARKEN_PERCENTAGE)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.DARKEN)
settingsDataStoreImpl.deleteString(SettingsConstants.WALLPAPER_SCALING)
_state.update {
it.copy(
darkMode = null,
@@ -211,7 +263,10 @@ class SettingsViewModel @Inject constructor (
lastSetTime = null,
nextSetTime = null,
animate = true,
enableChanger = false
enableChanger = false,
darkenPercentage = 100,
darken = false,
wallpaperScaling = ScalingConstants.FILL
)
}
}
@@ -53,7 +53,8 @@ fun DarkModeListItem(darkMode: Boolean?, onDarkModeClick: (Boolean?) -> Unit) {
false -> 2
else -> 1
}
) }
)
}
Row(
modifier = Modifier.fillMaxSize()
) {
@@ -1,5 +1,7 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen
import android.app.WallpaperManager
import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
@@ -27,14 +29,18 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.AlbumBottomSheet
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.CurrentAndNextChange
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.CurrentSelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.DarkenSwitchAndSlider
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.SetLockScreenSwitch
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.ShowLiveWallpaperEnabledDialog
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.TimeSliders
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.WallpaperScalingRow
import kotlinx.coroutines.launch
@Composable
@@ -51,13 +57,27 @@ fun WallpaperScreen(
lastSetTime: String?,
nextSetTime: String?,
selectedAlbum: SelectedAlbum?,
enableChanger: Boolean
enableChanger: Boolean,
darkenPercentage: Int,
onDarkenPercentage: (Int) -> Unit,
darken: Boolean,
onDarkCheck: (Boolean) -> Unit,
scaling: ScalingConstants,
onScalingChange: (ScalingConstants) -> Unit
) {
val context = LocalContext.current
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val context = LocalContext.current
val openDialog = rememberSaveable { mutableStateOf(false) }
val showInterval = rememberSaveable { mutableStateOf(false) }
if (openDialog.value) {
ShowLiveWallpaperEnabledDialog(
onDismissRequest = { openDialog.value = false }
)
}
Scaffold(
snackbarHost = {
@@ -83,7 +103,22 @@ fun WallpaperScreen(
CurrentSelectedAlbum(
selectedAlbum = selectedAlbum,
onOpenBottomSheet = {
if (albumState.value.albumsWithWallpapers.firstOrNull() != null) openBottomSheet = true
if (albumState.value.albumsWithWallpapers.firstOrNull() != null) {
if (isLiveWallpaperSet(context)) {
openDialog.value = true
}
else { openBottomSheet = true }
}
else {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = context.getString(R.string.no_albums_found),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
}
},
onStop = {
if (selectedAlbum != null) {
@@ -145,7 +180,10 @@ fun WallpaperScreen(
albumUri = selectedAlbum.album.currentWallpaper,
checked = setLockWithHome,
onCheckedChange = { onSetLockWithHome(it) },
animate = true
animate = true,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling
)
}
}
@@ -156,7 +194,32 @@ fun WallpaperScreen(
albumUri = selectedAlbum.album.currentWallpaper,
checked = setLockWithHome,
onCheckedChange = { onSetLockWithHome(it) },
animate = false
animate = false,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling
)
}
}
}
item {
if (animate) {
AnimatedVisibility(
visible = selectedAlbum != null,
enter = slideInVertically(initialOffsetY = { -it }),
exit = fadeOut()
) {
WallpaperScalingRow(
scaling = scaling,
onScalingChange = onScalingChange
)
}
}
else {
if (selectedAlbum != null) {
WallpaperScalingRow(
scaling = scaling,
onScalingChange = onScalingChange
)
}
}
@@ -173,7 +236,10 @@ fun WallpaperScreen(
onTimeChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onScheduleWallpaperChanger(totalMinutes)
}
},
showInterval = showInterval.value,
animate = true,
onShowIntervalChange = { showInterval.value = it }
)
}
}
@@ -184,7 +250,38 @@ fun WallpaperScreen(
onTimeChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onScheduleWallpaperChanger(totalMinutes)
}
},
showInterval = showInterval.value,
animate = false,
onShowIntervalChange = { showInterval.value = it }
)
}
}
}
item {
if (animate) {
AnimatedVisibility(
visible = selectedAlbum != null,
enter = slideInVertically(initialOffsetY = { -it }),
exit = fadeOut()
) {
DarkenSwitchAndSlider(
onDarkCheck = onDarkCheck,
darken = darken,
onDarkenChange = onDarkenPercentage,
darkenPercentage = darkenPercentage,
animate = true
)
}
}
else {
if (selectedAlbum != null) {
DarkenSwitchAndSlider(
onDarkCheck = onDarkCheck,
darken = darken,
onDarkenChange = onDarkenPercentage,
darkenPercentage = darkenPercentage,
animate = false
)
}
}
@@ -205,4 +302,9 @@ fun WallpaperScreen(
}
},
)
}
fun isLiveWallpaperSet(context: Context): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
return wallpaperManager.wallpaperInfo != null
}
@@ -33,8 +33,6 @@ import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
import kotlinx.coroutines.launch
@@ -105,15 +103,9 @@ fun AlbumBottomSheet(
GlideImage(
imageModel = { it.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.FillBounds,
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
),
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.transition(BitmapTransitionOptions.withCrossFade())
},
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
@@ -24,6 +24,9 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
/**
* Contains the current and next change components that shows the last and next set time
*/
@Composable
fun CurrentAndNextChange(
lastSetTime: String?,
@@ -37,10 +40,10 @@ fun CurrentAndNextChange(
) {
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.weight(1f)
.padding(PaddingValues(16.dp, 8.dp, 8.dp, 8.dp))
.clip(RoundedCornerShape(16.dp))
) {
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -37,8 +37,6 @@ import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -100,15 +98,9 @@ fun CurrentSelectedAlbum(
GlideImage(
imageModel = { selectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.FillBounds,
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
),
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.transition(BitmapTransitionOptions.withCrossFade())
},
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
@@ -0,0 +1,154 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.shape.RoundedCornerShape
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
/**
* Composable that displays a switch and slider to adjust the brightness of the wallpaper
*/
@Composable
fun DarkenSwitchAndSlider(
onDarkCheck: (Boolean) -> Unit,
onDarkenChange: (Int) -> Unit,
darken: Boolean,
darkenPercentage: Int,
animate: Boolean
) {
val view = LocalView.current
val scope = rememberCoroutineScope()
var job by remember { mutableStateOf<Job?>(null) }
var percentage by rememberSaveable { mutableFloatStateOf(darkenPercentage.toFloat()) }
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
val columnModifier = if (animate) {
Modifier.animateContentSize(
animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing)
)
} else { Modifier }
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = columnModifier
) {
Row (horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
Text(
text = stringResource(R.string.adjust_brightness),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Switch(
checked = darken,
onCheckedChange = onDarkCheck
)
}
if (animate) {
AnimatedVisibility(
visible = darken,
enter = expandVertically(animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)),
exit = fadeOut(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
)
) {
Column {
Text(
text = stringResource(R.string.brightness_percentage, percentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W400
)
Slider(
value = percentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
percentage = it
job?.cancel()
job = scope.launch {
delay(500)
onDarkenChange(it.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Spacer(modifier = Modifier.height(16.dp))
}
}
} else {
if (darken) {
Column {
Text(
text = stringResource(R.string.brightness_percentage, percentage.roundToInt()),
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp)),
fontWeight = FontWeight.W500
)
Slider(
value = percentage,
onValueChange = {
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
percentage = it
job?.cancel()
job = scope.launch {
delay(500)
onDarkenChange(it.roundToInt())
}
},
valueRange = 0f..100f,
steps = 100,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Spacer(modifier = Modifier.height(16.dp))
}
}
}
}
}
}
@@ -0,0 +1,37 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.anthonyla.paperize.R
/**
* Dialog to show when a live wallpaper is detected and ask the user to disable it
*/
@Composable
fun ShowLiveWallpaperEnabledDialog(
onDismissRequest: () -> Unit
) {
AlertDialog(
onDismissRequest = { onDismissRequest() },
icon = { Icon(Icons.Filled.ErrorOutline, stringResource(R.string.disable_live_wallpaper)) },
title = {
Text(stringResource(R.string.live_wallpaper_detected))
},
text = {
Text(stringResource(R.string.please_disable_your_live_wallpaper_to_use_the_wallpaper_changer))
},
confirmButton = {
Button(
onClick = { onDismissRequest() }
) {
Text(stringResource(R.string.ok))
}
}
)
}
@@ -13,42 +13,54 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.shape.RoundedCornerShape
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
/**
* SetLockScreenSwitch is a composable that displays a switch to set the wallpaper as the lock screen wallpaper
* Also shows a preview of lock and home screen when enabled along with brightness added
*/
@Composable
fun SetLockScreenSwitch(
albumUri : String?,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
animate: Boolean
animate: Boolean,
darken: Boolean,
darkenPercentage: Int,
scaling: ScalingConstants?
) {
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
.clip(RoundedCornerShape(16.dp))
) {
val columnModifier = if (animate) {
Modifier.animateContentSize(
animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing)
)
} else { Modifier }
val columnModifier = remember {
if (animate) {
Modifier.animateContentSize(
animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing)
)
} else { Modifier }
}
Column (
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
@@ -94,11 +106,19 @@ fun SetLockScreenSwitch(
onWallpaperViewClick = {},
modifier = Modifier
.padding(4.dp)
.border(3.dp, color = Color.Black, shape = RoundedCornerShape(16.dp)),
.border(
3.dp,
color = Color.Black,
shape = RoundedCornerShape(16.dp)
),
aspectRatio = 9f / 19.5f,
clickable = false,
animate = true
animate = true,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling
)
Spacer(modifier = Modifier.height(8.dp))
}
}
Column(
@@ -118,11 +138,19 @@ fun SetLockScreenSwitch(
onWallpaperViewClick = {},
modifier = Modifier
.padding(4.dp)
.border(3.dp, color = Color.Black, shape = RoundedCornerShape(16.dp)),
.border(
3.dp,
color = Color.Black,
shape = RoundedCornerShape(16.dp)
),
aspectRatio = 9f / 19.5f,
clickable = false,
animate = true
animate = true,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling
)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
@@ -148,11 +176,19 @@ fun SetLockScreenSwitch(
onWallpaperViewClick = {},
modifier = Modifier
.padding(4.dp)
.border(3.dp, color = Color.Black, shape = RoundedCornerShape(16.dp)),
.border(
3.dp,
color = Color.Black,
shape = RoundedCornerShape(16.dp)
),
aspectRatio = 9f / 19.5f,
clickable = false,
animate = false
animate = false,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling
)
Spacer(modifier = Modifier.height(8.dp))
}
}
Column(
@@ -172,11 +208,19 @@ fun SetLockScreenSwitch(
onWallpaperViewClick = {},
modifier = Modifier
.padding(4.dp)
.border(3.dp, color = Color.Black, shape = RoundedCornerShape(16.dp)),
.border(
3.dp,
color = Color.Black,
shape = RoundedCornerShape(16.dp)
),
aspectRatio = 9f / 19.5f,
clickable = false,
animate = false
animate = false,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling
)
Spacer(modifier = Modifier.height(8.dp))
}
}
}
@@ -1,10 +1,28 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
@@ -16,8 +34,8 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
@@ -27,10 +45,16 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* TimeSliders is a composable that displays sliders for the user to select the time interval for changing wallpaper
*/
@Composable
fun TimeSliders(
onTimeChange: (Int, Int, Int) -> Unit,
timeInMinutes: Int
timeInMinutes: Int,
showInterval: Boolean,
animate: Boolean,
onShowIntervalChange: (Boolean) -> Unit
) {
val view = LocalView.current
var days by rememberSaveable { mutableFloatStateOf((timeInMinutes / (24 * 60)).toFloat()) }
@@ -40,14 +64,24 @@ fun TimeSliders(
val context = LocalView.current
var job by remember { mutableStateOf<Job?>(null) }
val columnModifier = remember {
if (animate) {
Modifier.animateContentSize(
animationSpec = tween(durationMillis = 300, easing = LinearOutSlowInEasing)
)
} else { Modifier }
}
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.padding(16.dp)
.clip(RoundedCornerShape(16.dp))
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Column {
Column (
modifier = columnModifier
) {
val totalMinutes = (days.toInt() * 24 * 60) + (hours.toInt() * 60) + minutes.toInt()
val displayDays = totalMinutes / (24 * 60)
val displayHours = (totalMinutes % (24 * 60)) / 60
@@ -69,71 +103,161 @@ fun TimeSliders(
listOf(formattedDays, formattedHours, formattedMinutes).filter { it.isNotEmpty() }.joinToString(", ")
)
Text(
text = formattedTime,
modifier = Modifier.padding(PaddingValues(horizontal = 24.dp, vertical = 12.dp)),
fontWeight = FontWeight.W500
)
Row (
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.width(32.dp))
Text(
text = formattedTime,
fontWeight = FontWeight.W500,
)
IconButton(
onClick = { onShowIntervalChange(!showInterval) },
) {
Icon(imageVector = Icons.Filled.ArrowDropDown, contentDescription = "Show interval sliders")
}
}
Slider(
value = days,
onValueChange = { newDays ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
days = newDays
val totalMinute = (newDays.toInt() * 24 * 60) + (hours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (hours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(newDays.toInt(), hours.toInt(), minutes.toInt())
}
},
valueRange = 0f..30f,
steps = 30,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
if (animate) {
AnimatedVisibility(
visible = showInterval,
enter = expandVertically(animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)),
exit = fadeOut(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
)
) {
Column {
Slider(
value = days,
onValueChange = { newDays ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
days = newDays
val totalMinute = (newDays.toInt() * 24 * 60) + (hours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (hours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(newDays.toInt(), hours.toInt(), minutes.toInt())
}
},
valueRange = 0f..30f,
steps = 30,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Slider(
value = hours,
onValueChange = { newHours ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
hours = newHours
val totalMinute = (days.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (newHours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(days.toInt(), newHours.toInt(), minutes.toInt())
}
},
valueRange = 0f..24f,
steps = 24,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Slider(
value = hours,
onValueChange = { newHours ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
hours = newHours
val totalMinute = (days.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (newHours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(days.toInt(), newHours.toInt(), minutes.toInt())
}
},
valueRange = 0f..24f,
steps = 24,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Slider(
value = minutes,
onValueChange = { newMinutes ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
minutes = if (days.toInt() == 0 && hours.toInt() == 0 && newMinutes < 15) {
15f
} else {
newMinutes
Slider(
value = minutes,
onValueChange = { newMinutes ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
minutes = if (days.toInt() == 0 && hours.toInt() == 0 && newMinutes < 15) {
15f
} else {
newMinutes
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(days.toInt(), hours.toInt(), minutes.toInt())
}
},
valueRange = 0f..60f,
steps = 60,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Spacer(modifier = Modifier.height(16.dp))
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(days.toInt(), hours.toInt(), minutes.toInt())
}
},
valueRange = 0f..60f,
steps = 60,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
}
}
else {
if (showInterval) {
Slider(
value = days,
onValueChange = { newDays ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
days = newDays
val totalMinute = (newDays.toInt() * 24 * 60) + (hours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (hours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(newDays.toInt(), hours.toInt(), minutes.toInt())
}
},
valueRange = 0f..30f,
steps = 30,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Slider(
value = hours,
onValueChange = { newHours ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
hours = newHours
val totalMinute = (days.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (newHours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(days.toInt(), newHours.toInt(), minutes.toInt())
}
},
valueRange = 0f..24f,
steps = 24,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
Slider(
value = minutes,
onValueChange = { newMinutes ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
minutes = if (days.toInt() == 0 && hours.toInt() == 0 && newMinutes < 15) {
15f
} else {
newMinutes
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange(days.toInt(), hours.toInt(), minutes.toInt())
}
},
valueRange = 0f..60f,
steps = 60,
modifier = Modifier.padding(PaddingValues(horizontal = 30.dp))
)
}
}
}
}
@@ -0,0 +1,117 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
/**
* Row for selecting the scaling of the wallpaper
*/
@Composable
fun WallpaperScalingRow(
scaling: ScalingConstants,
onScalingChange: (ScalingConstants) -> Unit
) {
var selectedIndex by rememberSaveable {
mutableIntStateOf(
when (scaling) {
ScalingConstants.FILL -> 0
ScalingConstants.FIT -> 1
ScalingConstants.STRETCH -> 2
}
)
}
val options = listOf(
stringResource(R.string.fill),
stringResource(R.string.fit),
stringResource(R.string.stretch)
)
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Column {
Row (
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(top = 16.dp, bottom = 4.dp)),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Text(
text = stringResource(R.string.wallpaper_scaling),
fontWeight = FontWeight.W500
)
}
SingleChoiceSegmentedButtonRow (
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 16.dp))
) {
options.forEachIndexed { index, label ->
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(index = index, count = options.size),
onClick = {
selectedIndex = index
onScalingChange(
when (index) {
0 -> ScalingConstants.FILL
1 -> ScalingConstants.FIT
2 -> ScalingConstants.STRETCH
else -> ScalingConstants.FILL
}
) },
selected = index == selectedIndex
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
painter = when (index) {
0 -> painterResource(id = R.drawable.fill)
1 -> painterResource(id = R.drawable.fit)
2 -> painterResource(id = R.drawable.stretch)
else -> painterResource(id = R.drawable.fill)
},
contentDescription = null,
tint = Color.Unspecified,
modifier = Modifier.size(36.dp)
)
Text(text = label)
}
}
}
}
}
}
}
@@ -29,8 +29,6 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
import net.engawapg.lib.zoomable.rememberZoomState
@@ -76,6 +74,7 @@ fun WallpaperViewScreen(
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(id = R.string.home_screen),
tint = Color.White
)
}
},
@@ -103,15 +102,9 @@ fun WallpaperViewScreen(
GlideImage(
imageModel = { wallpaperUri.toUri() },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
contentScale = ContentScale.Fit,
alignment = Alignment.Center
),
requestBuilder = {
Glide
.with(LocalContext.current)
.asBitmap()
.transition(BitmapTransitionOptions.withCrossFade())
},
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
@@ -62,6 +62,7 @@ data class WallpaperView(val wallpaper: String)
@Serializable
data class FolderView(val folderName: String?, val wallpapers: List<String>)
*/
sealed class NavScreens(val route: String) {
data object FolderView : NavScreens("folder_view_screen")
}
@@ -1,4 +1,4 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaperservice
package com.anthonyla.paperize.feature.wallpaper.wallpaper_service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -0,0 +1,414 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaper_service
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.DisplayMetrics
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.calculateInSampleSize
import com.anthonyla.paperize.core.darkenBitmap
import com.anthonyla.paperize.core.fillBitmap
import com.anthonyla.paperize.core.fitBitmap
import com.anthonyla.paperize.core.getImageDimensions
import com.anthonyla.paperize.core.stretchBitmap
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.io.IOException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
import kotlin.math.min
@AndroidEntryPoint
class WallpaperService: Service() {
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private val handler = Handler(Looper.getMainLooper())
private lateinit var runnableCode: Runnable
private var timeInMinutes: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
enum class Actions {
START,
STOP,
UPDATE,
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
/**
* Set up the runnable code to change the wallpaper to prevent runnableCode from being null
*/
override fun onCreate() {
super.onCreate()
startForeground(1, createNotification(0, 0))
runnableCode = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
changeWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler.postDelayed(self, timeInMinutes * 60 * 1000L)
}
}
}
}
}
/**
* Start the service and schedule the wallpaper change
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
handler.removeCallbacks(runnableCode)
when(intent?.action) {
Actions.START.toString() -> {
timeInMinutes = intent.getIntExtra("timeInMinutes", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
// Schedule the next wallpaper change
runnableCode = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
changeWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler.postDelayed(self, timeInMinutes * 60 * 1000L)
}
}
}
}
handler.postDelayed(runnableCode, 3000)
}
Actions.UPDATE.toString() -> {
CoroutineScope(Dispatchers.IO).launch {
try {
updateCurrentWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing brightness", e)
}
}
}
Actions.STOP.toString() -> {
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, "")
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, "")
}
stopSelf()
}
}
return START_STICKY
}
/**
* Clean up the service when it is destroyed
*/
override fun onDestroy() {
super.onDestroy()
handler.removeCallbacks(runnableCode)
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, "")
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, "")
}
}
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(current: Int = 0, total: Int = 0): Notification {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(resources.getQuantityString(R.plurals.notification_content_text, total, current, total, formatTime(timeInMinutes)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
/**
* Changes the wallpaper to the next wallpaper in the queue of the selected album
* If none left, reshuffle the wallpapers and pick the first one
*/
private suspend fun changeWallpaper(context: Context) {
try {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val time = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, time.format(formatter))
settingsDataStoreImpl.putString(
SettingsConstants.NEXT_SET_TIME,
time.plusMinutes(timeInMinutes.toLong()).format(formatter)
)
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)
?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val setLockWithHome =
settingsDataStoreImpl.getBoolean(SettingsConstants.SET_LOCK_WITH_HOME) ?: false
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage =
settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
selectedAlbum.let { it ->
var wallpaper = it.album.wallpapersInQueue.firstOrNull()
if (wallpaper != null) {
val notification =
createNotification(it.album.wallpapersInQueue.size, it.wallpapers.size)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
if (!setWallpaper(
context,
wallpaper.toUri(),
setLockWithHome,
darken,
darkenPercentage,
scaling
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(
1
),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = wallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val notification =
createNotification(it.wallpapers.size, it.wallpapers.size)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context,
wallpaper.toUri(),
setLockWithHome,
darken,
darkenPercentage,
scaling
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(
1
),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = newWallpaperInQueue.drop(1),
currentWallpaper = wallpaper
)
)
)
}
} else {
onDestroy()
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
}
}
private suspend fun updateCurrentWallpaper(context: Context) {
try {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val time = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, time.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, time.plusMinutes(timeInMinutes.toLong()).format(formatter))
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val setLockWithHome = settingsDataStoreImpl.getBoolean(SettingsConstants.SET_LOCK_WITH_HOME) ?: false
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
selectedAlbum.let { it ->
val wallpaper = it.album.currentWallpaper
if (wallpaper != null) {
val notification = createNotification(it.album.wallpapersInQueue.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
if (!setWallpaper(context, wallpaper.toUri(), setLockWithHome, darken, darkenPercentage, scaling)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in updating", e)
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(context: Context, wallpaper: Uri, setLockWithHome: Boolean, darken: Boolean, percent: Int, scaling: ScalingConstants): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val imageSize = wallpaper.getImageDimensions(context)
val aspectRatio = imageSize.height.toFloat() / imageSize.width.toFloat()
val device = context.resources.displayMetrics
val targetWidth = min(4 * device.widthPixels, imageSize.width)
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSize(targetWidth, targetHeight)
}
} else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
if (bitmap == null) return false
else {
processBitmap(device, bitmap, darken, percent, scaling)?.let {
image -> wallpaperManager.setBitmap(image, null, true, when (setLockWithHome) {
true -> WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM
false -> WallpaperManager.FLAG_SYSTEM
})
}
return true
}
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e)
return false
}
}
/**
* Formats the time in minutes to a human readable format
*/
private fun formatTime(timeInMinutes: Int): String {
val days = timeInMinutes / (24 * 60)
val hours = (timeInMinutes % (24 * 60)) / 60
val minutes = timeInMinutes % 60
val formattedDays = if (days > 0) resources.getQuantityString(R.plurals.days, days, days) else ""
val formattedHours = if (hours > 0) resources.getQuantityString(R.plurals.hours, hours, hours) else ""
val formattedMinutes = if (minutes > 0) resources.getQuantityString(R.plurals.minutes, minutes, minutes) else ""
return listOf(formattedDays, formattedHours, formattedMinutes).filter { it.isNotEmpty() }.joinToString(", ")
}
/**
* Darkens the bitmap by the given percentage and returns it
* 0 - lightest, 100 - darkest
*/
private fun processBitmap(device: DisplayMetrics, source: Bitmap, darken: Boolean, percent: Int, scaling: ScalingConstants): Bitmap? {
try {
var processedBitmap = source.copy(Bitmap.Config.ARGB_8888, true)
// Apply wallpaper scaling effects
processedBitmap = when (scaling) {
ScalingConstants.FILL -> fillBitmap(processedBitmap, device.widthPixels, device.heightPixels)
ScalingConstants.FIT -> fitBitmap(processedBitmap, device.widthPixels, device.heightPixels)
ScalingConstants.STRETCH -> stretchBitmap(processedBitmap, device.widthPixels, device.heightPixels)
}
// Apply brightness effect
if (darken && percent < 100) {
processedBitmap = darkenBitmap(processedBitmap, percent, device.widthPixels, device.heightPixels)
}
return processedBitmap
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error darkening bitmap", e)
return null
}
}
}
@@ -1,271 +0,0 @@
package com.anthonyla.paperize.feature.wallpaper.wallpaperservice
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.io.IOException
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import javax.inject.Inject
@AndroidEntryPoint
class WallpaperService: Service() {
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private val handler = Handler(Looper.getMainLooper())
private lateinit var runnableCode: Runnable
private var timeInMinutes: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
enum class Actions {
START,
STOP
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
/**
* Set up the runnable code to change the wallpaper to prevent runnableCode from being null
*/
override fun onCreate() {
super.onCreate()
startForeground(1, createNotification(0, 0))
runnableCode = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
changeWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler.postDelayed(self, timeInMinutes * 60 * 1000L)
}
}
}
}
}
/**
* Start the service and schedule the wallpaper change
*/
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
handler.removeCallbacks(runnableCode)
when(intent?.action) {
Actions.START.toString() -> {
timeInMinutes = intent.getIntExtra("timeInMinutes", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
// Schedule the next wallpaper change
runnableCode = object : Runnable {
override fun run() {
val self = this
CoroutineScope(Dispatchers.IO).launch {
try {
changeWallpaper(this@WallpaperService)
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in runnableCode", e)
} finally {
handler.postDelayed(self, timeInMinutes * 60 * 1000L)
}
}
}
}
handler.postDelayed(runnableCode, 3000)
}
Actions.STOP.toString() -> {
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, "")
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, "")
}
stopSelf()
}
}
return START_STICKY
}
/**
* Clean up the service when it is destroyed
*/
override fun onDestroy() {
super.onDestroy()
handler.removeCallbacks(runnableCode)
CoroutineScope(Dispatchers.IO).launch {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, "")
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, "")
}
}
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(current: Int = 0, total: Int = 0): Notification {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(resources.getQuantityString(R.plurals.notification_content_text, total, current, total, formatTime(timeInMinutes)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
/**
* Changes the wallpaper to the next wallpaper in the queue of the selected album
* If none left, reshuffle the wallpapers and pick the first one
*/
private suspend fun changeWallpaper(context: Context) {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val time = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, time.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, time.plusMinutes(timeInMinutes.toLong()).format(formatter))
val setLockWithHome = settingsDataStoreImpl.getBoolean(SettingsConstants.SET_LOCK_WITH_HOME) ?: false
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
selectedAlbum.let { it ->
var wallpaper = it.album.wallpapersInQueue.firstOrNull()
// Pick the next wallpaper in the queue
if (wallpaper != null) {
val notification = createNotification(it.album.wallpapersInQueue.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
if (!setWallpaper(context, wallpaper.toUri(), setLockWithHome)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = wallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val notification = createNotification(it.wallpapers.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(context, wallpaper.toUri(), setLockWithHome)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = newWallpaperInQueue.drop(1),
currentWallpaper = wallpaper
)
)
)
}
} else { onDestroy() }
}
}
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(context: Context, wallpaper: Uri, setLockWithHome: Boolean): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
val displayMetrics = context.resources.displayMetrics
val targetWidth = displayMetrics.widthPixels
val targetHeight = displayMetrics.heightPixels
decoder.setTargetSize(targetWidth, targetHeight)
}
} else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
BitmapFactory.decodeStream(inputStream)
}
}
bitmap?.let {
image -> wallpaperManager.setBitmap(image, null, true, when (setLockWithHome) {
true -> WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM
false -> WallpaperManager.FLAG_SYSTEM
})
}
return true
} catch (e: IOException) { return false }
}
/**
* Formats the time in minutes to a human readable format
*/
private fun formatTime(timeInMinutes: Int): String {
val days = timeInMinutes / (24 * 60)
val hours = (timeInMinutes % (24 * 60)) / 60
val minutes = timeInMinutes % 60
val formattedDays = if (days > 0) resources.getQuantityString(R.plurals.days, days, days) else ""
val formattedHours = if (hours > 0) resources.getQuantityString(R.plurals.hours, hours, hours) else ""
val formattedMinutes = if (minutes > 0) resources.getQuantityString(R.plurals.minutes, minutes, minutes) else ""
return listOf(formattedDays, formattedHours, formattedMinutes).filter { it.isNotEmpty() }.joinToString(", ")
}
}