Baseline code refactor for home/lock separate album functionality

Added F-Droid Link
This commit is contained in:
Anthonyy232 committed 2024-08-05 21:44:27 -07:00
1 parent e0bc6ccb22
commit 65972a9ae6
31 files changed
+1297 -1472

No files matched your search

+2 -2
View File
@@ -33,8 +33,8 @@
android:theme="@android:style/Theme.NoDisplay">
</activity>
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver" />
<service android:name=".feature.wallpaper.wallpaper_service.WallpaperService1"/>
<service android:name=".feature.wallpaper.wallpaper_service.WallpaperService2"/>
<service android:name=".feature.wallpaper.wallpaper_service.HomeWallpaperService"/>
<service android:name=".feature.wallpaper.wallpaper_service.LockWallpaperService"/>
<service
android:name=".feature.wallpaper.wallpaper_tile.ChangeWallpaperTileService"
android:exported="true"
@@ -10,8 +10,12 @@ object SettingsConstants {
const val DYNAMIC_THEME_TYPE = "dynamic_theme_type"
const val ANIMATE_TYPE = "animate_type"
const val ENABLE_CHANGER = "enable_changer"
const val HOME_WALLPAPER = "home_wallpaper"
const val LOCK_WALLPAPER = "lock_wallpaper"
const val ENABLE_HOME_WALLPAPER = "home_wallpaper"
const val ENABLE_LOCK_WALLPAPER = "lock_wallpaper"
const val CURRENT_HOME_WALLPAPER = "current_home_wallpaper"
const val CURRENT_LOCK_WALLPAPER = "current_lock_wallpaper"
const val HOME_ALBUM_NAME = "home_album_name"
const val LOCK_ALBUM_NAME = "lock_album_name"
const val HOME_WALLPAPER_CHANGE_INTERVAL = "home_wallpaper_change_interval"
const val LOCK_WALLPAPER_CHANGE_INTERVAL = "lock_wallpaper_change_interval"
const val WALLPAPER_CHANGE_INTERVAL_DEFAULT = 15
@@ -19,7 +19,7 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.google.android.renderscript.Toolkit
import com.lazygeniouz.dfc.file.DocumentFileCompat
enum class Type { HOME, LOCK, BOTH, REFRESH }
enum class Type { HOME, LOCK, SINGLE, REFRESH }
/**
* Get the dimensions of the image from the uri
@@ -6,7 +6,6 @@ import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
@@ -31,13 +30,13 @@ interface SelectedAlbumDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
@Delete
suspend fun deleteAlbum(album: Album)
@Query("DELETE FROM album WHERE initialAlbumName = :initialAlbumName")
suspend fun deleteAlbum(initialAlbumName: String)
@Delete
suspend fun deleteWallpaper(wallpaper: Wallpaper)
@Query("DELETE FROM wallpaper WHERE initialAlbumName=:initialAlbumName")
@Query("DELETE FROM wallpaper WHERE initialAlbumName = :initialAlbumName")
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
@Query("DELETE FROM album")
@@ -46,12 +45,15 @@ interface SelectedAlbumDao {
@Query("DELETE FROM wallpaper")
suspend fun deleteAllWallpapers()
@Update
suspend fun updateAlbum(album: Album)
@Transaction
suspend fun deleteAll() {
deleteAllAlbums()
deleteAllWallpapers()
}
@Transaction
suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
upsertAlbum(selectedAlbum.album)
upsertWallpaperList(selectedAlbum.wallpapers)
}
}
@@ -1,7 +1,6 @@
package com.anthonyla.paperize.feature.wallpaper.data.repository
import com.anthonyla.paperize.feature.wallpaper.data.data_source.SelectedAlbumDao
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
@@ -15,38 +14,22 @@ class SelectedAlbumRepositoryImpl(
}
override suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum) {
dao.deleteAll()
dao.upsertAlbum(selectedAlbum.album)
dao.upsertWallpaperList(selectedAlbum.wallpapers)
dao.upsertSelectedAlbum(selectedAlbum)
}
override suspend fun upsertAlbum(album: Album) {
dao.upsertAlbum(album)
}
override suspend fun upsertWallpaper(wallpaper: Wallpaper) {
dao.upsertWallpaper(wallpaper)
}
override suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>) {
dao.upsertWallpaperList(wallpapers)
}
override suspend fun updateAlbum(album: Album) {
dao.updateAlbum(album)
}
override suspend fun deleteAlbum(album: Album) {
dao.deleteAlbum(album)
override suspend fun deleteAlbum(initialAlbumName: String) {
dao.deleteAlbum(initialAlbumName)
}
override suspend fun deleteWallpaper(wallpaper: Wallpaper) {
dao.deleteWallpaper(wallpaper)
}
override suspend fun cascadeDeleteWallpaper(initialAlbumName: String) {
override suspend fun cascadeDeleteAlbum(initialAlbumName: String) {
dao.deleteAlbum(initialAlbumName)
dao.cascadeDeleteWallpaper(initialAlbumName)
}
override suspend fun deleteAll() {
dao.deleteAll()
}
@@ -10,10 +10,7 @@ import androidx.room.PrimaryKey
* @param displayedAlbumName The displayed album name
* @param coverUri The cover uri of the album
* @param initialized Whether the album has been initialized
* @param homeWallpapersInQueue The wallpapers in the queue to be displayed for the home screen or when the user schedules both lock and home together
* @param lockWallpapersInQueue The wallpapers in the queue to be displayed for the lock screen when scheduled separately
* @param currentHomeWallpaper The current wallpaper for the home screen
* @param currentLockWallpaper The current wallpaper for the lock screen
* @param wallpapersInQueue The wallpapers in the queue
*/
@Entity
data class Album(
@@ -21,8 +18,5 @@ data class Album(
val displayedAlbumName: String,
val coverUri: String?,
val initialized: Boolean = false,
val homeWallpapersInQueue: List<String> = emptyList(),
val lockWallpapersInQueue: List<String> = emptyList(),
val currentHomeWallpaper: String? = null,
val currentLockWallpaper: String? = null
val wallpapersInQueue: List<String> = emptyList(),
)
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.domain.repository
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import kotlinx.coroutines.flow.Flow
@@ -16,31 +15,10 @@ interface SelectedAlbumRepository {
*/
suspend fun upsertSelectedAlbum(selectedAlbum: SelectedAlbum)
/**
* Upsert or insert album to database
*/
suspend fun upsertAlbum(album: Album)
/**
* Upsert or insert wallpaper to database
*/
suspend fun updateAlbum(album: Album)
/**
* Delete album from database
*/
suspend fun deleteAlbum(album: Album)
/**
* Upsert or insert wallpaper to database
*/
suspend fun upsertWallpaper(wallpaper: Wallpaper)
/**
* Upsert or insert list of wallpapers to database
*/
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
suspend fun deleteAlbum(initialAlbumName: String)
/**
* Delete wallpaper from database
@@ -48,9 +26,9 @@ interface SelectedAlbumRepository {
suspend fun deleteWallpaper(wallpaper: Wallpaper)
/**
* Delete all wallpapers and folders from database
* Cascade delete album and its wallpaper and folder. Proper way to delete an AlbumWithWallpaperAndFolder
*/
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
suspend fun cascadeDeleteAlbum(initialAlbumName: String)
/**
* Delete all data from database
@@ -41,8 +41,8 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.themes.PaperizeThem
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperScreenViewModel
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmSchedulerImpl
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@@ -86,7 +86,7 @@ class MainActivity : ComponentActivity() {
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
if (isFirstLaunch) {
scheduler.cancelWallpaperAlarm()
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
settingsViewModel.onEvent(SettingsEvent.Reset)
albumsViewModel.onEvent(AlbumsEvent.Reset)
val contentResolver = context.contentResolver
@@ -98,20 +98,27 @@ class MainActivity : ComponentActivity() {
LifecycleEventEffect(Lifecycle.Event.ON_CREATE) {
lifecycleScope.launch {
if (settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) == true) {
val shouldScheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val shouldScheduleAlarm = if (shouldScheduleSeparately) {
!(isPendingIntentSet(Type.HOME.ordinal) && isPendingIntentSet(Type.LOCK.ordinal))
} else {
!isPendingIntentSet(Type.BOTH.ordinal)
val homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME)
val lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME)
if (homeAlbumName.isNullOrEmpty() || lockAlbumName.isNullOrEmpty()) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
}
if (shouldScheduleAlarm) {
scheduler.scheduleWallpaperAlarm(
WallpaperAlarmItem(
timeInMinutes1 = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
timeInMinutes2 = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
scheduleSeparately = shouldScheduleSeparately
), null, true, true
)
else {
val shouldScheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val shouldScheduleAlarm = if (shouldScheduleSeparately) {
!(isPendingIntentSet(Type.HOME.ordinal) && isPendingIntentSet(Type.LOCK.ordinal))
} else {
!isPendingIntentSet(Type.SINGLE.ordinal)
}
if (shouldScheduleAlarm) {
scheduler.scheduleWallpaperAlarm(
WallpaperAlarmItem(
homeInterval = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
lockInterval = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
scheduleSeparately = shouldScheduleSeparately
), null, true, true
)
}
}
}
}
@@ -23,8 +23,6 @@ import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import androidx.navigation.toRoute
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumScreen
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumViewModel
@@ -87,12 +85,13 @@ fun PaperizeApp(
val scope = rememberCoroutineScope()
// React to albumState changes and change selectedAlbum's details to keep it from being stale
LaunchedEffect(albumState.value.albumsWithWallpapers) {
LaunchedEffect(albumState) {
withContext(Dispatchers.IO) {
albumState.value.albumsWithWallpapers.asSequence().forEach { albumWithWallpapers ->
if (!albumWithWallpapers.album.initialized && (albumWithWallpapers.wallpapers.isNotEmpty() || albumWithWallpapers.folders.isNotEmpty())) {
albumsViewModel.onEvent(AlbumsEvent.InitializeAlbum(albumWithWallpapers))
} else if (albumWithWallpapers.wallpapers.isEmpty() && albumWithWallpapers.folders.isEmpty() && albumWithWallpapers.album.initialized) {
}
else if (albumWithWallpapers.wallpapers.isEmpty() && albumWithWallpapers.folders.isEmpty() && albumWithWallpapers.album.initialized) {
if (navController.currentDestination?.route == Home::class.simpleName) {
try {
navController.popBackStack<Home>(inclusive = false)
@@ -103,7 +102,7 @@ fun PaperizeApp(
albumsViewModel.onEvent(AlbumsEvent.DeleteAlbumWithWallpapers(albumWithWallpapers))
}
}
selectedState.value.selectedAlbum?.let { selectedAlbum ->
/*selectedState.value.selectedAlbum?.let { selectedAlbum ->
albumState.value.albumsWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName }
?.let { foundAlbum ->
val albumNameHashCode = foundAlbum.album.initialAlbumName.hashCode()
@@ -146,7 +145,7 @@ fun PaperizeApp(
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
scheduler.cancelWallpaperAlarm()
}
}
}*/
}
}
@@ -246,46 +245,34 @@ fun PaperizeApp(
onAlbumViewClick = {
navController.navigate(AlbumView(it))
},
onScheduleWallpaperChanger1 = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetHomeWallpaperInterval(timeInMinutes))
onScheduleWallpaperChanger = {
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately,
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
}
}
},
onScheduleWallpaperChanger2 = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetLockWallpaperInterval(timeInMinutes))
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = timeInMinutes,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
}
}
},
onTimeChange1 = { timeInMinutes ->
onHomeTimeChange = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetHomeWallpaperInterval(timeInMinutes))
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(3000)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
homeInterval = timeInMinutes,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately,
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.updateWallpaperAlarm(it)}
scheduler.scheduleRefresh()
@@ -293,16 +280,18 @@ fun PaperizeApp(
}
},
onTimeChange2 = { timeInMinutes ->
onLockTimeChange = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetLockWallpaperInterval(timeInMinutes))
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(3000)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = timeInMinutes,
scheduleSeparately = settingsState.value.scheduleSeparately
homeInterval = settingsState.value.homeInterval,
lockInterval = timeInMinutes,
scheduleSeparately = settingsState.value.scheduleSeparately,
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.updateWallpaperAlarm(it)}
scheduler.scheduleRefresh()
@@ -310,19 +299,31 @@ fun PaperizeApp(
}
},
onStop = {
onStop = { lock, home ->
if (selectedState.value.selectedAlbum != null) {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
val notSameAlbum = settingsState.value.homeAlbumName != settingsState.value.lockAlbumName
when {
lock && home -> {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset(selectedState.value.selectedAlbum!!.find { it.album.initialAlbumName == settingsState.value.homeAlbumName}))
}
lock -> {
if (notSameAlbum) wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset(selectedState.value.selectedAlbum!!.find { it.album.initialAlbumName == settingsState.value.lockAlbumName}))
}
home -> {
if (notSameAlbum) wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset(selectedState.value.selectedAlbum!!.find { it.album.initialAlbumName == settingsState.value.homeAlbumName}))
}
}
settingsViewModel.onEvent(SettingsEvent.RemoveSelectedAlbum(lock, home))
scheduler.cancelWallpaperAlarm()
}
},
animate = settingsState.value.animate,
interval1 = settingsState.value.homeInterval,
interval2 = settingsState.value.lockInterval,
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
lastSetTime = settingsState.value.lastSetTime,
nextSetTime = settingsState.value.nextSetTime,
selectedAlbum = selectedState.value.selectedAlbum,
homeSelectedAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.homeAlbumName },
lockSelectedAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.lockAlbumName },
enableChanger = settingsState.value.enableChanger,
darkenPercentage = settingsState.value.darkenPercentage,
darken = settingsState.value.darken,
@@ -331,54 +332,68 @@ fun PaperizeApp(
scheduleSeparately = settingsState.value.scheduleSeparately,
blur = settingsState.value.blur,
blurPercentage = settingsState.value.blurPercentage,
currentHomeWallpaper = settingsState.value.currentHomeWallpaper,
currentLockWallpaper = settingsState.value.currentLockWallpaper,
onToggleChanger = { enableWallpaperChanger ->
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
if (selectedState.value.selectedAlbum != null && enableWallpaperChanger && (settingsState.value.setHomeWallpaper || settingsState.value.setLockWallpaper)) {
wallpaperScreenViewModel.onEvent(
WallpaperEvent.UpdateSelectedAlbum(
selectedState.value.selectedAlbum!!.copy(
album = selectedState.value.selectedAlbum!!.album.copy(
currentHomeWallpaper = if (settingsState.value.setHomeWallpaper) selectedState.value.selectedAlbum!!.album.homeWallpapersInQueue.firstOrNull() else null,
currentLockWallpaper = if (settingsState.value.scheduleSeparately && settingsState.value.setLockWallpaper) selectedState.value.selectedAlbum!!.album.lockWallpapersInQueue.firstOrNull() else if (settingsState.value.setLockWallpaper) selectedState.value.selectedAlbum!!.album.homeWallpapersInQueue.firstOrNull() else null
)
),
null,
settingsState.value.scheduleSeparately,
settingsState.value.setHomeWallpaper,
settingsState.value.setLockWallpaper
)
)
job?.cancel()
job = scope.launch {
delay(2000)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
if (selectedState.value.selectedAlbum != null && !settingsState.value.homeAlbumName.isNullOrEmpty() && !settingsState.value.lockAlbumName.isNullOrEmpty()) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
if (enableWallpaperChanger) {
// update the wallpaper preview in wallpaper screen viewmodel
job?.cancel()
job = scope.launch {
delay(2000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately,
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true)
}
scheduler.scheduleRefresh()
}
}
else { scheduler.cancelWallpaperAlarm() }
}
},
onSelectAlbum = {album, lock, home ->
val notSameAlbum = settingsState.value.homeAlbumName != settingsState.value.lockAlbumName
when {
lock && home -> {
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(album, settingsState.value.homeAlbumName))
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = album.album.initialAlbumName,
lockAlbumName = album.album.initialAlbumName,
))
}
lock -> {
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(album, if (notSameAlbum) settingsState.value.lockAlbumName else null))
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = null,
lockAlbumName = album.album.initialAlbumName,
))
}
home -> {
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(album, if (notSameAlbum) settingsState.value.homeAlbumName else null))
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = album.album.initialAlbumName,
lockAlbumName = null,
))
}
}
else { scheduler.cancelWallpaperAlarm() }
},
onSelectAlbum = {album ->
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(true))
wallpaperScreenViewModel.onEvent(
WallpaperEvent.UpdateSelectedAlbum(
null,
album,
settingsState.value.scheduleSeparately,
settingsState.value.setHomeWallpaper,
settingsState.value.setLockWallpaper
)
)
job?.cancel()
job = scope.launch {
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = settingsState.value.scheduleSeparately,
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
@@ -390,7 +405,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
},
@@ -400,7 +415,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
},
@@ -412,29 +427,30 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
}
},
onHomeCheckedChange = { enableHome ->
settingsViewModel.onEvent(SettingsEvent.SetHome(enableHome))
if (selectedState.value.selectedAlbum!= null && !enableHome && !settingsState.value.setLockWallpaper) {
onHomeCheckedChange = { setHome -> settingsViewModel.onEvent(SettingsEvent.SetHome(setHome))
if (selectedState.value.selectedAlbum != null && !setHome && !settingsState.value.setLockWallpaper) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
selectedState.value.selectedAlbum?.let {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
}
scheduler.cancelWallpaperAlarm()
}
else if (selectedState.value.selectedAlbum!= null && (enableHome && !settingsState.value.setLockWallpaper) || (!enableHome && settingsState.value.setLockWallpaper)) {
else if (selectedState.value.selectedAlbum != null && (setHome && !settingsState.value.setLockWallpaper) || (!setHome && settingsState.value.setLockWallpaper)) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(2000)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = false
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = false,
setHome = setHome,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
@@ -444,28 +460,29 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
},
onLockCheckedChange = { enableLock ->
settingsViewModel.onEvent(SettingsEvent.SetLock(enableLock))
if (selectedState.value.selectedAlbum!= null && !enableLock && !settingsState.value.setHomeWallpaper) {
onLockCheckedChange = { setLock -> settingsViewModel.onEvent(SettingsEvent.SetLock(setLock))
if (selectedState.value.selectedAlbum!= null && !setLock && !settingsState.value.setHomeWallpaper) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
selectedState.value.selectedAlbum?.let {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
}
scheduler.cancelWallpaperAlarm()
}
else if (selectedState.value.selectedAlbum!= null && (enableLock && !settingsState.value.setHomeWallpaper) || (!enableLock && settingsState.value.setHomeWallpaper)) {
else if (selectedState.value.selectedAlbum!= null && (setLock && !settingsState.value.setHomeWallpaper) || (!setLock && settingsState.value.setHomeWallpaper)) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(2000)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = false
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = false,
setHome = settingsState.value.setHomeWallpaper,
setLock = setLock
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
@@ -475,35 +492,23 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
},
onScheduleSeparatelyChange = { changeSeparately ->
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(changeSeparately))
if (selectedState.value.selectedAlbum!= null && settingsState.value.enableChanger) {
wallpaperScreenViewModel.onEvent(
WallpaperEvent.UpdateSelectedAlbum(
selectedState.value.selectedAlbum!!.copy(
album = selectedState.value.selectedAlbum!!.album.copy(
currentHomeWallpaper = if (settingsState.value.setHomeWallpaper) selectedState.value.selectedAlbum!!.album.homeWallpapersInQueue.firstOrNull() else null,
currentLockWallpaper = if (changeSeparately && settingsState.value.setLockWallpaper) selectedState.value.selectedAlbum!!.album.lockWallpapersInQueue.firstOrNull() else if (settingsState.value.setLockWallpaper) selectedState.value.selectedAlbum!!.album.homeWallpapersInQueue.firstOrNull() else null
)
),
null,
settingsState.value.scheduleSeparately,
settingsState.value.setHomeWallpaper,
settingsState.value.setLockWallpaper
)
)
if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
//update wallpaper preview
job?.cancel()
job = scope.launch {
delay(2000)
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = settingsState.value.homeInterval,
timeInMinutes2 = settingsState.value.lockInterval,
scheduleSeparately = changeSeparately
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
scheduleSeparately = changeSeparately,
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
scheduler.scheduleRefresh()
@@ -516,7 +521,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
},
@@ -526,7 +531,7 @@ fun PaperizeApp(
job?.cancel()
job = scope.launch {
delay(2000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
},
@@ -564,12 +569,6 @@ fun PaperizeApp(
navController.navigate(WallpaperView(it))
},
onShowFolderView = { folderName, wallpapers ->
/*navController.navigate(
com.anthonyla.paperize.feature.wallpaper.util.navigation.FolderView(
folderName,
wallpapers
)
)*/
val encodedWallpapers = runBlocking { encodeUri(uri = Gson().toJson(wallpapers)) }
navController.navigate("${NavScreens.FolderView.route}/$folderName/$encodedWallpapers")
},
@@ -606,41 +605,6 @@ fun PaperizeApp(
animate = settingsState.value.animate
)
}
/*composable<FolderView>(
enterTransition = {
if (settingsState.value.animate) {
sharedXTransitionIn(initial = { (it * INITIAL_OFFSET).toInt() })
} else { null }
},
exitTransition = {
if (settingsState.value.animate) {
sharedXTransitionOut(target = { -(it * INITIAL_OFFSET).toInt() })
} else { null }
},
popEnterTransition = {
if (settingsState.value.animate) {
sharedXTransitionIn(initial = { -(it * INITIAL_OFFSET).toInt() })
} else { null }
},
popExitTransition = {
if (settingsState.value.animate) {
sharedXTransitionOut(target = { -(it * INITIAL_OFFSET).toInt() })
} else { null }
}
) { backStackEntry ->
val folderView: FolderView = backStackEntry.toRoute()
if (folderView.wallpapers.isNotEmpty()) {
FolderViewScreen(
folderName = folderView.folderName,
wallpapers = folderView.wallpapers,
onBackClick = { navController.navigateUp() },
onShowWallpaperView = {
navController.navigate(WallpaperView(it))
},
animate = settingsState.value.animate
)
} else { navController.navigateUp() }
}*/
composable(
route = NavScreens.FolderView.route.plus("/{folderName}/{wallpapers}"),
arguments = listOf(
@@ -721,12 +685,6 @@ fun PaperizeApp(
navController.navigate(WallpaperView(it))
},
onShowFolderView = { folderName, wallpapers ->
/*navController.navigate(
com.anthonyla.paperize.feature.wallpaper.util.navigation.FolderView(
folderName,
wallpapers
)
)*/
val encodedWallpapers = runBlocking { encodeUri(uri = Gson().toJson(wallpapers)) }
navController.navigate("${NavScreens.FolderView.route}/$folderName/$encodedWallpapers")
},
@@ -790,7 +748,7 @@ fun PaperizeApp(
},
onResetClick = {
settingsViewModel.onEvent(SettingsEvent.Reset)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
albumsViewModel.onEvent(AlbumsEvent.Reset)
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
scheduler.cancelWallpaperAlarm()
@@ -53,23 +53,13 @@ class AddAlbumViewModel @Inject constructor(
initialAlbumName = _state.value.initialAlbumName,
displayedAlbumName = _state.value.displayedAlbumName,
coverUri = albumCoverUri,
initialized = false,
),
wallpapers = _state.value.wallpapers,
folders = _state.value.folders,
)
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
_state.update { it.copy(
initialAlbumName = "",
displayedAlbumName = "",
coverUri = "",
wallpapers = emptyList(),
folders = emptyList(),
selectedFolders = emptyList(),
selectedWallpapers = emptyList(),
isEmpty = false,
allSelected = false,
selectedCount = 0,
) }
_state.update { AddAlbumState() }
}
}
is AddAlbumEvent.DeleteSelected -> {
@@ -121,7 +111,7 @@ class AddAlbumViewModel @Inject constructor(
Wallpaper(
initialAlbumName = _state.value.initialAlbumName,
wallpaperUri = uri,
key = uri.hashCode() + _state.value.initialAlbumName.hashCode(),
key = uri.hashCode() + _state.value.initialAlbumName.hashCode() + System.currentTimeMillis().toInt()
)
}
_state.update {
@@ -156,7 +146,7 @@ class AddAlbumViewModel @Inject constructor(
folderUri = event.directoryUri,
coverUri = wallpapers.randomOrNull(),
wallpapers = wallpapers,
key = event.directoryUri.hashCode() + it.initialAlbumName.hashCode()
key = event.directoryUri.hashCode() + it.initialAlbumName.hashCode() + System.currentTimeMillis().toInt()
)
)
)
@@ -38,8 +38,8 @@ fun HomeScreen(
darkenPercentage: Int,
enableChanger: Boolean,
homeEnabled : Boolean,
interval1: Int,
interval2: Int,
homeInterval: Int,
lockInterval: Int,
lastSetTime: String?,
lockEnabled : Boolean,
navigateToAddWallpaperScreen: (String) -> Unit,
@@ -50,22 +50,24 @@ fun HomeScreen(
onHomeCheckedChange: (Boolean) -> Unit,
onLockCheckedChange: (Boolean) -> Unit,
onScalingChange: (ScalingConstants) -> Unit,
onScheduleWallpaperChanger1: (Int) -> Unit,
onScheduleWallpaperChanger2: (Int) -> Unit,
onSelectAlbum: (AlbumWithWallpaperAndFolder) -> Unit,
onScheduleWallpaperChanger: () -> Unit,
onSelectAlbum: (AlbumWithWallpaperAndFolder, Boolean, Boolean) -> Unit,
onScheduleSeparatelyChange: (Boolean) -> Unit,
onTimeChange1: (Int) -> Unit,
onTimeChange2: (Int) -> Unit,
onHomeTimeChange: (Int) -> Unit,
onLockTimeChange: (Int) -> Unit,
onSettingsClick: () -> Unit,
onStop: () -> Unit,
onStop: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
scaling: ScalingConstants,
selectedAlbum: SelectedAlbum?,
scheduleSeparately: Boolean,
blur: Boolean,
onBlurPercentageChange: (Int) -> Unit,
onBlurChange: (Boolean) -> Unit,
blurPercentage: Int,
currentHomeWallpaper: String?,
currentLockWallpaper: String?,
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
) {
val tabItems = getTabItems()
val pagerState = rememberPagerState(0) { tabItems.size }
@@ -117,9 +119,7 @@ fun HomeScreen(
text = { Text(text = item.title) },
icon = {
Icon(
imageVector =
if (index == tabIndex) item.filledIcon
else item.unfilledIcon,
imageVector = if (index == tabIndex) item.filledIcon else item.unfilledIcon,
contentDescription = item.title
)
}
@@ -130,7 +130,7 @@ fun HomeScreen(
state = pagerState,
beyondViewportPageCount = 1
) { index ->
when(index.coerceIn(tabItems.indices)) {
when (index.coerceIn(tabItems.indices)) {
0 -> WallpaperScreen(
albums = albums,
animate = animate,
@@ -138,8 +138,8 @@ fun HomeScreen(
darkenPercentage = darkenPercentage,
enableChanger = enableChanger,
homeEnabled = homeEnabled,
interval1 = interval1,
interval2 = interval2,
homeInterval = homeInterval,
lockInterval = lockInterval,
lastSetTime = lastSetTime,
lockEnabled = lockEnabled,
nextSetTime = nextSetTime,
@@ -149,20 +149,22 @@ fun HomeScreen(
onLockCheckedChange = onLockCheckedChange,
scheduleSeparately = scheduleSeparately,
onScheduleSeparatelyChange = onScheduleSeparatelyChange,
onScheduleWallpaperChanger1 = onScheduleWallpaperChanger1,
onScheduleWallpaperChanger2 = onScheduleWallpaperChanger2,
onScheduleWallpaperChanger = onScheduleWallpaperChanger,
onScalingChange = onScalingChange,
onSelectAlbum = onSelectAlbum,
onTimeChange1 = onTimeChange1,
onTimeChange2 = onTimeChange2,
onHomeTimeChange = onHomeTimeChange,
onLockTimeChange = onLockTimeChange,
onStop = onStop,
onToggleChanger = onToggleChanger,
scaling = scaling,
selectedAlbum = selectedAlbum,
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
blur = blur,
onBlurPercentageChange = onBlurPercentageChange,
onBlurChange = onBlurChange,
blurPercentage = blurPercentage
blurPercentage = blurPercentage,
currentHomeWallpaper = currentHomeWallpaper,
currentLockWallpaper = currentLockWallpaper
)
else -> LibraryScreen(
albums = albums,
@@ -16,6 +16,10 @@ sealed class SettingsEvent {
data class SetBlur(val blur: Boolean): SettingsEvent()
data class SetLock(val lock: Boolean): SettingsEvent()
data class SetHome(val home: Boolean): SettingsEvent()
data class SetCurrentHomeWallpaper(val currentHomeWallpaper: String?): SettingsEvent()
data class SetCurrentLockWallpaper(val currentLockWallpaper: String?): SettingsEvent()
data class SetAlbumName(val homeAlbumName: String? = null, val lockAlbumName: String? = null): SettingsEvent()
data class RemoveSelectedAlbum(val removeLock: Boolean = false, val removeHome: Boolean = false): SettingsEvent()
data class SetScheduleSeparately(val scheduleSeparately: Boolean): SettingsEvent()
data class SetHomeWallpaperInterval(val interval: Int): SettingsEvent()
data class SetLockWallpaperInterval(val interval: Int): SettingsEvent()
@@ -13,6 +13,10 @@ data class SettingsState(
val enableChanger: Boolean = false,
val setHomeWallpaper: Boolean = false,
val setLockWallpaper: Boolean = false,
val currentHomeWallpaper: String? = null,
val currentLockWallpaper: String? = null,
val homeAlbumName: String? = null,
val lockAlbumName: String? = null,
val scheduleSeparately: Boolean = false,
val homeInterval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lockInterval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
@@ -39,10 +39,14 @@ class SettingsViewModel @Inject constructor (
val amoledTheme = async { settingsDataStoreImpl.getBoolean(SettingsConstants.AMOLED_THEME_TYPE) ?: false }
val dynamicTheming = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DYNAMIC_THEME_TYPE) ?: false }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: true }
val setHomeWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false }
val setLockWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false }
val setHomeWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false }
val setLockWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false }
val setCurrentHomeWallpaper = async { settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER) }
val setCurrentLockWallpaper = async { settingsDataStoreImpl.getString(SettingsConstants.CURRENT_LOCK_WALLPAPER) }
val homeWallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
val lockWallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
val homeAlbumName = async { settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) }
val lockAlbumName = async { settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) }
val lastSetTime = async { settingsDataStoreImpl.getString(SettingsConstants.LAST_SET_TIME) }
val nextSetTime = async { settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME) }
val animate = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ANIMATE_TYPE) ?: true }
@@ -60,6 +64,8 @@ class SettingsViewModel @Inject constructor (
dynamicTheming = dynamicTheming.await(),
homeInterval = homeWallpaperInterval.await(),
lockInterval = lockWallpaperInterval.await(),
homeAlbumName = homeAlbumName.await(),
lockAlbumName = lockAlbumName.await(),
firstLaunch = firstLaunch.await(),
lastSetTime = lastSetTime.await(),
nextSetTime = nextSetTime.await(),
@@ -70,6 +76,8 @@ class SettingsViewModel @Inject constructor (
wallpaperScaling = wallpaperScaling.await(),
setHomeWallpaper = setHomeWallpaper.await(),
setLockWallpaper = setLockWallpaper.await(),
currentHomeWallpaper = setCurrentHomeWallpaper.await(),
currentLockWallpaper = setCurrentLockWallpaper.await(),
scheduleSeparately = scheduleSeparately.await(),
blur = blur.await(),
blurPercentage = blurPercentage.await()
@@ -115,8 +123,12 @@ class SettingsViewModel @Inject constructor (
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: true }
val darkenPercentage = async { settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 0 }
val darken = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false }
val setHomeWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false }
val setLockWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false }
val setHomeWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false }
val setLockWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false }
val homeAlbumName = async { settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) }
val lockAlbumName = async { settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) }
val currentHomeWallpaper = async { settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER) }
val currentLockWallpaper = async { settingsDataStoreImpl.getString(SettingsConstants.CURRENT_LOCK_WALLPAPER) }
val homeWallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
val lockWallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
val scheduleSeparately = async { settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false }
@@ -136,6 +148,10 @@ class SettingsViewModel @Inject constructor (
darken = darken.await(),
setHomeWallpaper = setHomeWallpaper.await(),
setLockWallpaper = setLockWallpaper.await(),
homeAlbumName = homeAlbumName.await(),
lockAlbumName = lockAlbumName.await(),
currentHomeWallpaper = currentHomeWallpaper.await(),
currentLockWallpaper = currentLockWallpaper.await(),
lockInterval = lockWallpaperInterval.await(),
homeInterval = homeWallpaperInterval.await(),
scheduleSeparately = scheduleSeparately.await(),
@@ -288,7 +304,7 @@ class SettingsViewModel @Inject constructor (
is SettingsEvent.SetHome -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putBoolean(SettingsConstants.HOME_WALLPAPER, event.home)
settingsDataStoreImpl.putBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER, event.home)
_state.update {
it.copy(
setHomeWallpaper = event.home
@@ -299,7 +315,7 @@ class SettingsViewModel @Inject constructor (
is SettingsEvent.SetLock -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.putBoolean(SettingsConstants.LOCK_WALLPAPER, event.lock)
settingsDataStoreImpl.putBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER, event.lock)
_state.update {
it.copy(
setLockWallpaper = event.lock
@@ -374,6 +390,80 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.SetCurrentHomeWallpaper -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.currentHomeWallpaper != null) {
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, event.currentHomeWallpaper)
}
else {
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_HOME_WALLPAPER)
}
_state.update {
it.copy(
currentHomeWallpaper = event.currentHomeWallpaper
)
}
}
}
is SettingsEvent.SetCurrentLockWallpaper -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.currentLockWallpaper != null) {
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, event.currentLockWallpaper)
}
else {
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_LOCK_WALLPAPER)
}
_state.update {
it.copy(
currentLockWallpaper = event.currentLockWallpaper
)
}
}
}
is SettingsEvent.SetAlbumName -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.homeAlbumName != null) {
settingsDataStoreImpl.putString(SettingsConstants.HOME_ALBUM_NAME, event.homeAlbumName)
}
if (event.lockAlbumName != null) {
settingsDataStoreImpl.putString(SettingsConstants.LOCK_ALBUM_NAME, event.lockAlbumName)
}
val enableChanger: Boolean = when {
event.homeAlbumName != null && event.lockAlbumName != null -> { true }
event.homeAlbumName != null && !_state.value.lockAlbumName.isNullOrEmpty() -> { true }
event.lockAlbumName != null && !_state.value.homeAlbumName.isNullOrEmpty() -> { true }
else -> { false }
}
settingsDataStoreImpl.putBoolean(SettingsConstants.ENABLE_CHANGER, enableChanger)
_state.update {
it.copy(
homeAlbumName = event.homeAlbumName ?: it.homeAlbumName,
lockAlbumName = event.lockAlbumName ?: it.lockAlbumName,
enableChanger = enableChanger
)
}
}
}
is SettingsEvent.RemoveSelectedAlbum -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.removeHome) {
settingsDataStoreImpl.deleteString(SettingsConstants.HOME_ALBUM_NAME)
}
if (event.removeLock) {
settingsDataStoreImpl.deleteString(SettingsConstants.LOCK_ALBUM_NAME)
}
_state.update {
it.copy(
homeAlbumName = if (event.removeHome) null else it.homeAlbumName,
lockAlbumName = if (event.removeLock) null else it.lockAlbumName,
enableChanger = false
)
}
}
}
is SettingsEvent.Reset -> {
viewModelScope.launch(Dispatchers.IO) {
settingsDataStoreImpl.deleteBoolean(SettingsConstants.DARK_MODE_TYPE)
@@ -387,8 +477,12 @@ class SettingsViewModel @Inject constructor (
settingsDataStoreImpl.deleteInt(SettingsConstants.DARKEN_PERCENTAGE)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.DARKEN)
settingsDataStoreImpl.deleteString(SettingsConstants.WALLPAPER_SCALING)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.HOME_WALLPAPER)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.LOCK_WALLPAPER)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_HOME_WALLPAPER)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_LOCK_WALLPAPER)
settingsDataStoreImpl.deleteString(SettingsConstants.HOME_ALBUM_NAME)
settingsDataStoreImpl.deleteString(SettingsConstants.LOCK_ALBUM_NAME)
settingsDataStoreImpl.deleteInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL)
settingsDataStoreImpl.deleteInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.SCHEDULE_SEPARATELY)
@@ -413,8 +507,12 @@ class SettingsViewModel @Inject constructor (
wallpaperScaling = ScalingConstants.FILL,
setHomeWallpaper = false,
setLockWallpaper = false,
currentHomeWallpaper = null,
currentLockWallpaper = null,
lockInterval = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
homeInterval = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
homeAlbumName = null,
lockAlbumName = null,
scheduleSeparately = false,
blur = false,
blurPercentage = 0
@@ -4,13 +4,7 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperA
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
sealed class WallpaperEvent {
data class UpdateSelectedAlbum(
val selectedAlbum: SelectedAlbum?,
val album: AlbumWithWallpaperAndFolder?,
val scheduleSeparately: Boolean = false,
val setHome: Boolean = false,
val setLock: Boolean = false
): WallpaperEvent()
data object Reset : WallpaperEvent()
data class UpdateSelectedAlbum(val album: AlbumWithWallpaperAndFolder, val deleteAlbumName: String? = null): WallpaperEvent()
data class Reset(val album: SelectedAlbum? = null) : WallpaperEvent()
data object Refresh : WallpaperEvent()
}
@@ -38,6 +38,7 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.co
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.IndividualSchedulingAndToggleRow
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.TimeSliders
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.WallpaperPreviewAndScale
import kotlinx.coroutines.launch
@@ -50,40 +51,44 @@ fun WallpaperScreen(
darkenPercentage: Int,
enableChanger: Boolean,
homeEnabled: Boolean,
interval1: Int,
interval2: Int,
homeInterval: Int,
lockInterval: Int,
lastSetTime: String?,
lockEnabled: Boolean,
nextSetTime: String?,
currentHomeWallpaper: String?,
currentLockWallpaper: String?,
onDarkCheck: (Boolean) -> Unit,
onDarkenPercentage: (Int) -> Unit,
onHomeCheckedChange: (Boolean) -> Unit,
onLockCheckedChange: (Boolean) -> Unit,
scheduleSeparately: Boolean,
onScheduleSeparatelyChange: (Boolean) -> Unit,
onScheduleWallpaperChanger1: (Int) -> Unit,
onScheduleWallpaperChanger2: (Int) -> Unit,
onScheduleWallpaperChanger: () -> Unit,
onScalingChange: (ScalingConstants) -> Unit,
onSelectAlbum: (AlbumWithWallpaperAndFolder) -> Unit,
onTimeChange1: (Int) -> Unit,
onTimeChange2: (Int) -> Unit,
onStop: () -> Unit,
onSelectAlbum: (AlbumWithWallpaperAndFolder, Boolean, Boolean) -> Unit,
onHomeTimeChange: (Int) -> Unit,
onLockTimeChange: (Int) -> Unit,
onStop: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
scaling: ScalingConstants,
selectedAlbum: SelectedAlbum?,
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
blur: Boolean,
onBlurPercentageChange: (Int) -> Unit,
onBlurChange: (Boolean) -> Unit,
blurPercentage: Int
) {
val shouldShowScreen = homeEnabled || lockEnabled
val shouldShowSettings = shouldShowScreen && selectedAlbum != null
val shouldShowSettings = shouldShowScreen && (homeSelectedAlbum != null || lockSelectedAlbum != null)
val scrollState = rememberScrollState()
val context = LocalContext.current
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val showInterval = rememberSaveable { mutableStateOf(false) }
val lock = rememberSaveable { mutableStateOf(false) }
val home = rememberSaveable { mutableStateOf(false) }
Scaffold(
snackbarHost = {
@@ -112,9 +117,20 @@ fun WallpaperScreen(
onHomeCheckedChange = onHomeCheckedChange,
onLockCheckedChange = onLockCheckedChange
)
if (homeEnabled && lockEnabled) {
IndividualSchedulingAndToggleRow(
animate = animate,
scheduleSeparately = scheduleSeparately,
enableChanger = enableChanger,
onToggleChanger = onToggleChanger,
onScheduleSeparatelyChange = onScheduleSeparatelyChange
)
}
if (homeEnabled || lockEnabled) {
CurrentSelectedAlbum(
selectedAlbum = selectedAlbum,
homeSelectedAlbum = homeSelectedAlbum,
lockSelectedAlbum = lockSelectedAlbum,
scheduleSeparately = scheduleSeparately,
animate = animate,
enableChanger = enableChanger,
onToggleChanger = {
@@ -130,9 +146,11 @@ fun WallpaperScreen(
}
onToggleChanger(it)
},
onOpenBottomSheet = {
onOpenBottomSheet = { changeLock, changeHome ->
if (albums.firstOrNull() != null) {
openBottomSheet = true
lock.value = changeLock
home.value = changeHome
} else {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
@@ -144,28 +162,32 @@ fun WallpaperScreen(
}
}
},
onStop = {
if (selectedAlbum != null) {
onStop = { lock, home ->
if (homeSelectedAlbum != null || lockSelectedAlbum != null) {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = context.getString(
R.string.has_been_unselected,
selectedAlbum.album.displayedAlbumName
when {
home && lock -> homeSelectedAlbum?.album?.displayedAlbumName ?: ""
home -> homeSelectedAlbum?.album?.displayedAlbumName ?: ""
lock -> lockSelectedAlbum?.album?.displayedAlbumName ?: ""
else -> ""
}
),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
onStop()
onStop(lock, home)
}
}
)
if (shouldShowSettings) {
CurrentAndNextChange(lastSetTime, nextSetTime)
if (true) {
WallpaperPreviewAndScale(
currentHomeWallpaper = selectedAlbum!!.album.currentHomeWallpaper,
currentLockWallpaper = selectedAlbum!!.album.currentLockWallpaper,
currentHomeWallpaper = currentHomeWallpaper,
currentLockWallpaper = currentLockWallpaper,
animate = animate,
darken = darken,
darkenPercentage = darkenPercentage,
@@ -176,22 +198,22 @@ fun WallpaperScreen(
blur = blur,
blurPercentage = blurPercentage
)
CurrentAndNextChange(lastSetTime, nextSetTime)
TimeSliders(
timeInMinutes1 = interval1,
timeInMinutes2 = interval2,
timeInMinutes1 = homeInterval,
timeInMinutes2 = lockInterval,
onTimeChange1 = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onTimeChange1(totalMinutes)
onHomeTimeChange(totalMinutes)
},
onTimeChange2 = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onTimeChange2(totalMinutes)
onLockTimeChange(totalMinutes)
},
showInterval = showInterval.value,
animate = animate,
onShowIntervalChange = { showInterval.value = it },
scheduleSeparately = scheduleSeparately,
onScheduleSeparatelyChange = onScheduleSeparatelyChange,
lockEnabled = lockEnabled,
homeEnabled = homeEnabled
)
@@ -215,7 +237,7 @@ fun WallpaperScreen(
if (shouldShowScreen && openBottomSheet) {
AlbumBottomSheet(
albums = albums,
currentSelectedAlbum = selectedAlbum,
currentSelectedAlbum = null,
onDismiss = { openBottomSheet = false },
onSelect = { album ->
openBottomSheet = false
@@ -228,13 +250,13 @@ fun WallpaperScreen(
}
}
else {
onSelectAlbum(album)
onScheduleWallpaperChanger1(interval1)
onSelectAlbum(album, lock.value, home.value)
onScheduleWallpaperChanger()
}
}
else {
onSelectAlbum(album)
onScheduleWallpaperChanger1(interval1)
onSelectAlbum(album, lock.value, home.value)
onScheduleWallpaperChanger()
}
},
animate = animate
@@ -31,7 +31,7 @@ class WallpaperScreenViewModel @Inject constructor (
repository.getSelectedAlbum().collect { selectedAlbum ->
_state.update {
it.copy(
selectedAlbum = selectedAlbum.firstOrNull(),
selectedAlbum = selectedAlbum,
isDataLoaded = true
)
}
@@ -43,42 +43,30 @@ class WallpaperScreenViewModel @Inject constructor (
when (event) {
is WallpaperEvent.UpdateSelectedAlbum -> {
viewModelScope.launch(Dispatchers.IO) {
if (!event.setHome && !event.setLock) return@launch
if (event.selectedAlbum != null) {
_state.update {
it.copy(
selectedAlbum = event.selectedAlbum
val deleted = event.deleteAlbumName?.let {
repository.cascadeDeleteAlbum(it)
true
} ?: false
val wallpapers = event.album.wallpapers + event.album.folders.flatMap { folder ->
folder.wallpapers.map { wallpaper ->
Wallpaper(
initialAlbumName = event.album.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + event.album.album.initialAlbumName.hashCode() + System.currentTimeMillis().toInt(),
)
}
repository.upsertSelectedAlbum(event.selectedAlbum)
}
else if (event.album != null) {
val wallpapers: List<Wallpaper> = event.album.wallpapers + event.album.folders.asSequence().flatMap { folder ->
folder.wallpapers.asSequence().map { wallpaper ->
Wallpaper(
initialAlbumName = event.album.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + event.album.album.initialAlbumName.hashCode(),
)
val newSelectedAlbum = SelectedAlbum(
album = event.album.album.copy(wallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled()),
wallpapers = wallpapers
)
repository.upsertSelectedAlbum(newSelectedAlbum)
_state.update {
it.copy(
selectedAlbum = it.selectedAlbum?.let { selectedAlbums ->
selectedAlbums.filterNot { selectedAlbum -> deleted && selectedAlbum.album.initialAlbumName == event.deleteAlbumName } + newSelectedAlbum
}
}.toList()
val shuffledWallpapers1 = wallpapers.map { it.wallpaperUri }.shuffled()
val shuffledWallpapers2 = wallpapers.map { it.wallpaperUri }.shuffled()
val newSelectedAlbum = SelectedAlbum(
album = event.album.album.copy(
homeWallpapersInQueue = shuffledWallpapers1,
lockWallpapersInQueue = shuffledWallpapers2,
currentHomeWallpaper = if (event.setHome) shuffledWallpapers1.firstOrNull() else null,
currentLockWallpaper = if (event.scheduleSeparately && event.setLock) shuffledWallpapers2.firstOrNull() else if (event.setLock) shuffledWallpapers1.firstOrNull() else null,
),
wallpapers = wallpapers
)
_state.update {
it.copy(
selectedAlbum = newSelectedAlbum
)
}
repository.upsertSelectedAlbum(newSelectedAlbum)
}
}
}
@@ -87,12 +75,22 @@ class WallpaperScreenViewModel @Inject constructor (
}
is WallpaperEvent.Reset -> {
viewModelScope.launch(Dispatchers.IO) {
_state.update {
it.copy(
selectedAlbum = null
)
if (event.album == null) {
repository.deleteAll()
_state.update {
it.copy(
selectedAlbum = null
)
}
}
else {
repository.cascadeDeleteAlbum(event.album.album.initialAlbumName)
_state.update {
it.copy(
selectedAlbum = it.selectedAlbum?.filter { selectedAlbum -> selectedAlbum.album.initialAlbumName != event.album.album.initialAlbumName }
)
}
}
repository.deleteAll()
}
}
}
@@ -103,7 +101,7 @@ class WallpaperScreenViewModel @Inject constructor (
viewModelScope.launch(Dispatchers.IO) {
repository.getSelectedAlbum().collect { selectedAlbum ->
_state.update { it.copy(
selectedAlbum = selectedAlbum.firstOrNull(),
selectedAlbum = selectedAlbum,
) }
}
}
@@ -4,5 +4,5 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
data class WallpaperState (
val isDataLoaded: Boolean = false,
val selectedAlbum: SelectedAlbum? = null
val selectedAlbum: List<SelectedAlbum>? = null
)
@@ -23,21 +23,21 @@ fun ChangerSelectionRow(
MultiChoiceSegmentedButtonRow (
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(start = 16.dp, end = 16.dp,))
.padding(PaddingValues(start = 16.dp, end = 16.dp))
) {
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2),
onCheckedChange = onHomeCheckedChange,
checked = homeEnabled
) {
Text(text = stringResource(R.string.home_screen_btn))
}
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),
onCheckedChange = onLockCheckedChange,
checked = lockEnabled
) {
Text(stringResource(R.string.lock_screen_btn))
}
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),
onCheckedChange = onHomeCheckedChange,
checked = homeEnabled
) {
Text(text = stringResource(R.string.home_screen_btn))
}
}
}
@@ -5,6 +5,7 @@ import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
@@ -46,11 +47,13 @@ import com.skydoves.landscapist.glide.GlideImage
*/
@Composable
fun CurrentSelectedAlbum(
selectedAlbum: SelectedAlbum?,
homeSelectedAlbum: SelectedAlbum?,
lockSelectedAlbum: SelectedAlbum?,
scheduleSeparately: Boolean,
enableChanger: Boolean,
onOpenBottomSheet: () -> Unit,
onStop: () -> Unit,
animate: Boolean,
onOpenBottomSheet: (Boolean, Boolean) -> Unit, // lock, home
onStop: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit
) {
fun isValidUri(context: Context, uriString: String?): Boolean {
@@ -64,94 +67,245 @@ fun CurrentSelectedAlbum(
} catch (e: Exception) { false }
}
val showCoverUri = isValidUri(LocalContext.current, selectedAlbum?.album?.coverUri)
val showHomeCoverUri = isValidUri(LocalContext.current, homeSelectedAlbum?.album?.coverUri)
val showLockCoverUri = isValidUri(LocalContext.current, lockSelectedAlbum?.album?.coverUri)
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.clip(RoundedCornerShape(16.dp))
.clickable {
if (selectedAlbum != null) {
onToggleChanger(!enableChanger)
} else {
onOpenBottomSheet()
}
},
headlineContent = {
Text(
text = selectedAlbum?.album?.displayedAlbumName ?: stringResource(R.string.no_album_selected),
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis
) },
supportingContent = {
if (selectedAlbum != null) {
if (scheduleSeparately) {
Row {
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.weight(1f)
.clip(RoundedCornerShape(16.dp))
.clickable { onOpenBottomSheet(true, false) },
headlineContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
if (lockSelectedAlbum != null) {
IconButton(onClick = { onStop(true, false) }) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.stop_the_album)
)
}
}
IconButton(onClick = { onOpenBottomSheet(true, false) }) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
}
}
},
supportingContent = {},
leadingContent = {
Column (horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Box(modifier = Modifier.size(50.dp)) {
if (lockSelectedAlbum != null) {
if (showLockCoverUri) {
GlideImage(
imageModel = { lockSelectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
}
},
trailingContent = {},
tonalElevation = 10.dp
)
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.weight(1f)
.clip(RoundedCornerShape(16.dp))
.clickable { onOpenBottomSheet(false, true) },
headlineContent = {
Row(verticalAlignment = Alignment.CenterVertically) {
if (homeSelectedAlbum != null) {
IconButton(onClick = { onStop(false, true) }) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.stop_the_album)
)
}
}
IconButton(onClick = { onOpenBottomSheet(false, true) }) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
}
}
},
supportingContent = {},
leadingContent = {
Box(modifier = Modifier.size(50.dp)) {
if (homeSelectedAlbum != null) {
if (showHomeCoverUri) {
GlideImage(
imageModel = { homeSelectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
},
trailingContent = {
},
tonalElevation = 10.dp
)
}
}
else {
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.clip(RoundedCornerShape(16.dp))
.clickable {
if (homeSelectedAlbum != null) {
onToggleChanger(!enableChanger)
} else {
onOpenBottomSheet(true, true)
}
},
headlineContent = {
Text(
text = LocalContext.current.resources.getQuantityString(R.plurals.wallpaper_count, selectedAlbum.wallpapers.size, selectedAlbum.wallpapers.size),
style = MaterialTheme.typography.bodySmall,
text = homeSelectedAlbum?.album?.displayedAlbumName ?: stringResource(R.string.no_album_selected),
style = MaterialTheme.typography.titleMedium,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
} },
leadingContent = {
Box (modifier = Modifier.size(60.dp)) {
if (selectedAlbum != null) {
if (showCoverUri) {
GlideImage(
imageModel = { selectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(modifier = Modifier.align(
Alignment.Center))
},
supportingContent = {
if (homeSelectedAlbum != null) {
Text(
text = LocalContext.current.resources.getQuantityString(
R.plurals.wallpaper_count,
homeSelectedAlbum.wallpapers.size,
homeSelectedAlbum.wallpapers.size
),
style = MaterialTheme.typography.bodySmall,
overflow = TextOverflow.Ellipsis
)
}
},
leadingContent = {
Box(modifier = Modifier.size(60.dp)) {
if (homeSelectedAlbum != null) {
if (showHomeCoverUri) {
GlideImage(
imageModel = { homeSelectedAlbum.album.coverUri },
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(150, 150),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(
modifier = Modifier.align(
Alignment.Center
)
)
}
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
} else {
Image(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.no_icon),
modifier = Modifier.fillMaxSize()
)
}
}
},
trailingContent = {
Row (
horizontalArrangement = Arrangement.spacedBy((-8).dp),
verticalAlignment = Alignment.CenterVertically
) {
if (selectedAlbum != null) {
IconButton(onClick = { onStop() }) {
Icon(imageVector = Icons.Default.Stop, contentDescription = stringResource(R.string.stop_the_album))
},
trailingContent = {
Row(
horizontalArrangement = Arrangement.spacedBy((-8).dp),
verticalAlignment = Alignment.CenterVertically
) {
if (homeSelectedAlbum != null) {
IconButton(onClick = { onStop(true, true) }) {
Icon(
imageVector = Icons.Default.Stop,
contentDescription = stringResource(R.string.stop_the_album)
)
}
}
IconButton(onClick = { onOpenBottomSheet(true, true) }) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
}
if (homeSelectedAlbum != null) {
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger,
modifier = Modifier
.rotate(270f)
.scale(0.75f)
)
}
}
IconButton(onClick = { onOpenBottomSheet() }) {
Icon(
contentDescription = stringResource(R.string.click_to_select_a_different_album),
imageVector = Icons.Filled.ArrowDropDown,
)
}
if (selectedAlbum != null) {
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger,
modifier = Modifier
.rotate(270f)
.scale(0.75f)
)
}
}
},
tonalElevation = 10.dp
)
},
tonalElevation = 10.dp
)
}
}
@@ -0,0 +1,134 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
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.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
/**
* Composable to toggle individual scheduling settings and toggle wallpaper changer when scheduling separately
*/
@Composable
fun IndividualSchedulingAndToggleRow(
animate: Boolean,
scheduleSeparately: Boolean,
enableChanger : Boolean,
onToggleChanger: (Boolean) -> Unit,
onScheduleSeparatelyChange: (Boolean) -> Unit,
) {
val columnModifier = remember {
if (animate) {
Modifier.animateContentSize(
animationSpec = tween(durationMillis = 200, easing = LinearOutSlowInEasing)
)
} else { Modifier }
}
Surface(
tonalElevation = 10.dp,
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
) {
Column(
modifier = columnModifier
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.individual_scheduling),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Switch(
checked = scheduleSeparately,
onCheckedChange = onScheduleSeparatelyChange
)
}
if (animate) {
AnimatedVisibility(
visible = scheduleSeparately,
enter = expandVertically(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
),
exit = fadeOut(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
)
) {
Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 48.dp)) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline, thickness = 2.dp)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Enable Wallpaper Changer",
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger
)
}
}
}
else {
if (scheduleSeparately) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Enable wallpaper changer",
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger
)
}
}
}
}
}
}
@@ -28,7 +28,6 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
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
@@ -61,7 +60,6 @@ fun TimeSliders(
animate: Boolean,
onShowIntervalChange: (Boolean) -> Unit,
scheduleSeparately: Boolean,
onScheduleSeparatelyChange: (Boolean) -> Unit,
onTimeChange1: (Int, Int, Int) -> Unit,
onTimeChange2: (Int, Int, Int) -> Unit,
lockEnabled: Boolean,
@@ -353,19 +351,6 @@ fun TimeSliders(
)
}
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Spacer(modifier = Modifier.width(16.dp))
Text(text = stringResource(R.string.individual_scheduling), fontWeight = FontWeight.W500)
Spacer(modifier = Modifier.width(16.dp))
Switch(
checked = scheduleSeparately,
onCheckedChange = onScheduleSeparatelyChange
)
}
}
Spacer(modifier = Modifier.height(16.dp))
}
@@ -192,7 +192,7 @@ fun WallpaperPreviewAndScale(
},
contentDescription = null,
tint = Color.Unspecified,
modifier = Modifier.size(40.dp)
modifier = Modifier.size(32.dp)
)
Text(text = label, maxLines = 1, overflow = TextOverflow.Ellipsis )
}
@@ -4,12 +4,16 @@ import com.anthonyla.paperize.core.SettingsConstants
/**
* Data class for storing wallpaper alarm item
* @param timeInMinutes1: Int - time in minutes for home wallpaper or both if scheduled together
* @param timeInMinutes2: Int - time in minutes for lock wallpaper
* @param homeInterval: Int - time in minutes for home wallpaper or both if scheduled together
* @param lockInterval: Int - time in minutes for lock wallpaper
* @param scheduleSeparately: Boolean - schedule wallpapers separately
* @param setHome: Boolean - set home wallpaper
* @param setLock: Boolean - set lock wallpaper
*/
data class WallpaperAlarmItem(
val timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val scheduleSeparately: Boolean = false
val homeInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val lockInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val scheduleSeparately: Boolean = false,
val setHome : Boolean = false,
val setLock : Boolean = false
)
@@ -18,10 +18,10 @@ interface WallpaperAlarmScheduler {
/**
* Update the wallpaper without changing the alarm
*/
fun updateWallpaper(scheduleSeparately: Boolean)
fun updateWallpaper(scheduleSeparately: Boolean, setHome: Boolean, setLock: Boolean)
/**
* Cancel all wallpaper alarms
*/
fun cancelWallpaperAlarm()
fun cancelWallpaperAlarm(cancelLock: Boolean = true, cancelHome: Boolean = true)
}
@@ -6,15 +6,15 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService1
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService2
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService
import java.time.LocalDateTime
import java.time.ZoneId
/**
* This class is responsible for scheduling wallpaper alarms.
* It uses the AlarmManager to schedule alarms for the WallpaperReceiver.
* It also uses the WallpaperService to change the wallpaper due to receiver limitations.
* It uses the AlarmManager to schedule alarms for the [WallpaperReceiver].
* It also uses [HomeWallpaperService] and [LockWallpaperService] to change the wallpaper due to receiver limitations.
*/
class WallpaperAlarmSchedulerImpl (
private val context: Context,
@@ -25,18 +25,21 @@ class WallpaperAlarmSchedulerImpl (
* Schedules the wallpaper alarm based on the origin and changeImmediate
*/
override fun scheduleWallpaperAlarm(wallpaperAlarmItem: WallpaperAlarmItem, origin: Int?, changeImmediate: Boolean, cancelImmediate: Boolean) {
// Cancel previous alarms before setting new ones to prevent stale alarms
if (cancelImmediate) cancelWallpaperAlarm()
else {
when(origin) {
when (origin) {
Type.HOME.ordinal -> cancelAlarm(Type.HOME)
Type.LOCK.ordinal -> cancelAlarm(Type.LOCK)
null -> {
cancelAlarm(Type.HOME)
cancelAlarm(Type.LOCK)
cancelAlarm(Type.BOTH)
cancelAlarm(Type.SINGLE)
}
}
}
// Schedule new wallpaper alarm
if (wallpaperAlarmItem.scheduleSeparately) {
when (origin) {
Type.LOCK.ordinal -> {
@@ -58,8 +61,8 @@ class WallpaperAlarmSchedulerImpl (
}
}
else {
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.BOTH)
scheduleWallpaper(wallpaperAlarmItem, Type.BOTH)
if (changeImmediate) changeWallpaperImmediate(wallpaperAlarmItem, Type.SINGLE)
scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE)
}
}
@@ -73,31 +76,30 @@ class WallpaperAlarmSchedulerImpl (
scheduleWallpaper(wallpaperAlarmItem, Type.HOME, null, true)
}
else {
scheduleWallpaper(wallpaperAlarmItem, Type.BOTH, null, true)
scheduleWallpaper(wallpaperAlarmItem, Type.SINGLE, null, true)
}
}
/**
* Update the wallpaper without scheduling alarms
*/
override fun updateWallpaper(scheduleSeparately: Boolean) {
override fun updateWallpaper(scheduleSeparately: Boolean, setHome: Boolean, setLock: Boolean) {
if (scheduleSeparately) {
updateWallpaper(Type.LOCK)
updateWallpaper(Type.HOME)
updateWallpaper(Type.LOCK, setHome, setLock)
updateWallpaper(Type.HOME, setHome, setLock)
}
else {
updateWallpaper(Type.BOTH)
updateWallpaper(Type.SINGLE, setHome, setLock)
}
}
/**
* Cancels all active alarms
*/
override fun cancelWallpaperAlarm() {
cancelAlarm(Type.HOME)
cancelAlarm(Type.LOCK)
cancelAlarm(Type.BOTH)
cancelAlarm(Type.REFRESH)
override fun cancelWallpaperAlarm(cancelLock: Boolean, cancelHome: Boolean) {
if (cancelLock) cancelAlarm(Type.LOCK)
if (cancelHome) cancelAlarm(Type.HOME)
if (cancelLock && cancelHome) cancelAlarm(Type.SINGLE)
}
/**
@@ -105,15 +107,16 @@ class WallpaperAlarmSchedulerImpl (
*/
private fun scheduleWallpaper(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int? = null, update: Boolean = false) {
val nextTime = when (type) {
Type.HOME, Type.BOTH -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.timeInMinutes1.toLong())
Type.LOCK -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.timeInMinutes2.toLong())
else -> LocalDateTime.now()
Type.LOCK -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.lockInterval.toLong())
else -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.homeInterval.toLong())
}
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.timeInMinutes1)
putExtra("timeInMinutes2", wallpaperAlarmItem.timeInMinutes2)
putExtra("timeInMinutes1", wallpaperAlarmItem.homeInterval)
putExtra("timeInMinutes2", wallpaperAlarmItem.lockInterval)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
putExtra("setHome", wallpaperAlarmItem.setHome)
putExtra("setLock", wallpaperAlarmItem.setLock)
putExtra("origin", origin)
}
@@ -147,22 +150,18 @@ class WallpaperAlarmSchedulerImpl (
)
}
if (update) {
val serviceIntent = Intent().apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.timeInMinutes1)
putExtra("timeInMinutes2", wallpaperAlarmItem.timeInMinutes2)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
}
if (type == Type.BOTH || type == Type.HOME) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.REQUEUE.toString()
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.REQUEUE.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.REQUEUE.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.REQUEUE.toString()
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.REQUEUE.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.HOME.ordinal)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.REQUEUE.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.LOCK.ordinal)
}
}
context.startService(serviceIntent)
}
}
@@ -210,39 +209,36 @@ class WallpaperAlarmSchedulerImpl (
* Use the service to change the wallpaper
*/
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
val serviceIntent = Intent().apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.timeInMinutes1)
putExtra("timeInMinutes2", wallpaperAlarmItem.timeInMinutes2)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
}
if (type == Type.BOTH || type == Type.HOME) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.START.toString()
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.START.toString()
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.HOME.ordinal)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.LOCK.ordinal)
}
}
context.startService(serviceIntent)
}
/**
* Updates the wallpaper without changing the alarm
*/
private fun updateWallpaper(type: Type) {
val serviceIntent = Intent()
if (type == Type.BOTH || type == Type.HOME) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.UPDATE.toString()
private fun updateWallpaper(type: Type, setHome: Boolean, setLock: Boolean) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
if (setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.UPDATE.toString()
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
}
}
context.startService(serviceIntent)
}
/**
@@ -257,4 +253,18 @@ class WallpaperAlarmSchedulerImpl (
)
alarmManager.cancel(pendingIntent)
}
/**
* Starts the service to change the wallpaper
*/
private fun startService(context: Context, serviceClass: Class<*>, action: String, timeInMinutes1: Int? = null, timeInMinutes2: Int? = null, scheduleSeparately: Boolean? = null, type: Int? = null) {
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action
timeInMinutes1?.let { putExtra("timeInMinutes1", it) }
timeInMinutes2?.let { putExtra("timeInMinutes2", it) }
scheduleSeparately?.let { putExtra("scheduleSeparately", it) }
type?.let { putExtra("type", it) }
}
context.startService(serviceIntent)
}
}
@@ -30,8 +30,8 @@ class WallpaperBootAndChangeReceiver : BroadcastReceiver() {
val timeInMinutes2 = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val alarmItem = WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes1,
timeInMinutes2 = timeInMinutes2,
homeInterval = timeInMinutes1,
lockInterval = timeInMinutes2,
scheduleSeparately = scheduleSeparately
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
@@ -5,8 +5,8 @@ import android.content.Context
import android.content.Intent
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService1
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.WallpaperService2
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperService
import dagger.hilt.android.AndroidEntryPoint
/**
@@ -16,10 +16,9 @@ import dagger.hilt.android.AndroidEntryPoint
class WallpaperReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null) {
val refresh = intent?.getBooleanExtra("refresh", false) ?: false
if (refresh) {
val serviceIntent = Intent(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.REFRESH.toString()
if (intent?.getBooleanExtra("refresh", false) == true) {
val serviceIntent = Intent(context, HomeWallpaperService::class.java).apply {
action = HomeWallpaperService.Actions.REFRESH.toString()
}
context.startService(serviceIntent)
WallpaperAlarmSchedulerImpl(context).scheduleRefresh()
@@ -28,35 +27,50 @@ class WallpaperReceiver: BroadcastReceiver() {
val timeInMinutes1 = intent?.getIntExtra("timeInMinutes1", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val timeInMinutes2 = intent?.getIntExtra("timeInMinutes2", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = intent?.getBooleanExtra("scheduleSeparately", false) ?: false
val type = intent?.getIntExtra("type", Type.BOTH.ordinal) ?: Type.BOTH.ordinal
val serviceIntent = Intent().apply {
putExtra("timeInMinutes1", timeInMinutes1)
putExtra("timeInMinutes2", timeInMinutes2)
putExtra("scheduleSeparately", scheduleSeparately)
putExtra("type", type)
}
if (type == Type.BOTH.ordinal || type == Type.HOME.ordinal) {
serviceIntent.setClass(context, WallpaperService1::class.java).apply {
action = WallpaperService1.Actions.START.toString()
val type = intent?.getIntExtra("type", Type.SINGLE.ordinal) ?: Type.SINGLE.ordinal
val setHome = intent?.getBooleanExtra("setHome", false) ?: false
val setLock = intent?.getBooleanExtra("setLock", false) ?: false
when (type) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), timeInMinutes1, timeInMinutes2, scheduleSeparately, type)
if (setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), timeInMinutes1, timeInMinutes2, scheduleSeparately, type)
}
} else {
serviceIntent.setClass(context, WallpaperService2::class.java).apply {
action = WallpaperService2.Actions.START.toString()
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), timeInMinutes1, timeInMinutes2, scheduleSeparately, type)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), timeInMinutes1, timeInMinutes2, scheduleSeparately, type)
}
}
context.startService(serviceIntent)
// Schedule next alarm for next wallpaper change
val origin = intent?.getIntExtra("origin", -1)?.takeIf { it != -1 }
WallpaperAlarmSchedulerImpl(context).scheduleWallpaperAlarm(
WallpaperAlarmItem(
timeInMinutes1 = timeInMinutes1,
timeInMinutes2 = timeInMinutes2,
scheduleSeparately = scheduleSeparately
homeInterval = timeInMinutes1,
lockInterval = timeInMinutes2,
scheduleSeparately = scheduleSeparately,
setHome = setHome,
setLock = setLock
),
origin
)
}
}
}
/**
* Starts the service to change the wallpaper
*/
private fun startService(context: Context, serviceClass: Class<*>, action: String, timeInMinutes1: Int? = null, timeInMinutes2: Int? = null, scheduleSeparately: Boolean? = null, type: Int? = null) {
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action
timeInMinutes1?.let { putExtra("timeInMinutes1", it) }
timeInMinutes2?.let { putExtra("timeInMinutes2", it) }
scheduleSeparately?.let { putExtra("scheduleSeparately", it) }
type?.let { putExtra("type", it) }
}
context.startService(serviceIntent)
}
}
@@ -33,7 +33,6 @@ import com.anthonyla.paperize.core.getImageDimensions
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.core.stretchBitmap
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
@@ -53,11 +52,11 @@ import javax.inject.Inject
import kotlin.math.min
/**
* Main service for changing the wallpaper if wallpapers are scheduled together
* Service for changing home screen
*/
@AndroidEntryPoint
class WallpaperService1: Service() {
private val handleThread = HandlerThread("MyThread1")
class HomeWallpaperService: Service() {
private val handleThread = HandlerThread("HomeThread")
private lateinit var workerHandler: Handler
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@@ -65,6 +64,8 @@ class WallpaperService1: Service() {
private var scheduleSeparately: Boolean = false
private var timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var type = Type.SINGLE.ordinal
private var nextSetTime1: LocalDateTime? = null
private var nextSetTime2: LocalDateTime? = null
private var nextSetTime: LocalDateTime? = null
@@ -93,14 +94,8 @@ class WallpaperService1: Service() {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
val setHomeOrLock = if (scheduleSeparately) {
when (intent.getIntExtra("type", Type.BOTH.ordinal)) {
Type.HOME.ordinal -> true
Type.LOCK.ordinal -> false
else -> null
}
} else { null }
workerTaskStart(setHomeOrLock)
type = intent.getIntExtra("type", Type.SINGLE.ordinal)
//workerTaskStart()
}
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
@@ -125,11 +120,11 @@ class WallpaperService1: Service() {
handleThread.quitSafely()
}
private fun workerTaskStart(setHomeOrLock: Boolean? = null) {
private fun workerTaskStart() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
if (scheduleSeparately) delay(5000)
changeWallpaper(this@WallpaperService1, setHomeOrLock)
changeWallpaper(this@HomeWallpaperService)
}
stopSelf()
}
@@ -152,7 +147,7 @@ class WallpaperService1: Service() {
private fun workerTaskUpdate(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@WallpaperService1, setHomeOrLock)
updateCurrentWallpaper(this@HomeWallpaperService, setHomeOrLock)
}
stopSelf()
}
@@ -161,7 +156,7 @@ class WallpaperService1: Service() {
private fun workerTaskRefresh() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
refreshAlbum(this@WallpaperService1)
refreshAlbum(this@HomeWallpaperService)
}
stopSelf()
}
@@ -189,7 +184,7 @@ class WallpaperService1: Service() {
* 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, setHomeOrLock: Boolean? = null) {
private suspend fun changeWallpaper(context: Context) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
@@ -198,38 +193,40 @@ class WallpaperService1: Service() {
}
else {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
if (!toggled || (!setHome && !setLock)) {
onDestroy()
return
}
/*nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (setHomeOrLock == null) {
if (setHome && setLock && !scheduleSeparately) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = nextSetTime1
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHomeOrLock) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
if (setHome) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong()) }
nextSetTime = if (nextSetTime1 == null && nextSetTime2 != null) {
nextSetTime2
} else if (nextSetTime1 != null && nextSetTime2 == null) {
}
else if (nextSetTime1 != null && nextSetTime2 == null) {
nextSetTime1
} else {
}
else {
if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
}
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())*/
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@@ -240,185 +237,6 @@ class WallpaperService1: Service() {
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
selectedAlbum.let { it ->
if (setHomeOrLock != null) {
var wallpaper = if (setHomeOrLock) it.album.homeWallpapersInQueue.firstOrNull() else it.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) it.album.homeWallpapersInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) it.album.lockWallpapersInQueue.drop(1) else it.album.lockWallpapersInQueue
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) it.album.homeWallpapersInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) it.album.lockWallpapersInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.lockWallpapersInQueue
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
)
)
)
}
} else { onDestroy() }
}
}
else {
var wallpaper = it.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper }
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper },
currentHomeWallpaper = wallpaper,
currentLockWallpaper = wallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper }
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = newWallpaperInQueue.drop(1),
currentHomeWallpaper = wallpaper,
currentLockWallpaper = wallpaper
)
)
)
}
} else { onDestroy() }
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
@@ -433,8 +251,8 @@ class WallpaperService1: Service() {
return
}
else {
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
if (!setHome && !setLock) {
onDestroy()
return
@@ -444,69 +262,6 @@ class WallpaperService1: Service() {
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
selectedAlbum.let { it ->
val wallpaper1 = it.album.currentHomeWallpaper
val wallpaper2 = it.album.currentLockWallpaper
if (wallpaper2 != null && (setHomeOrLock == null || setHomeOrLock == false)) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper2.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = false,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper2 }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.filter { it != wallpaper1 },
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper1 }
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
}
if (wallpaper1 != null && (setHomeOrLock == null || setHomeOrLock == true)) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper1.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = true,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper1 }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.filter { it != wallpaper1 },
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper1 }
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in updating", e)
@@ -694,24 +449,6 @@ class WallpaperService1: Service() {
onDestroy()
}
else {
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
homeWallpapersInQueue = if (selectedAlbum.album.homeWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.homeWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
lockWallpapersInQueue = if (selectedAlbum.album.lockWallpapersInQueue.firstOrNull() in wallpapersUri) {
val firstElement = selectedAlbum.album.lockWallpapersInQueue.first()
val modifiedWallpapersUri = wallpapersUri.filter { it != firstElement }
listOf(firstElement) + modifiedWallpapersUri.shuffled()
} else { wallpapersUri.shuffled() },
currentHomeWallpaper = if (selectedAlbum.album.currentHomeWallpaper in wallpapersUri) selectedAlbum.album.currentHomeWallpaper else selectedAlbum.album.homeWallpapersInQueue.firstOrNull { it in wallpapersUri },
currentLockWallpaper = if (selectedAlbum.album.currentLockWallpaper in wallpapersUri) selectedAlbum.album.currentLockWallpaper else selectedAlbum.album.lockWallpapersInQueue.firstOrNull { it in wallpapersUri }
),
wallpapers = wallpapers
)
selectedRepository.upsertSelectedAlbum(newSelectedAlbum)
}
} ?: run { onDestroy() }
}
@@ -0,0 +1,360 @@
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.HandlerThread
import android.os.IBinder
import android.util.DisplayMetrics
import android.util.Log
import androidx.core.app.NotificationCompat
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.blurBitmap
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
/**
* Service to change lock screen
*/
@AndroidEntryPoint
class LockWallpaperService: Service() {
private val handleThread = HandlerThread("LockThread")
private lateinit var workerHandler: Handler
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private var scheduleSeparately: Boolean = false
private var timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var nextSetTime1: LocalDateTime? = null
private var nextSetTime2: LocalDateTime? = null
private var nextSetTime: LocalDateTime? = null
enum class Actions {
START,
REQUEUE,
UPDATE
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
handleThread.start()
workerHandler = Handler(handleThread.looper)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
when (intent.action) {
Actions.START.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
//workerTaskStart()
}
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
workerTaskRequeue()
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
}
}
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
workerHandler.removeCallbacksAndMessages(null)
handleThread.quitSafely()
}
private fun workerTaskStart(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
changeWallpaper(this@LockWallpaperService, setHomeOrLock)
if (setHomeOrLock != null && !setHomeOrLock) {
updateCurrentWallpaper(this@LockWallpaperService, true)
}
}
stopSelf()
}
}
private fun workerTaskRequeue() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
stopSelf()
}
}
private fun workerTaskUpdate(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@LockWallpaperService, setHomeOrLock)
}
stopSelf()
}
}
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(): Notification? {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
if (nextSetTime != null) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.next_wallpaper_change, nextSetTime!!.format(formatter)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
return null
}
/**
* 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, setHomeOrLock: Boolean? = null) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
if (!toggled || (!setHome && !setLock)) {
onDestroy()
return
}
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (setHomeOrLock == null) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = nextSetTime1
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHomeOrLock) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong()) }
if (nextSetTime1 == null && nextSetTime2 != null) {
nextSetTime = nextSetTime2
}
else if (nextSetTime1 != null && nextSetTime2 == null) {
nextSetTime = nextSetTime1
}
else {
nextSetTime = if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
}
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
}
}
private suspend fun updateCurrentWallpaper(context: Context, setHomeOrLock: Boolean? = null) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
if (!setHome && !setLock) {
onDestroy()
return
}
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in updating", e)
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(
context: Context,
wallpaper: Uri,
darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
setHome: Boolean, setLock: Boolean,
setLockOrHome: Boolean? = null,
blur: Boolean = false,
blurPercent: Int,
): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val imageSize = wallpaper.getImageDimensions(context) ?: return false
val aspectRatio = imageSize.height.toFloat() / imageSize.width.toFloat()
val device = context.resources.displayMetrics
val targetWidth = min(3 * device.widthPixels, imageSize.width)
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSize(targetWidth, targetHeight)
decoder.isMutableRequired = true
}
} catch (e: Exception) {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
}
else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
if (bitmap == null) return false
else {
processBitmap(device, bitmap, darken, darkenPercent, scaling, blur, blurPercent)?.let { image ->
when {
setLockOrHome == true -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
setLockOrHome == false -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
setHome && setLock -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM)
setHome -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
setLock -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
else -> {}
}
wallpaperManager.forgetLoadedWallpaper()
image.recycle()
}
bitmap.recycle()
}
return true
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e)
return false
}
}
/**
* Darkens the bitmap by the given percentage and returns it
* 0 - lightest, 100 - darkest
*/
private fun processBitmap(
device: DisplayMetrics,
source: Bitmap, darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
blur: Boolean,
blurPercent: Int
): Bitmap? {
try {
var processedBitmap = source
// 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 && darkenPercent < 100) {
processedBitmap = darkenBitmap(processedBitmap, darkenPercent)
}
// Apply blur effect
if (blur && blurPercent > 0) {
processedBitmap = blurBitmap(processedBitmap, blurPercent)
}
return processedBitmap
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error darkening bitmap", e)
return null
}
}
}
@@ -1,611 +0,0 @@
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.HandlerThread
import android.os.IBinder
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.Type
import com.anthonyla.paperize.core.blurBitmap
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
/**
* Used in conjunction with [WallpaperService1] to schedule home screen and lock screen separately -- sets lock screen wallpaper
*/
@AndroidEntryPoint
class WallpaperService2: Service() {
private val handleThread = HandlerThread("MyThread2")
private lateinit var workerHandler: Handler
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private var scheduleSeparately: Boolean = false
private var timeInMinutes1: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var timeInMinutes2: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var nextSetTime1: LocalDateTime? = null
private var nextSetTime2: LocalDateTime? = null
private var nextSetTime: LocalDateTime? = null
enum class Actions {
START,
REQUEUE,
UPDATE
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
handleThread.start()
workerHandler = Handler(handleThread.looper)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent != null) {
when (intent.action) {
Actions.START.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
val setHomeOrLock = if (scheduleSeparately) {
when (intent.getIntExtra("type", Type.BOTH.ordinal)) {
Type.HOME.ordinal -> true
Type.LOCK.ordinal -> false
else -> null
}
} else { null }
workerTaskStart(setHomeOrLock)
}
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
workerTaskRequeue()
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
}
}
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
workerHandler.removeCallbacksAndMessages(null)
handleThread.quitSafely()
}
private fun workerTaskStart(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
changeWallpaper(this@WallpaperService2, setHomeOrLock)
if (setHomeOrLock != null && !setHomeOrLock) {
updateCurrentWallpaper(this@WallpaperService2, true)
}
}
stopSelf()
}
}
private fun workerTaskRequeue() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
stopSelf()
}
}
private fun workerTaskUpdate(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@WallpaperService2, setHomeOrLock)
}
stopSelf()
}
}
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(): Notification? {
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
if (nextSetTime != null) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 3, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.next_wallpaper_change, nextSetTime!!.format(formatter)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
return null
}
/**
* 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, setHomeOrLock: Boolean? = null) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
if (!toggled || (!setHome && !setLock)) {
onDestroy()
return
}
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (setHomeOrLock == null) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime2 = nextSetTime1
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHomeOrLock) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong()) }
if (nextSetTime1 == null && nextSetTime2 != null) {
nextSetTime = nextSetTime2
}
else if (nextSetTime1 != null && nextSetTime2 == null) {
nextSetTime = nextSetTime1
}
else {
nextSetTime = if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
}
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
val notification = createNotification()
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
selectedAlbum.let { it ->
if (setHomeOrLock != null) {
var wallpaper = if (setHomeOrLock) it.album.homeWallpapersInQueue.firstOrNull() else it.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) it.album.homeWallpapersInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) it.album.lockWallpapersInQueue.drop(1) else it.album.lockWallpapersInQueue,
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) it.album.homeWallpapersInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) it.album.lockWallpapersInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.lockWallpapersInQueue
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = if (setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.homeWallpapersInQueue,
lockWallpapersInQueue = if (!setHomeOrLock) newWallpaperInQueue.drop(1) else it.album.lockWallpapersInQueue,
currentHomeWallpaper = if (setHomeOrLock) wallpaper else it.album.currentHomeWallpaper,
currentLockWallpaper = if (!setHomeOrLock) wallpaper else it.album.currentLockWallpaper
)
)
)
}
} else { onDestroy() }
}
}
else {
var wallpaper = it.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper }
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper },
currentHomeWallpaper = wallpaper,
currentLockWallpaper = wallpaper,
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = setHomeOrLock,
blur = blur,
blurPercent = blurPercentage
)
) {
selectedAlbum.wallpapers.firstOrNull { it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.drop(1),
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper }
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
} else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = newWallpaperInQueue.drop(1),
currentHomeWallpaper = wallpaper,
currentLockWallpaper = wallpaper
)
)
)
}
} else { onDestroy() }
}
}
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
}
}
private suspend fun updateCurrentWallpaper(context: Context, setHomeOrLock: Boolean? = null) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
onDestroy()
return
}
else {
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.LOCK_WALLPAPER) ?: false
if (!setHome && !setLock) {
onDestroy()
return
}
val scaling = settingsDataStoreImpl.getString(SettingsConstants.WALLPAPER_SCALING)?.let { ScalingConstants.valueOf(it) } ?: ScalingConstants.FILL
val darken = settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false
val darkenPercentage = settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 100
val blur = settingsDataStoreImpl.getBoolean(SettingsConstants.BLUR) ?: false
val blurPercentage = settingsDataStoreImpl.getInt(SettingsConstants.BLUR_PERCENTAGE) ?: 0
selectedAlbum.let { it ->
val wallpaper1 = it.album.currentHomeWallpaper
val wallpaper2 = it.album.currentLockWallpaper
if (wallpaper2 != null && (setHomeOrLock == null || setHomeOrLock == false)) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper2.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = false,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper2 }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.filter { it != wallpaper1 },
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper1 }
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
}
if (wallpaper1 != null && (setHomeOrLock == null || setHomeOrLock == true)) {
if (!setWallpaper(
context = context,
wallpaper = wallpaper1.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
setHome = setHome,
setLock = setLock,
setLockOrHome = true,
blur = blur,
blurPercent = blurPercentage
)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper1 }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
homeWallpapersInQueue = it.album.homeWallpapersInQueue.filter { it != wallpaper1 },
lockWallpapersInQueue = it.album.lockWallpapersInQueue.filter { it != wallpaper1 }
),
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,
darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
setHome: Boolean, setLock: Boolean,
setLockOrHome: Boolean? = null,
blur: Boolean = false,
blurPercent: Int,
): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val imageSize = wallpaper.getImageDimensions(context) ?: return false
val aspectRatio = imageSize.height.toFloat() / imageSize.width.toFloat()
val device = context.resources.displayMetrics
val targetWidth = min(3 * device.widthPixels, imageSize.width)
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSize(targetWidth, targetHeight)
decoder.isMutableRequired = true
}
} catch (e: Exception) {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
}
else {
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
val options = BitmapFactory.Options().apply {
inSampleSize = calculateInSampleSize(imageSize, targetWidth, targetHeight)
inMutable = true
}
BitmapFactory.decodeStream(inputStream, null, options)
}
}
if (bitmap == null) return false
else {
processBitmap(device, bitmap, darken, darkenPercent, scaling, blur, blurPercent)?.let { image ->
when {
setLockOrHome == true -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
setLockOrHome == false -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
setHome && setLock -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM)
setHome -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
setLock -> wallpaperManager.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
else -> {}
}
wallpaperManager.forgetLoadedWallpaper()
image.recycle()
}
bitmap.recycle()
}
return true
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e)
return false
}
}
/**
* Darkens the bitmap by the given percentage and returns it
* 0 - lightest, 100 - darkest
*/
private fun processBitmap(
device: DisplayMetrics,
source: Bitmap, darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
blur: Boolean,
blurPercent: Int
): Bitmap? {
try {
var processedBitmap = source
// 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 && darkenPercent < 100) {
processedBitmap = darkenBitmap(processedBitmap, darkenPercent)
}
// Apply blur effect
if (blur && blurPercent > 0) {
processedBitmap = blurBitmap(processedBitmap, blurPercent)
}
return processedBitmap
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error darkening bitmap", e)
return null
}
}
}