Major refactor of wallpaper changer functionality to allow different albums for lock screen and home screen

This commit is contained in:
Anthonyy232 committed 2024-08-08 01:17:36 -07:00
1 parent 65972a9ae6
commit f76313b998
31 files changed
+1424 -605

No files matched your search

@@ -19,6 +19,7 @@ object SettingsConstants {
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
const val WALLPAPER_CHANGE_INTERVAL_MIN = 1
const val FIRST_LAUNCH = "first_launch"
const val FIRST_SET = "first_set"
const val LAST_SET_TIME = "last_set_time"
@@ -9,10 +9,9 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.anthonyla.paperize.core.SettingsConstants.SETTINGS_DATASTORE
import kotlinx.coroutines.flow.first
import javax.inject.Inject
private val Context.dataStore : DataStore<Preferences> by preferencesDataStore(name = SETTINGS_DATASTORE)
class SettingsDataStoreImpl @Inject constructor (private val context: Context): SettingsDataStore {
class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
override suspend fun putBoolean(key: String, value: Boolean) {
val preferencesKey = booleanPreferencesKey(key)
context.dataStore.edit {
@@ -10,7 +10,8 @@ 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 wallpapersInQueue The wallpapers in the queue
* @param homeWallpapersInQueue The list of home wallpapers in the queue
* @param lockWallpapersInQueue The list of lock wallpapers in the queue
*/
@Entity
data class Album(
@@ -18,5 +19,6 @@ data class Album(
val displayedAlbumName: String,
val coverUri: String?,
val initialized: Boolean = false,
val wallpapersInQueue: List<String> = emptyList(),
val homeWallpapersInQueue: List<String> = emptyList(),
val lockWallpapersInQueue: List<String> = emptyList(),
)
@@ -85,7 +85,7 @@ fun PaperizeApp(
val scope = rememberCoroutineScope()
// React to albumState changes and change selectedAlbum's details to keep it from being stale
LaunchedEffect(albumState) {
LaunchedEffect(albumState.value) {
withContext(Dispatchers.IO) {
albumState.value.albumsWithWallpapers.asSequence().forEach { albumWithWallpapers ->
if (!albumWithWallpapers.album.initialized && (albumWithWallpapers.wallpapers.isNotEmpty() || albumWithWallpapers.folders.isNotEmpty())) {
@@ -102,50 +102,22 @@ fun PaperizeApp(
albumsViewModel.onEvent(AlbumsEvent.DeleteAlbumWithWallpapers(albumWithWallpapers))
}
}
/*selectedState.value.selectedAlbum?.let { selectedAlbum ->
albumState.value.albumsWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName }
?.let { foundAlbum ->
val albumNameHashCode = foundAlbum.album.initialAlbumName.hashCode()
val wallpapers: List<Wallpaper> =
foundAlbum.wallpapers + foundAlbum.folders.flatMap { folder ->
folder.wallpapers.map { wallpaper ->
Wallpaper(
initialAlbumName = foundAlbum.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + albumNameHashCode,
)
}
}
val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet()
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
)
wallpaperScreenViewModel.onEvent(
WallpaperEvent.UpdateSelectedAlbum(
newSelectedAlbum,
null,
settingsState.value.scheduleSeparately
)
)
} ?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
selectedState.value.selectedAlbum?.forEach { selectedAlbum ->
val album = albumState.value.albumsWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName }
if (album != null) {
if (selectedAlbum.album.displayedAlbumName != album.album.displayedAlbumName ||
selectedAlbum.album.coverUri != album.album.coverUri ||
selectedAlbum.wallpapers.size != album.wallpapers.size + album.folders.sumOf { it.wallpapers.size })
{
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(album, selectedAlbum.album.initialAlbumName))
}
}
else {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset(selectedAlbum))
settingsViewModel.onEvent(SettingsEvent.RemoveSelectedAlbumAsName(selectedAlbum.album.initialAlbumName))
scheduler.cancelWallpaperAlarm()
}
}*/
}
}
}
@@ -238,17 +210,36 @@ fun PaperizeApp(
) {
HomeScreen(
albums = albumState.value.albumsWithWallpapers,
animate = settingsState.value.animate,
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
lastSetTime = settingsState.value.lastSetTime,
nextSetTime = settingsState.value.nextSetTime,
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,
homeEnabled = settingsState.value.setHomeWallpaper,
lockEnabled = settingsState.value.setLockWallpaper,
scheduleSeparately = settingsState.value.scheduleSeparately,
blur = settingsState.value.blur,
blurPercentage = settingsState.value.blurPercentage,
currentHomeWallpaper = settingsState.value.currentHomeWallpaper,
currentLockWallpaper = settingsState.value.currentLockWallpaper,
onSettingsClick = { navController.navigate(Settings) },
navigateToAddWallpaperScreen = {
navController.navigate(AddEdit(it))
},
onAlbumViewClick = {
onViewAlbum = {
navController.navigate(AlbumView(it))
},
onScheduleWallpaperChanger = {
if (settingsState.value.enableChanger) {
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
job?.cancel()
job = scope.launch {
delay(1000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
@@ -256,7 +247,12 @@ fun PaperizeApp(
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true
) }
scheduler.scheduleRefresh()
}
}
@@ -300,7 +296,7 @@ fun PaperizeApp(
},
onStop = { lock, home ->
if (selectedState.value.selectedAlbum != null) {
if (!selectedState.value.selectedAlbum.isNullOrEmpty()) {
val notSameAlbum = settingsState.value.homeAlbumName != settingsState.value.lockAlbumName
when {
lock && home -> {
@@ -313,35 +309,55 @@ fun PaperizeApp(
if (notSameAlbum) wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset(selectedState.value.selectedAlbum!!.find { it.album.initialAlbumName == settingsState.value.homeAlbumName}))
}
}
settingsViewModel.onEvent(SettingsEvent.RemoveSelectedAlbum(lock, home))
settingsViewModel.onEvent(SettingsEvent.RemoveSelectedAlbumAsType(lock, home))
scheduler.cancelWallpaperAlarm()
}
},
animate = settingsState.value.animate,
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
lastSetTime = settingsState.value.lastSetTime,
nextSetTime = settingsState.value.nextSetTime,
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,
homeEnabled = settingsState.value.setHomeWallpaper,
lockEnabled = settingsState.value.setLockWallpaper,
scheduleSeparately = settingsState.value.scheduleSeparately,
blur = settingsState.value.blur,
blurPercentage = settingsState.value.blurPercentage,
currentHomeWallpaper = settingsState.value.currentHomeWallpaper,
currentLockWallpaper = settingsState.value.currentLockWallpaper,
onToggleChanger = { enableWallpaperChanger ->
if (selectedState.value.selectedAlbum != null && !settingsState.value.homeAlbumName.isNullOrEmpty() && !settingsState.value.lockAlbumName.isNullOrEmpty()) {
if (!selectedState.value.selectedAlbum.isNullOrEmpty() && !settingsState.value.homeAlbumName.isNullOrEmpty() && !settingsState.value.lockAlbumName.isNullOrEmpty()) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
if (enableWallpaperChanger) {
// update the wallpaper preview in wallpaper screen viewmodel
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
val currentHomeAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.homeAlbumName }
val currentLockAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.lockAlbumName }
when {
settingsState.value.scheduleSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
!settingsState.value.scheduleSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
settingsState.value.setHomeWallpaper -> {
if (currentHomeAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = if (settingsState.value.scheduleSeparately) null else currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
settingsState.value.setLockWallpaper -> {
if (currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = if (settingsState.value.scheduleSeparately) null else currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
}
job?.cancel()
job = scope.launch {
delay(2000)
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
delay(1000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
@@ -353,8 +369,8 @@ fun PaperizeApp(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true)
}
cancelImmediate = true
) }
scheduler.scheduleRefresh()
}
}
@@ -363,40 +379,114 @@ fun PaperizeApp(
},
onSelectAlbum = {album, lock, home ->
val notSameAlbum = settingsState.value.homeAlbumName != settingsState.value.lockAlbumName
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
when {
lock && home -> {
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(album, settingsState.value.homeAlbumName))
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(
album = album,
deleteAlbumName = if (notSameAlbum) settingsState.value.lockAlbumName else null)
)
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))
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(
album = album,
deleteAlbumName = 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))
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(
album = album,
deleteAlbumName = if (notSameAlbum) settingsState.value.homeAlbumName else null)
)
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = album.album.initialAlbumName,
lockAlbumName = null,
))
}
}
job?.cancel()
job = scope.launch {
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(it, null, true, true)}
scheduler.scheduleRefresh()
scope.launch {
delay(1000) // Delay for enableChanger to refresh
if (settingsState.value.enableChanger) {
val currentHomeAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.homeAlbumName }
val currentLockAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.lockAlbumName }
when {
settingsState.value.scheduleSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(
SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull()
?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull()
?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
)
)
}
}
!settingsState.value.scheduleSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(
SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull()
?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull()
?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
)
)
}
}
settingsState.value.setHomeWallpaper -> {
if (currentHomeAlbum != null) {
settingsViewModel.onEvent(
SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull()
?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = if (settingsState.value.scheduleSeparately) null else currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull()
?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
)
)
}
}
settingsState.value.setLockWallpaper -> {
if (currentLockAlbum != null) {
settingsViewModel.onEvent(
SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = if (settingsState.value.scheduleSeparately) null else currentLockAlbum.album.lockWallpapersInQueue.firstOrNull()
?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull()
?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
)
)
}
}
}
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()
}
}
},
onDarkenPercentage = {
@@ -404,7 +494,7 @@ fun PaperizeApp(
if (settingsState.value.enableChanger && settingsState.value.darken) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(3000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
@@ -414,7 +504,7 @@ fun PaperizeApp(
if (settingsState.value.enableChanger && (settingsState.value.darken && settingsState.value.darkenPercentage < 100)) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
@@ -426,25 +516,27 @@ fun PaperizeApp(
if (settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
}
},
onHomeCheckedChange = { setHome -> settingsViewModel.onEvent(SettingsEvent.SetHome(setHome))
if (selectedState.value.selectedAlbum != null && !setHome && !settingsState.value.setLockWallpaper) {
if (!selectedState.value.selectedAlbum.isNullOrEmpty() && !setHome && !settingsState.value.setLockWallpaper) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper("", ""))
selectedState.value.selectedAlbum?.let {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
}
scheduler.cancelWallpaperAlarm()
}
else if (selectedState.value.selectedAlbum != null && (setHome && !settingsState.value.setLockWallpaper) || (!setHome && settingsState.value.setLockWallpaper)) {
else if (!selectedState.value.selectedAlbum.isNullOrEmpty() && (setHome && !settingsState.value.setLockWallpaper) || (!setHome && settingsState.value.setLockWallpaper)) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, setHome, settingsState.value.setLockWallpaper)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
@@ -452,14 +544,19 @@ fun PaperizeApp(
setHome = setHome,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = false,
cancelImmediate = true,
) }
scheduler.scheduleRefresh()
}
}
else if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
else if (!selectedState.value.selectedAlbum.isNullOrEmpty() && settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
@@ -467,6 +564,7 @@ fun PaperizeApp(
onLockCheckedChange = { setLock -> settingsViewModel.onEvent(SettingsEvent.SetLock(setLock))
if (selectedState.value.selectedAlbum!= null && !setLock && !settingsState.value.setHomeWallpaper) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper("", ""))
selectedState.value.selectedAlbum?.let {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset())
}
@@ -476,7 +574,8 @@ fun PaperizeApp(
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, setLock)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
@@ -484,25 +583,65 @@ fun PaperizeApp(
setHome = settingsState.value.setHomeWallpaper,
setLock = setLock
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = false,
cancelImmediate = true
) }
scheduler.scheduleRefresh()
}
}
else if (selectedState.value.selectedAlbum != null && settingsState.value.enableChanger) {
else if (!selectedState.value.selectedAlbum.isNullOrEmpty() && settingsState.value.enableChanger) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
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) {
//update wallpaper preview
if (!selectedState.value.selectedAlbum.isNullOrEmpty() && settingsState.value.enableChanger) {
val currentHomeAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.homeAlbumName }
val currentLockAlbum = selectedState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.lockAlbumName }
when {
changeSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
!changeSeparately && settingsState.value.setHomeWallpaper && settingsState.value.setLockWallpaper -> {
if (currentHomeAlbum != null && currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
settingsState.value.setHomeWallpaper -> {
if (currentHomeAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = currentHomeAlbum.album.homeWallpapersInQueue.firstOrNull() ?: currentHomeAlbum.wallpapers.firstOrNull()?.wallpaperUri,
currentLockWallpaper = null
))
}
}
settingsState.value.setLockWallpaper -> {
if (currentLockAlbum != null) {
settingsViewModel.onEvent(SettingsEvent.SetCurrentWallpaper(
currentHomeWallpaper = null,
currentLockWallpaper = currentLockAlbum.album.lockWallpapersInQueue.firstOrNull() ?: currentLockAlbum.wallpapers.firstOrNull()?.wallpaperUri
))
}
}
}
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.homeInterval,
lockInterval = settingsState.value.lockInterval,
@@ -510,7 +649,12 @@ fun PaperizeApp(
setHome = settingsState.value.setHomeWallpaper,
setLock = settingsState.value.setLockWallpaper
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true)
}
scheduler.scheduleRefresh()
}
}
@@ -520,7 +664,7 @@ fun PaperizeApp(
if (settingsState.value.enableChanger && (settingsState.value.blur && settingsState.value.blurPercentage > 0)) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
@@ -530,7 +674,7 @@ fun PaperizeApp(
if (settingsState.value.enableChanger && settingsState.value.blur) {
job?.cancel()
job = scope.launch {
delay(2000)
delay(3000)
scheduler.updateWallpaper(settingsState.value.scheduleSeparately, settingsState.value.setHomeWallpaper, settingsState.value.setLockWallpaper)
}
}
@@ -692,8 +836,8 @@ fun PaperizeApp(
navController.navigateUp()
albumsViewModel.onEvent(AlbumsEvent.DeleteAlbumWithWallpapers(albumWithWallpaper))
},
onTitleChange = { title, originalAlbumWithWallpaper ->
albumsViewModel.onEvent(AlbumsEvent.ChangeAlbumName(title, originalAlbumWithWallpaper))
onAlbumNameChange = { name, originalAlbumWithWallpaper ->
albumsViewModel.onEvent(AlbumsEvent.ChangeAlbumName(name, originalAlbumWithWallpaper))
},
onSelectionDeleted = {
albumsViewModel.onEvent(AlbumsEvent.RefreshAlbums)
@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
@@ -136,7 +137,7 @@ fun AddAlbumScreen(
modifier = Modifier
.fillMaxSize()
.padding(it),
columns = StaggeredGridCells.Fixed(2),
columns = StaggeredGridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
content = {
@@ -170,32 +171,59 @@ fun AddAlbumScreen(
}
items (items = addAlbumState.value.wallpapers, key = { wallpaper -> wallpaper.wallpaperUri }
) { wallpaper ->
WallpaperItem(
wallpaperUri = wallpaper.wallpaperUri,
itemSelected = addAlbumState.value.selectedWallpapers.contains(wallpaper.wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
addAlbumViewModel.onEvent(
if (!addAlbumState.value.selectedWallpapers.contains(wallpaper.wallpaperUri))
AddAlbumEvent.SelectWallpaper(wallpaper.wallpaperUri)
else {
AddAlbumEvent.RemoveWallpaperFromSelection(wallpaper.wallpaperUri)
}
)
},
onWallpaperViewClick = {
onShowWallpaperView(wallpaper.wallpaperUri)
},
modifier = Modifier.padding(4.dp).animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
),
animate = animate
)
if (animate) {
WallpaperItem(
wallpaperUri = wallpaper.wallpaperUri,
itemSelected = addAlbumState.value.selectedWallpapers.contains(wallpaper.wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
addAlbumViewModel.onEvent(
if (!addAlbumState.value.selectedWallpapers.contains(wallpaper.wallpaperUri))
AddAlbumEvent.SelectWallpaper(wallpaper.wallpaperUri)
else {
AddAlbumEvent.RemoveWallpaperFromSelection(wallpaper.wallpaperUri)
}
)
},
onWallpaperViewClick = {
onShowWallpaperView(wallpaper.wallpaperUri)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
)
)
}
else {
WallpaperItem(
wallpaperUri = wallpaper.wallpaperUri,
itemSelected = addAlbumState.value.selectedWallpapers.contains(wallpaper.wallpaperUri),
selectionMode = selectionMode,
onActivateSelectionMode = { selectionMode = it },
onItemSelection = {
addAlbumViewModel.onEvent(
if (!addAlbumState.value.selectedWallpapers.contains(wallpaper.wallpaperUri))
AddAlbumEvent.SelectWallpaper(wallpaper.wallpaperUri)
else {
AddAlbumEvent.RemoveWallpaperFromSelection(wallpaper.wallpaperUri)
}
)
},
onWallpaperViewClick = {
onShowWallpaperView(wallpaper.wallpaperUri)
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
}
}
}
)
@@ -162,7 +162,6 @@ fun AddAlbumSmallTopBar(
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier.padding(6.dp)
)
}
@@ -44,6 +44,13 @@ class AlbumsViewModel @Inject constructor (
is AlbumsEvent.DeleteAlbumWithWallpapers -> {
viewModelScope.launch(Dispatchers.IO) {
repository.cascadeDeleteAlbum(event.albumWithWallpaperAndFolder.album)
_state.update {
it.copy(
albumsWithWallpapers = it.albumsWithWallpapers.filterNot { albumWithWallpaper ->
albumWithWallpaper.album == event.albumWithWallpaperAndFolder.album
}
)
}
}
}
is AlbumsEvent.ChangeAlbumName -> {
@@ -52,13 +59,22 @@ class AlbumsViewModel @Inject constructor (
repository.updateAlbum(
event.albumWithWallpaperAndFolder.album.copy(displayedAlbumName = event.title)
)
_state.update {
it.copy(
albumsWithWallpapers = it.albumsWithWallpapers.map { albumWithWallpaper ->
if (albumWithWallpaper.album == event.albumWithWallpaperAndFolder.album) {
albumWithWallpaper.copy(
album = albumWithWallpaper.album.copy(displayedAlbumName = event.title)
)
} else {
albumWithWallpaper
}
}
)
}
}
}
}
is AlbumsEvent.RefreshAlbums -> {
updateAlbums()
refreshAlbums()
}
is AlbumsEvent.InitializeAlbum -> {
viewModelScope.launch(Dispatchers.IO) {
repository.updateAlbum(
@@ -66,12 +82,31 @@ class AlbumsViewModel @Inject constructor (
initialized = true
)
)
_state.update {
it.copy(
albumsWithWallpapers = it.albumsWithWallpapers.map { albumWithWallpaper ->
if (albumWithWallpaper.album == event.albumWithWallpaperAndFolder.album) {
albumWithWallpaper.copy(
album = albumWithWallpaper.album.copy(
initialized = true
)
)
} else {
albumWithWallpaper
}
}
)
}
}
}
is AlbumsEvent.RefreshAlbums -> {
updateAlbums()
refreshAlbums()
}
is AlbumsEvent.Reset -> {
viewModelScope.launch(Dispatchers.IO) {
_state.update { AlbumsState() }
repository.deleteAllData()
_state.update { AlbumsState() }
}
}
}
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -11,7 +10,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -26,7 +24,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -39,26 +37,13 @@ fun AlbumItem(
album: Album,
onAlbumViewClick: () -> Unit,
modifier: Modifier = Modifier,
animate: Boolean = true
) {
val context = LocalContext.current
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
}
val showCoverUri by remember { mutableStateOf(album.coverUri != null && isValidUri(context, album.coverUri)) }
Card(
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
modifier = modifier
.fillMaxSize()
.clip(RoundedCornerShape(16.dp)),
modifier = modifier.fillMaxSize(),
shape = RoundedCornerShape(16.dp),
onClick = onAlbumViewClick
) {
@@ -73,15 +58,8 @@ fun AlbumItem(
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(250, 250),
requestSize = IntSize(300, 300),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
},
modifier = Modifier
.aspectRatio(1f)
.clip(RoundedCornerShape(16.dp))
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
import android.content.Context
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.ExperimentalFoundationApi
@@ -21,7 +20,6 @@ import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -44,6 +42,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.isValidUri
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -75,16 +74,6 @@ fun FolderItem(
if (selected) 24.dp else 16.dp
}
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
return try {
uri?.let {
val inputStream = context.contentResolver.openInputStream(it)
inputStream?.close()
}
true
} catch (e: Exception) { false }
}
val showCoverUri by remember { mutableStateOf(folder.coverUri != null && isValidUri(context, folder.coverUri)) }
Card(
@@ -109,7 +98,6 @@ fun FolderItem(
}
}
),
shape = RoundedCornerShape(roundedCornerShapeTransition),
) {
Column(
verticalArrangement = Arrangement.Top,
@@ -122,18 +110,11 @@ fun FolderItem(
imageOptions = ImageOptions(
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
requestSize = IntSize(250, 250),
requestSize = IntSize(300, 300),
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
},
modifier = Modifier
.aspectRatio(0.8f)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.clip(RoundedCornerShape(16.dp))
)
}
if (selectionMode) {
@@ -8,14 +8,13 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.RadioButtonUnchecked
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.surfaceColorAtElevation
@@ -25,23 +24,16 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.times
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.getImageDimensions
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
@@ -54,18 +46,11 @@ fun WallpaperItem(
wallpaperUri: String,
itemSelected: Boolean,
selectionMode: Boolean,
modifier: Modifier = Modifier,
allowHapticFeedback: Boolean = true,
onActivateSelectionMode: (Boolean) -> Unit,
onItemSelection: () -> Unit,
onWallpaperViewClick: () -> Unit,
modifier: Modifier = Modifier,
aspectRatio: Float? = null,
clickable: Boolean = true,
animate: Boolean = true,
darken: Boolean = false,
darkenPercentage: Int? = null,
blur: Boolean = false,
blurPercentage: Int? = null,
scaling: ScalingConstants? = null
) {
val context = LocalContext.current
val haptics = LocalHapticFeedback.current
@@ -90,69 +75,36 @@ fun WallpaperItem(
}
val showUri by remember { mutableStateOf(isValidUri(context, wallpaperUri)) }
val boxModifier = if (clickable) {
modifier
.padding(paddingTransition)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.combinedClickable(
onClick = {
if (!selectionMode) {
onWallpaperViewClick()
} else {
onItemSelection()
}
},
onLongClick = {
if (!selectionMode) {
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onActivateSelectionMode(true)
onItemSelection()
}
Box(
modifier = modifier
.padding(paddingTransition)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
.combinedClickable(
onClick = {
if (!selectionMode) {
onWallpaperViewClick()
} else {
onItemSelection()
}
)
} else {
modifier
.padding(paddingTransition)
.clip(RoundedCornerShape(roundedCornerShapeTransition))
}
Box(modifier = boxModifier) {
},
onLongClick = {
if (!selectionMode) {
if (allowHapticFeedback) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
onActivateSelectionMode(true)
onItemSelection()
}
}
)
) {
if (showUri) {
val dimension = wallpaperUri.toUri().getImageDimensions(context)
val imageAspectRatio = aspectRatio ?: ((dimension?.width?.toFloat() ?: 9f) / (dimension?.height?.toFloat() ?: 19.5f))
GlideImage(
imageModel = { wallpaperUri },
imageOptions = ImageOptions(
contentScale = if (scaling != null) {
when (scaling) {
ScalingConstants.FILL -> ContentScale.FillHeight
ScalingConstants.FIT -> ContentScale.FillWidth
ScalingConstants.STRETCH -> ContentScale.FillBounds
}
} else { ContentScale.Crop },
requestSize = IntSize(250, 250),
requestSize = IntSize(200, 200),
alignment = Alignment.Center,
colorFilter = if (darken && darkenPercentage != null && darkenPercentage < 100) {
ColorFilter.tint(
Color.Black.copy(alpha = (100 - darkenPercentage).toFloat().div(100f)),
BlendMode.Darken
)
} else { null }
),
loading = {
if (animate) {
Box(modifier = Modifier.matchParentSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
},
modifier = Modifier
.aspectRatio(imageAspectRatio)
.background(if (scaling != null) Color.Black else Color.Transparent)
.blur(
if (blur && blurPercentage != null && blurPercentage > 0 ) {
blurPercentage.toFloat().div(100f) * 1.5.dp
} else { 0.dp })
.fillMaxSize()
.clip(RoundedCornerShape(roundedCornerShapeTransition))
)
}
@@ -164,9 +116,9 @@ fun WallpaperItem(
contentDescription = stringResource(R.string.image_is_selected),
modifier = Modifier
.padding(4.dp)
.border(2.dp, bgColor, CircleShape)
.clip(CircleShape)
.background(bgColor)
.border(2.dp, bgColor, CircleShape)
)
} else {
Icon(
@@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
@@ -41,7 +42,7 @@ fun AlbumViewScreen(
onShowWallpaperView: (String) -> Unit,
onShowFolderView: (String?, List<String>) -> Unit,
onDeleteAlbum: () -> Unit,
onTitleChange: (String, AlbumWithWallpaperAndFolder) -> Unit,
onAlbumNameChange: (String, AlbumWithWallpaperAndFolder) -> Unit,
onSelectionDeleted: () -> Unit,
) {
albumViewScreenViewModel.onEvent(AlbumViewEvent.SetSize(album.wallpapers.size + album.folders.size)) // For selectedAll state
@@ -100,7 +101,7 @@ fun AlbumViewScreen(
onBackClick()
},
onDeleteAlbum = onDeleteAlbum,
onTitleChange = { onTitleChange(it, album) },
onTitleChange = { onAlbumNameChange(it, album) },
onSelectAllClick = {
if (!albumState.value.allSelected) albumViewScreenViewModel.onEvent(AlbumViewEvent.SelectAll(album))
else albumViewScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
@@ -132,7 +133,7 @@ fun AlbumViewScreen(
modifier = Modifier
.fillMaxSize()
.padding(it),
columns = StaggeredGridCells.Fixed(2),
columns = StaggeredGridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
content = {
@@ -160,11 +161,11 @@ fun AlbumViewScreen(
.padding(4.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
),
),
animate = true
)
}
@@ -213,14 +214,14 @@ fun AlbumViewScreen(
},
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
)
),
animate = true
)
)
}
else {
@@ -241,8 +242,9 @@ fun AlbumViewScreen(
onWallpaperViewClick = {
onShowWallpaperView(wallpaper.wallpaperUri)
},
modifier = Modifier.padding(4.dp),
animate = false
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
}
}
@@ -32,7 +32,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
@@ -103,7 +102,6 @@ fun AlbumViewTopBar(
Icon(
imageVector = Icons.Default.RadioButtonUnchecked,
contentDescription = stringResource(R.string.select_all_images_for_deletion),
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier.padding(6.dp)
)
}
@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
@@ -42,7 +43,7 @@ fun FolderViewScreen(
modifier = Modifier
.padding(it)
.fillMaxSize(),
columns = StaggeredGridCells.Fixed(2),
columns = StaggeredGridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
content = {
@@ -53,19 +54,22 @@ fun FolderViewScreen(
wallpaperUri = wallpaper,
itemSelected = false,
selectionMode = false,
allowHapticFeedback = false,
onActivateSelectionMode = {},
onItemSelection = {},
onWallpaperViewClick = {
onShowWallpaperView(wallpaper)
},
modifier = Modifier.padding(4.dp).animateItem(
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
.animateItem(
placementSpec = tween(
durationMillis = 800,
delayMillis = 0,
easing = FastOutSlowInEasing
),
),
animate = true
)
)
}
else {
@@ -73,13 +77,15 @@ fun FolderViewScreen(
wallpaperUri = wallpaper,
itemSelected = false,
selectionMode = false,
allowHapticFeedback = false,
onActivateSelectionMode = {},
onItemSelection = {},
onWallpaperViewClick = {
onShowWallpaperView(wallpaper)
},
modifier = Modifier.padding(4.dp),
animate = false
modifier = Modifier
.padding(4.dp)
.size(150.dp, 350.dp)
)
}
}
@@ -44,7 +44,7 @@ fun HomeScreen(
lockEnabled : Boolean,
navigateToAddWallpaperScreen: (String) -> Unit,
nextSetTime: String?,
onAlbumViewClick: (String) -> Unit,
onViewAlbum: (String) -> Unit,
onDarkCheck: (Boolean) -> Unit,
onDarkenPercentage: (Int) -> Unit,
onHomeCheckedChange: (Boolean) -> Unit,
@@ -169,8 +169,7 @@ fun HomeScreen(
else -> LibraryScreen(
albums = albums,
onAddNewAlbumClick = { addAlbumDialog = true },
onViewAlbum = onAlbumViewClick,
animate = animate
onViewAlbum = onViewAlbum,
)
}
}
@@ -26,9 +26,8 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.Al
fun LibraryScreen(
albums: List<AlbumWithWallpaperAndFolder>,
onAddNewAlbumClick: () -> Unit,
onViewAlbum: (String) -> Unit,
animate: Boolean
) {
onViewAlbum: (String) -> Unit
) {
val lazyListState = rememberLazyGridState()
Scaffold(
modifier = Modifier.fillMaxSize(),
@@ -49,7 +48,7 @@ fun LibraryScreen(
LazyVerticalGrid(
state = lazyListState,
modifier = Modifier.fillMaxSize(),
columns = GridCells.Fixed(2),
columns = GridCells.Adaptive(150.dp),
contentPadding = PaddingValues(4.dp, 4.dp),
horizontalArrangement = Arrangement.Start,
content = {
@@ -59,7 +58,6 @@ fun LibraryScreen(
album = album.album,
onAlbumViewClick = { onViewAlbum(album.album.initialAlbumName) },
modifier = Modifier.padding(4.dp),
animate = animate
)
}
}
@@ -18,8 +18,10 @@ sealed class SettingsEvent {
data class SetHome(val home: Boolean): SettingsEvent()
data class SetCurrentHomeWallpaper(val currentHomeWallpaper: String?): SettingsEvent()
data class SetCurrentLockWallpaper(val currentLockWallpaper: String?): SettingsEvent()
data class SetCurrentWallpaper(val currentHomeWallpaper: String?, 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 RemoveSelectedAlbumAsType(val removeLock: Boolean = false, val removeHome: Boolean = false): SettingsEvent()
data class RemoveSelectedAlbumAsName(val albumName: String): SettingsEvent()
data class SetScheduleSeparately(val scheduleSeparately: Boolean): SettingsEvent()
data class SetHomeWallpaperInterval(val interval: Int): SettingsEvent()
data class SetLockWallpaperInterval(val interval: Int): SettingsEvent()
@@ -38,7 +38,7 @@ class SettingsViewModel @Inject constructor (
val darkMode = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DARK_MODE_TYPE) }
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 enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: 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) }
@@ -106,6 +106,7 @@ class SettingsViewModel @Inject constructor (
_state.update {
it.copy(
enableChanger = event.toggle
)
}
}
@@ -120,7 +121,7 @@ class SettingsViewModel @Inject constructor (
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 }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: true }
val enableChanger = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false }
val darkenPercentage = async { settingsDataStoreImpl.getInt(SettingsConstants.DARKEN_PERCENTAGE) ?: 0 }
val darken = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DARKEN) ?: false }
val setHomeWallpaper = async { settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false }
@@ -285,13 +286,20 @@ class SettingsViewModel @Inject constructor (
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
val nextSetTime: String?
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (_state.value.scheduleSeparately) {
val nextSetTime1 = currentTime.plusMinutes(_state.value.homeInterval.toLong())
val nextSetTime2 = currentTime.plusMinutes(_state.value.lockInterval.toLong())
nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)!!.format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, nextSetTime1.toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
}
else {
nextSetTime = currentTime.plusMinutes(_state.value.homeInterval.toLong()).format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_1, currentTime.plusMinutes(_state.value.homeInterval.toLong()).toString())
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, currentTime.plusMinutes(_state.value.lockInterval.toLong()).toString())
}
_state.update {
it.copy(
@@ -395,9 +403,6 @@ class SettingsViewModel @Inject constructor (
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
@@ -411,9 +416,6 @@ class SettingsViewModel @Inject constructor (
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
@@ -422,6 +424,23 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.SetCurrentWallpaper -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.currentLockWallpaper != null) {
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, event.currentLockWallpaper)
}
if (event.currentHomeWallpaper != null) {
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, event.currentHomeWallpaper)
}
_state.update {
it.copy(
currentLockWallpaper = event.currentLockWallpaper ?: it.currentLockWallpaper,
currentHomeWallpaper = event.currentHomeWallpaper ?: it.currentHomeWallpaper
)
}
}
}
is SettingsEvent.SetAlbumName -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.homeAlbumName != null) {
@@ -447,21 +466,77 @@ class SettingsViewModel @Inject constructor (
}
}
is SettingsEvent.RemoveSelectedAlbum -> {
is SettingsEvent.RemoveSelectedAlbumAsType -> {
viewModelScope.launch(Dispatchers.IO) {
if (event.removeHome) {
settingsDataStoreImpl.deleteString(SettingsConstants.HOME_ALBUM_NAME)
if (_state.value.setLockWallpaper && _state.value.setHomeWallpaper) {
if (event.removeLock) {
settingsDataStoreImpl.deleteString(SettingsConstants.LOCK_ALBUM_NAME)
}
if (event.removeHome) {
settingsDataStoreImpl.deleteString(SettingsConstants.HOME_ALBUM_NAME)
}
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_LOCK_WALLPAPER)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_HOME_WALLPAPER)
settingsDataStoreImpl.deleteString(SettingsConstants.LAST_SET_TIME)
settingsDataStoreImpl.deleteString(SettingsConstants.NEXT_SET_TIME)
_state.update {
it.copy(
homeAlbumName = if (event.removeHome) null else it.homeAlbumName,
lockAlbumName = if (event.removeLock) null else it.lockAlbumName,
currentHomeWallpaper = null,
currentLockWallpaper = null,
enableChanger = false,
lastSetTime = null,
nextSetTime = null
)
}
}
if (event.removeLock) {
else {
if (event.removeLock) {
settingsDataStoreImpl.deleteString(SettingsConstants.LOCK_ALBUM_NAME)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_LOCK_WALLPAPER)
}
if (event.removeHome) {
settingsDataStoreImpl.deleteString(SettingsConstants.HOME_ALBUM_NAME)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_HOME_WALLPAPER)
}
_state.update {
it.copy(
homeAlbumName = if (event.removeHome) null else it.homeAlbumName,
lockAlbumName = if (event.removeLock) null else it.lockAlbumName,
currentHomeWallpaper = if (event.removeHome) null else it.currentHomeWallpaper,
currentLockWallpaper = if (event.removeLock) null else it.currentLockWallpaper,
enableChanger = false
)
}
}
}
}
is SettingsEvent.RemoveSelectedAlbumAsName -> {
viewModelScope.launch(Dispatchers.IO) {
var enableChanger = _state.value.enableChanger
if (event.albumName == _state.value.lockAlbumName) {
settingsDataStoreImpl.deleteString(SettingsConstants.LOCK_ALBUM_NAME)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_LOCK_WALLPAPER)
enableChanger = false
}
if (event.albumName == _state.value.homeAlbumName) {
settingsDataStoreImpl.deleteString(SettingsConstants.HOME_ALBUM_NAME)
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_HOME_WALLPAPER)
enableChanger = false
}
settingsDataStoreImpl.putBoolean(SettingsConstants.ENABLE_CHANGER, enableChanger)
_state.update {
it.copy(
homeAlbumName = if (event.removeHome) null else it.homeAlbumName,
lockAlbumName = if (event.removeLock) null else it.lockAlbumName,
enableChanger = false
homeAlbumName = if (event.albumName == _state.value.homeAlbumName) null else it.homeAlbumName,
lockAlbumName = if (event.albumName == _state.value.lockAlbumName) null else it.lockAlbumName,
currentHomeWallpaper = if (event.albumName == _state.value.homeAlbumName) null else it.currentHomeWallpaper,
currentLockWallpaper = if (event.albumName == _state.value.lockAlbumName) null else it.currentLockWallpaper,
enableChanger = enableChanger
)
}
}
}
is SettingsEvent.Reset -> {
@@ -501,7 +576,7 @@ class SettingsViewModel @Inject constructor (
lastSetTime = null,
nextSetTime = null,
animate = true,
enableChanger = true,
enableChanger = false,
darkenPercentage = 100,
darken = false,
wallpaperScaling = ScalingConstants.FILL,
@@ -4,7 +4,8 @@ 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 album: AlbumWithWallpaperAndFolder, val deleteAlbumName: String? = null): WallpaperEvent()
data class UpdateSelectedAlbum(val album: AlbumWithWallpaperAndFolder, val deleteAlbumName: String? = null
): WallpaperEvent()
data class Reset(val album: SelectedAlbum? = null) : WallpaperEvent()
data object Refresh : WallpaperEvent()
}
@@ -80,7 +80,7 @@ fun WallpaperScreen(
blurPercentage: Int
) {
val shouldShowScreen = homeEnabled || lockEnabled
val shouldShowSettings = shouldShowScreen && (homeSelectedAlbum != null || lockSelectedAlbum != null)
val shouldShowSettings = shouldShowScreen && homeSelectedAlbum != null && lockSelectedAlbum != null
val scrollState = rememberScrollState()
val context = LocalContext.current
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
@@ -134,9 +134,9 @@ fun WallpaperScreen(
animate = animate,
enableChanger = enableChanger,
onToggleChanger = {
if (!it) {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
if (!it) {
snackbarHostState.showSnackbar(
message = context.getString(R.string.wallpaper_changer_has_been_disabled),
actionLabel = context.getString(R.string.dismiss),
@@ -184,7 +184,7 @@ fun WallpaperScreen(
}
}
)
if (true) {
if (shouldShowSettings) {
WallpaperPreviewAndScale(
currentHomeWallpaper = currentHomeWallpaper,
currentLockWallpaper = currentLockWallpaper,
@@ -200,13 +200,13 @@ fun WallpaperScreen(
)
CurrentAndNextChange(lastSetTime, nextSetTime)
TimeSliders(
timeInMinutes1 = homeInterval,
timeInMinutes2 = lockInterval,
onTimeChange1 = { days, hours, minutes ->
homeInterval = homeInterval,
lockInterval = lockInterval,
onHomeIntervalChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onHomeTimeChange(totalMinutes)
},
onTimeChange2 = { days, hours, minutes ->
onLockIntervalChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
onLockTimeChange(totalMinutes)
},
@@ -57,7 +57,10 @@ class WallpaperScreenViewModel @Inject constructor (
}
}
val newSelectedAlbum = SelectedAlbum(
album = event.album.album.copy(wallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled()),
album = event.album.album.copy(
lockWallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled(),
homeWallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled()
),
wallpapers = wallpapers
)
repository.upsertSelectedAlbum(newSelectedAlbum)
@@ -8,6 +8,7 @@ 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.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
@@ -74,32 +75,41 @@ fun CurrentSelectedAlbum(
Row {
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.padding(PaddingValues(top = 8.dp, bottom = 8.dp, start = 16.dp, end = 8.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)
)
Row(modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.SpaceBetween) {
Box (modifier = Modifier.weight(1f)) {
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,
)
Spacer(modifier = Modifier.size(8.dp))
Box (modifier = Modifier.weight(1f)) {
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)) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Box(modifier = Modifier.size(48.dp)) {
if (lockSelectedAlbum != null) {
if (showLockCoverUri) {
GlideImage(
@@ -140,31 +150,36 @@ fun CurrentSelectedAlbum(
)
ListItem(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.padding(PaddingValues(top = 8.dp, bottom = 8.dp, start = 8.dp, end = 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)
)
Row(modifier = Modifier.fillMaxSize(), horizontalArrangement = Arrangement.SpaceBetween) {
Box (modifier = Modifier.weight(1f)) {
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,
)
Spacer(modifier = Modifier.size(8.dp))
Box (modifier = Modifier.weight(1f)) {
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)) {
Box(modifier = Modifier.size(48.dp)) {
if (homeSelectedAlbum != null) {
if (showHomeCoverUri) {
GlideImage(
@@ -211,13 +226,7 @@ fun CurrentSelectedAlbum(
modifier = Modifier
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.clip(RoundedCornerShape(16.dp))
.clickable {
if (homeSelectedAlbum != null) {
onToggleChanger(!enableChanger)
} else {
onOpenBottomSheet(true, true)
}
},
.clickable { onOpenBottomSheet(true, true) },
headlineContent = {
Text(
text = homeSelectedAlbum?.album?.displayedAlbumName ?: stringResource(R.string.no_album_selected),
@@ -2,12 +2,12 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.c
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.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
@@ -43,7 +43,10 @@ fun IndividualSchedulingAndToggleRow(
val columnModifier = remember {
if (animate) {
Modifier.animateContentSize(
animationSpec = tween(durationMillis = 200, easing = LinearOutSlowInEasing)
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
} else { Modifier }
}
@@ -76,20 +79,12 @@ fun IndividualSchedulingAndToggleRow(
if (animate) {
AnimatedVisibility(
visible = scheduleSeparately,
enter = expandVertically(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
),
exit = fadeOut(
animationSpec = tween(
durationMillis = 300,
easing = LinearOutSlowInEasing
)
)
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 48.dp)) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp)) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline, thickness = 2.dp)
}
Row(
@@ -98,7 +93,7 @@ fun IndividualSchedulingAndToggleRow(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Enable Wallpaper Changer",
text = stringResource(R.string.enable_wallpaper_changer),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
@@ -118,7 +113,7 @@ fun IndividualSchedulingAndToggleRow(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = "Enable wallpaper changer",
text = stringResource(R.string.enable_wallpaper_changer),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
@@ -0,0 +1,78 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.times
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.core.isValidUri
import com.skydoves.landscapist.ImageOptions
import com.skydoves.landscapist.glide.GlideImage
/**
* A composable that displays a wallpaper for preview
*/
@Composable
fun PreviewItem(
wallpaperUri: String,
darken: Boolean = false,
darkenPercentage: Int? = null,
blur: Boolean = false,
blurPercentage: Int? = null,
scaling: ScalingConstants? = null
) {
val context = LocalContext.current
val showUri by remember { mutableStateOf(isValidUri(context, wallpaperUri)) }
val configuration = LocalConfiguration.current
val screenWidth = configuration.screenWidthDp.dp
val screenHeight = configuration.screenHeightDp.dp
if (showUri) {
GlideImage(
imageModel = { wallpaperUri },
imageOptions = ImageOptions(
contentScale = if (scaling != null) {
when (scaling) {
ScalingConstants.FILL -> ContentScale.FillHeight
ScalingConstants.FIT -> ContentScale.FillWidth
ScalingConstants.STRETCH -> ContentScale.FillBounds
}
} else { ContentScale.Crop },
requestSize = IntSize(300, 300),
alignment = Alignment.Center,
colorFilter = if (darken && darkenPercentage != null && darkenPercentage < 100) {
ColorFilter.tint(
Color.Black.copy(alpha = (100 - darkenPercentage).toFloat().div(100f)),
BlendMode.Darken
)
} else { null },
),
modifier = Modifier
.size(screenWidth * 0.35f, screenHeight * 0.35f)
.clip(RoundedCornerShape(16.dp))
.border(3.dp, Color.Black, RoundedCornerShape(16.dp))
.background(Color.Black)
.blur(
if (blur && blurPercentage != null && blurPercentage > 0 ) {
blurPercentage.toFloat().div(100f) * 1.5.dp
} else { 0.dp })
)
}
}
@@ -44,7 +44,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_MIN
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -54,24 +54,24 @@ import kotlinx.coroutines.launch
*/
@Composable
fun TimeSliders(
timeInMinutes1: Int,
timeInMinutes2: Int,
homeInterval: Int,
lockInterval: Int,
showInterval: Boolean,
animate: Boolean,
onShowIntervalChange: (Boolean) -> Unit,
scheduleSeparately: Boolean,
onTimeChange1: (Int, Int, Int) -> Unit,
onTimeChange2: (Int, Int, Int) -> Unit,
onHomeIntervalChange: (Int, Int, Int) -> Unit,
onLockIntervalChange: (Int, Int, Int) -> Unit,
lockEnabled: Boolean,
homeEnabled: Boolean,
) {
val view = LocalView.current
var days1 by rememberSaveable { mutableFloatStateOf((timeInMinutes1 / (24 * 60)).toFloat()) }
var hours1 by rememberSaveable { mutableFloatStateOf(((timeInMinutes1 % (24 * 60)) / 60).toFloat()) }
var minutes1 by rememberSaveable { mutableFloatStateOf((timeInMinutes1 % 60).toFloat()) }
var days2 by rememberSaveable { mutableFloatStateOf((timeInMinutes2 / (24 * 60)).toFloat()) }
var hours2 by rememberSaveable { mutableFloatStateOf(((timeInMinutes2 % (24 * 60)) / 60).toFloat()) }
var minutes2 by rememberSaveable { mutableFloatStateOf((timeInMinutes2 % 60).toFloat()) }
var days1 by rememberSaveable { mutableFloatStateOf((homeInterval / (24 * 60)).toFloat()) }
var hours1 by rememberSaveable { mutableFloatStateOf(((homeInterval % (24 * 60)) / 60).toFloat()) }
var minutes1 by rememberSaveable { mutableFloatStateOf((homeInterval % 60).toFloat()) }
var days2 by rememberSaveable { mutableFloatStateOf((lockInterval / (24 * 60)).toFloat()) }
var hours2 by rememberSaveable { mutableFloatStateOf(((lockInterval % (24 * 60)) / 60).toFloat()) }
var minutes2 by rememberSaveable { mutableFloatStateOf((lockInterval % 60).toFloat()) }
val scope = rememberCoroutineScope()
val context = LocalView.current
var job by remember { mutableStateOf<Job?>(null) }
@@ -193,13 +193,13 @@ fun TimeSliders(
days1 = newDays
val totalMinute =
(newDays.toInt() * 24 * 60) + (hours1.toInt() * 60) + minutes1.toInt()
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat() - (hours1.toInt() * 60)
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_MIN) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_MIN.toFloat() - (hours1.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange1(newDays.toInt(), hours1.toInt(), minutes1.toInt())
onHomeIntervalChange(newDays.toInt(), hours1.toInt(), minutes1.toInt())
}
},
valueRange = 0f..30f,
@@ -214,13 +214,13 @@ fun TimeSliders(
hours1 = newHours
val totalMinute =
(days1.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes1.toInt()
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat() - (newHours.toInt() * 60)
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_MIN) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_MIN.toFloat() - (newHours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange1(days1.toInt(), newHours.toInt(), minutes1.toInt())
onHomeIntervalChange(days1.toInt(), newHours.toInt(), minutes1.toInt())
}
},
valueRange = 0f..24f,
@@ -233,15 +233,15 @@ fun TimeSliders(
onValueChange = { newMinutes ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
minutes1 =
if (days1.toInt() == 0 && hours1.toInt() == 0 && newMinutes < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat()
if (days1.toInt() == 0 && hours1.toInt() == 0 && newMinutes < WALLPAPER_CHANGE_INTERVAL_MIN) {
WALLPAPER_CHANGE_INTERVAL_MIN.toFloat()
} else {
newMinutes
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange1(days1.toInt(), hours1.toInt(), minutes1.toInt())
onHomeIntervalChange(days1.toInt(), hours1.toInt(), minutes1.toInt())
}
},
valueRange = 0f..60f,
@@ -282,13 +282,13 @@ fun TimeSliders(
days2 = newDays
val totalMinute =
(newDays.toInt() * 24 * 60) + (hours2.toInt() * 60) + minutes2.toInt()
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
minutes2 = WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat() - (hours2.toInt() * 60)
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_MIN) {
minutes2 = WALLPAPER_CHANGE_INTERVAL_MIN.toFloat() - (hours2.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange2(
onLockIntervalChange(
newDays.toInt(),
hours2.toInt(),
minutes2.toInt()
@@ -307,13 +307,13 @@ fun TimeSliders(
hours2 = newHours
val totalMinute =
(days2.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes2.toInt()
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
minutes2 = WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat() - (newHours.toInt() * 60)
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_MIN) {
minutes2 = WALLPAPER_CHANGE_INTERVAL_MIN.toFloat() - (newHours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange2(
onLockIntervalChange(
days2.toInt(),
newHours.toInt(),
minutes2.toInt()
@@ -330,15 +330,15 @@ fun TimeSliders(
onValueChange = { newMinutes ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
minutes2 =
if (days2.toInt() == 0 && hours2.toInt() == 0 && newMinutes < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat()
if (days2.toInt() == 0 && hours2.toInt() == 0 && newMinutes < WALLPAPER_CHANGE_INTERVAL_MIN) {
WALLPAPER_CHANGE_INTERVAL_MIN.toFloat()
} else {
newMinutes
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange2(
onLockIntervalChange(
days2.toInt(),
hours2.toInt(),
minutes2.toInt()
@@ -364,13 +364,13 @@ fun TimeSliders(
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
days1 = newDays
val totalMinute = (newDays.toInt() * 24 * 60) + (hours1.toInt() * 60) + minutes1.toInt()
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat() - (hours1.toInt() * 60)
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_MIN) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_MIN.toFloat() - (hours1.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange1(newDays.toInt(), hours1.toInt(), minutes1.toInt())
onHomeIntervalChange(newDays.toInt(), hours1.toInt(), minutes1.toInt())
}
},
valueRange = 0f..30f,
@@ -384,13 +384,13 @@ fun TimeSliders(
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
hours1 = newHours
val totalMinute = (days1.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes1.toInt()
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat() - (newHours.toInt() * 60)
if (totalMinute < WALLPAPER_CHANGE_INTERVAL_MIN) {
minutes1 = WALLPAPER_CHANGE_INTERVAL_MIN.toFloat() - (newHours.toInt() * 60)
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange1(days1.toInt(), newHours.toInt(), minutes1.toInt())
onHomeIntervalChange(days1.toInt(), newHours.toInt(), minutes1.toInt())
}
},
valueRange = 0f..24f,
@@ -402,15 +402,15 @@ fun TimeSliders(
value = minutes1,
onValueChange = { newMinutes ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
minutes1 = if (days1.toInt() == 0 && hours1.toInt() == 0 && newMinutes < WALLPAPER_CHANGE_INTERVAL_DEFAULT) {
WALLPAPER_CHANGE_INTERVAL_DEFAULT.toFloat()
minutes1 = if (days1.toInt() == 0 && hours1.toInt() == 0 && newMinutes < WALLPAPER_CHANGE_INTERVAL_MIN) {
WALLPAPER_CHANGE_INTERVAL_MIN.toFloat()
} else {
newMinutes
}
job?.cancel()
job = scope.launch {
delay(500)
onTimeChange1(days1.toInt(), hours1.toInt(), minutes1.toInt())
onHomeIntervalChange(days1.toInt(), hours1.toInt(), minutes1.toInt())
}
},
valueRange = 0f..60f,
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
@@ -33,7 +32,6 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.ScalingConstants
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
/**
* SetLockScreenSwitch is a composable that displays a switch to set the wallpaper as the lock screen wallpaper
@@ -97,23 +95,8 @@ fun WallpaperPreviewAndScale(
) {
Text(text = stringResource(R.string.lock_screen), fontWeight = FontWeight.W500)
if (currentLockWallpaper != null) {
WallpaperItem(
PreviewItem(
wallpaperUri = currentLockWallpaper,
itemSelected = false,
selectionMode = false,
onActivateSelectionMode = {},
onItemSelection = {},
onWallpaperViewClick = {},
modifier = Modifier
.padding(4.dp)
.border(
3.dp,
color = Color.Black,
shape = RoundedCornerShape(16.dp)
),
aspectRatio = 9f / 19.5f,
clickable = false,
animate = animate,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling,
@@ -131,23 +114,8 @@ fun WallpaperPreviewAndScale(
) {
Text(text = stringResource(R.string.home), fontWeight = FontWeight.W500)
if (currentHomeWallpaper != null) {
WallpaperItem(
PreviewItem(
wallpaperUri = currentHomeWallpaper,
itemSelected = false,
selectionMode = false,
onActivateSelectionMode = {},
onItemSelection = {},
onWallpaperViewClick = {},
modifier = Modifier
.padding(4.dp)
.border(
3.dp,
color = Color.Black,
shape = RoundedCornerShape(16.dp)
),
aspectRatio = 9f / 19.5f,
clickable = false,
animate = animate,
darken = darken,
darkenPercentage = darkenPercentage,
scaling = scaling,
@@ -99,7 +99,10 @@ class WallpaperAlarmSchedulerImpl (
override fun cancelWallpaperAlarm(cancelLock: Boolean, cancelHome: Boolean) {
if (cancelLock) cancelAlarm(Type.LOCK)
if (cancelHome) cancelAlarm(Type.HOME)
if (cancelLock && cancelHome) cancelAlarm(Type.SINGLE)
if (cancelLock && cancelHome) {
cancelAlarm(Type.SINGLE)
cancelAlarm(Type.REFRESH)
}
}
/**
@@ -111,8 +114,8 @@ class WallpaperAlarmSchedulerImpl (
else -> LocalDateTime.now().plusMinutes(wallpaperAlarmItem.homeInterval.toLong())
}
val intent = Intent(context, WallpaperReceiver::class.java).apply {
putExtra("timeInMinutes1", wallpaperAlarmItem.homeInterval)
putExtra("timeInMinutes2", wallpaperAlarmItem.lockInterval)
putExtra("homeInterval", wallpaperAlarmItem.homeInterval)
putExtra("lockInterval", wallpaperAlarmItem.lockInterval)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
putExtra("setHome", wallpaperAlarmItem.setHome)
@@ -214,12 +217,12 @@ class WallpaperAlarmSchedulerImpl (
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)
}
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)
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.HOME.ordinal)
}
}
}
@@ -232,12 +235,12 @@ class WallpaperAlarmSchedulerImpl (
if (setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
if (setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.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())
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
}
}
}
@@ -257,11 +260,11 @@ class WallpaperAlarmSchedulerImpl (
/**
* 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) {
private fun startService(context: Context, serviceClass: Class<*>, action: String, homeInterval: Int? = null, lockInterval: 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) }
homeInterval?.let { putExtra("homeInterval", it) }
lockInterval?.let { putExtra("lockInterval", it) }
scheduleSeparately?.let { putExtra("scheduleSeparately", it) }
type?.let { putExtra("type", it) }
}
@@ -26,15 +26,24 @@ class WallpaperBootAndChangeReceiver : BroadcastReceiver() {
val scheduler = WallpaperAlarmSchedulerImpl(context)
val toggleChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
if (toggleChanger) {
val timeInMinutes1 = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val timeInMinutes2 = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val homeInterval = settingsDataStoreImpl.getInt(SettingsConstants.HOME_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val lockInterval = settingsDataStoreImpl.getInt(SettingsConstants.LOCK_WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = settingsDataStoreImpl.getBoolean(SettingsConstants.SCHEDULE_SEPARATELY) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val alarmItem = WallpaperAlarmItem(
homeInterval = timeInMinutes1,
lockInterval = timeInMinutes2,
scheduleSeparately = scheduleSeparately
homeInterval = homeInterval,
lockInterval = lockInterval,
scheduleSeparately = scheduleSeparately,
setLock = setLock,
setHome = setHome
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(it, null, true, true)}
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true)
}
}
} catch (e: Exception) {
e.printStackTrace()
@@ -24,8 +24,8 @@ class WallpaperReceiver: BroadcastReceiver() {
WallpaperAlarmSchedulerImpl(context).scheduleRefresh()
}
else {
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 homeInterval = intent?.getIntExtra("homeInterval", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val lockInterval = intent?.getIntExtra("lockInterval", WALLPAPER_CHANGE_INTERVAL_DEFAULT) ?: WALLPAPER_CHANGE_INTERVAL_DEFAULT
val scheduleSeparately = intent?.getBooleanExtra("scheduleSeparately", false) ?: false
val type = intent?.getIntExtra("type", Type.SINGLE.ordinal) ?: Type.SINGLE.ordinal
val setHome = intent?.getBooleanExtra("setHome", false) ?: false
@@ -33,14 +33,14 @@ class WallpaperReceiver: BroadcastReceiver() {
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)
if (setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), homeInterval, lockInterval, scheduleSeparately, type)
if (setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), homeInterval, lockInterval, scheduleSeparately, type)
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), timeInMinutes1, timeInMinutes2, scheduleSeparately, type)
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), homeInterval, lockInterval, scheduleSeparately, type)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), timeInMinutes1, timeInMinutes2, scheduleSeparately, type)
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), homeInterval, lockInterval, scheduleSeparately, type)
}
}
@@ -48,8 +48,8 @@ class WallpaperReceiver: BroadcastReceiver() {
val origin = intent?.getIntExtra("origin", -1)?.takeIf { it != -1 }
WallpaperAlarmSchedulerImpl(context).scheduleWallpaperAlarm(
WallpaperAlarmItem(
homeInterval = timeInMinutes1,
lockInterval = timeInMinutes2,
homeInterval = homeInterval,
lockInterval = lockInterval,
scheduleSeparately = scheduleSeparately,
setHome = setHome,
setLock = setLock
@@ -63,11 +63,11 @@ class WallpaperReceiver: BroadcastReceiver() {
/**
* 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) {
private fun startService(context: Context, serviceClass: Class<*>, action: String, homeInterval: Int? = null, lockInterval: 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) }
homeInterval?.let { putExtra("homeInterval", it) }
lockInterval?.let { putExtra("lockInterval", it) }
scheduleSeparately?.let { putExtra("scheduleSeparately", it) }
type?.let { putExtra("type", it) }
}
@@ -62,14 +62,10 @@ class HomeWallpaperService: Service() {
@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 homeInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var lockInterval: 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
enum class Actions {
START,
REQUEUE,
@@ -91,15 +87,15 @@ class HomeWallpaperService: Service() {
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)
homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
type = intent.getIntExtra("type", Type.SINGLE.ordinal)
//workerTaskStart()
workerTaskStart()
}
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
workerTaskRequeue()
}
@@ -123,7 +119,7 @@ class HomeWallpaperService: Service() {
private fun workerTaskStart() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
if (scheduleSeparately) delay(5000)
delay(1000)
changeWallpaper(this@HomeWallpaperService)
}
stopSelf()
@@ -133,10 +129,10 @@ class HomeWallpaperService: Service() {
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 nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
val nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
val nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)
val notification = createNotification(nextSetTime)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
@@ -144,10 +140,10 @@ class HomeWallpaperService: Service() {
}
}
private fun workerTaskUpdate(setHomeOrLock: Boolean? = null) {
private fun workerTaskUpdate() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@HomeWallpaperService, setHomeOrLock)
updateCurrentWallpaper(this@HomeWallpaperService)
}
stopSelf()
}
@@ -165,14 +161,14 @@ class HomeWallpaperService: Service() {
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(): Notification? {
private fun createNotification(nextSetTime: LocalDateTime?): 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)))
.setContentText(getString(R.string.next_wallpaper_change, nextSetTime.format(formatter)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
@@ -186,34 +182,292 @@ class HomeWallpaperService: Service() {
*/
private suspend fun changeWallpaper(context: Context) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
var selectedAlbum = selectedRepository.getSelectedAlbum().first()
if (selectedAlbum.isEmpty()) {
onDestroy()
return
}
else {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
if (!toggled || (!setHome && !setLock)) {
if (!enableChanger || (!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
val homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: ""
val lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: ""
var homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName }
if (homeAlbum == null) {
onDestroy()
return
}
/*nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
when {
// Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album)
setHome && setLock && scheduleSeparately -> {
val delay = ((homeInterval % lockInterval == 0) || (lockInterval % homeInterval == 0)) && (homeAlbumName == lockAlbumName)
var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
// Reshuffle the wallpapers and pick the first one
val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpapers.firstOrNull()
if (wallpaper == null) {
// Delete invalid album if no valid wallpaper
selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName)
onDestroy()
return
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (delay) {
delay(5000)
selectedAlbum = selectedRepository.getSelectedAlbum().first()
homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName }
delay(5000)
}
if (homeAlbum != null) {
if (success) {
selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
homeAlbum.copy(
album = homeAlbum.album.copy(
homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (delay) {
delay(5000)
selectedAlbum = selectedRepository.getSelectedAlbum().first()
homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName }
delay(5000)
}
if (homeAlbum != null) {
if (success) {
selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
homeAlbum.copy(
album = homeAlbum.album.copy(
homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
}
// Case: Set home and lock screen wallpapers using the same album (home screen album)
setHome && setLock && !scheduleSeparately -> {
var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
// Reshuffle the wallpapers and pick the first one
val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpapers.firstOrNull()
if (wallpaper == null) {
// Delete invalid album if no valid wallpaper
selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName)
onDestroy()
return
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
homeAlbum.copy(
album = homeAlbum.album.copy(
homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
homeAlbum.copy(
album = homeAlbum.album.copy(
homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
// Case: Set home screen wallpaper (home screen album)
setHome -> {
var wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
// Reshuffle the wallpapers and pick the first one
val newWallpapers = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpapers.firstOrNull()
if (wallpaper == null) {
// Delete invalid album if no valid wallpaper
selectedRepository.cascadeDeleteAlbum(homeAlbum.album.initialAlbumName)
onDestroy()
return
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = newWallpapers.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
homeAlbum.copy(
album = homeAlbum.album.copy(
homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(homeAlbum.copy(album = homeAlbum.album.copy(homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_HOME_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = homeAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
homeAlbum.copy(
album = homeAlbum.album.copy(
homeWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = homeAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
}
// Run notification
var nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
var nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
val nextSetTime: LocalDateTime?
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (setHome && setLock && !scheduleSeparately) {
nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong())
nextSetTime1 = currentTime.plusMinutes(homeInterval.toLong())
nextSetTime2 = nextSetTime1
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHome) { nextSetTime1 = currentTime.plusMinutes(timeInMinutes1.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(timeInMinutes2.toLong()) }
if (setHome) { nextSetTime1 = currentTime.plusMinutes(homeInterval.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(lockInterval.toLong()) }
nextSetTime = if (nextSetTime1 == null && nextSetTime2 != null) {
nextSetTime2
}
@@ -226,42 +480,50 @@ class HomeWallpaperService: Service() {
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()
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME_2, nextSetTime2.toString())
val notification = createNotification(nextSetTime)
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) {
/**
* Updates the current wallpaper with current settings
*/
private suspend fun updateCurrentWallpaper(context: Context) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
val selectedAlbum = selectedRepository.getSelectedAlbum().first()
if (selectedAlbum.isEmpty()) {
onDestroy()
return
}
else {
val enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
if (!setHome && !setLock) {
if (!enableChanger || (!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
val currentHomeWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER) ?: ""
setWallpaper(
context = context,
wallpaper = currentHomeWallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in updating", e)
@@ -277,8 +539,6 @@ class HomeWallpaperService: Service() {
darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
setHome: Boolean, setLock: Boolean,
setLockOrHome: Boolean? = null,
blur: Boolean = false,
blurPercent: Int,
): Boolean {
@@ -287,7 +547,7 @@ class HomeWallpaperService: Service() {
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 targetWidth = min(2 * device.widthPixels, imageSize.width)
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
@@ -320,14 +580,7 @@ class HomeWallpaperService: Service() {
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.setBitmap(image, null, true, WallpaperManager.FLAG_SYSTEM)
wallpaperManager.forgetLoadedWallpaper()
image.recycle()
}
@@ -378,6 +631,9 @@ class HomeWallpaperService: Service() {
}
}
/**
* Refreshes the album by deleting invalid wallpapers and updating folder cover uri and wallpapers uri-
*/
private fun refreshAlbum(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
try {
@@ -448,8 +704,6 @@ class HomeWallpaperService: Service() {
selectedRepository.deleteAll()
onDestroy()
}
else {
}
} ?: run { onDestroy() }
}
} catch (e: Exception) {
@@ -18,20 +18,26 @@ import android.os.IBinder
import android.util.DisplayMetrics
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.documentfile.provider.DocumentFile
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.getWallpaperFromFolder
import com.anthonyla.paperize.core.stretchBitmap
import com.anthonyla.paperize.data.settings.SettingsDataStore
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
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import com.lazygeniouz.dfc.file.DocumentFileCompat
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -55,16 +61,15 @@ class LockWallpaperService: Service() {
@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
private var homeInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var lockInterval: Int = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT
private var type = Type.SINGLE.ordinal
enum class Actions {
START,
REQUEUE,
UPDATE
UPDATE,
REFRESH
}
override fun onBind(p0: Intent?): IBinder? {
@@ -81,20 +86,24 @@ class LockWallpaperService: Service() {
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)
homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
//workerTaskStart()
type = intent.getIntExtra("type", Type.SINGLE.ordinal)
workerTaskStart()
}
Actions.REQUEUE.toString() -> {
timeInMinutes1 = intent.getIntExtra("timeInMinutes1", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
timeInMinutes2 = intent.getIntExtra("timeInMinutes2", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
workerTaskRequeue()
}
Actions.UPDATE.toString() -> {
workerTaskUpdate()
}
Actions.REFRESH.toString() -> {
workerTaskRefresh()
}
}
}
return START_NOT_STICKY
@@ -109,10 +118,7 @@ class LockWallpaperService: Service() {
private fun workerTaskStart(setHomeOrLock: Boolean? = null) {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
changeWallpaper(this@LockWallpaperService, setHomeOrLock)
if (setHomeOrLock != null && !setHomeOrLock) {
updateCurrentWallpaper(this@LockWallpaperService, true)
}
changeWallpaper(this@LockWallpaperService)
}
stopSelf()
}
@@ -121,10 +127,10 @@ class LockWallpaperService: Service() {
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 nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
val nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
val nextSetTime = (if (nextSetTime1!!.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2)
val notification = createNotification(nextSetTime)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
@@ -132,10 +138,19 @@ class LockWallpaperService: Service() {
}
}
private fun workerTaskUpdate(setHomeOrLock: Boolean? = null) {
private fun workerTaskUpdate() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
updateCurrentWallpaper(this@LockWallpaperService, setHomeOrLock)
updateCurrentWallpaper(this@LockWallpaperService)
}
stopSelf()
}
}
private fun workerTaskRefresh() {
workerHandler.post {
CoroutineScope(Dispatchers.IO).launch {
refreshAlbum(this@LockWallpaperService)
}
stopSelf()
}
@@ -144,14 +159,14 @@ class LockWallpaperService: Service() {
/**
* Creates a notification for the wallpaper service
*/
private fun createNotification(): Notification? {
private fun createNotification(nextSetTime: LocalDateTime?): 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)))
.setContentText(getString(R.string.next_wallpaper_change, nextSetTime.format(formatter)))
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
@@ -163,85 +178,297 @@ class LockWallpaperService: 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) {
val selectedAlbum = selectedRepository.getSelectedAlbum().first()
if (selectedAlbum.isEmpty()) {
onDestroy()
return
}
else {
val toggled = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val enableChanger = 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)) {
if (!enableChanger || (!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
val lockAlbumName = settingsDataStoreImpl.getString(SettingsConstants.LOCK_ALBUM_NAME) ?: ""
val homeAlbumName = settingsDataStoreImpl.getString(SettingsConstants.HOME_ALBUM_NAME) ?: ""
val homeAlbum = selectedAlbum.find { it.album.initialAlbumName == homeAlbumName }
val lockAlbum = selectedAlbum.find { it.album.initialAlbumName == lockAlbumName }
if (lockAlbum == null) {
onDestroy()
return
}
when {
// Case: Set home and lock screen wallpapers using separate albums (home screen and lock screen album)
setHome && setLock && scheduleSeparately -> {
var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
// Reshuffle the wallpapers and pick the first one
val newWallpapers = lockAlbum.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpapers.firstOrNull()
if (wallpaper == null) {
// Delete invalid album if no valid wallpaper
selectedRepository.cascadeDeleteAlbum(lockAlbum.album.initialAlbumName)
onDestroy()
return
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = newWallpapers.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
lockAlbum.copy(
album = lockAlbum.album.copy(
lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
lockAlbum.copy(
album = lockAlbum.album.copy(
lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
if (homeInterval != lockInterval) {
wallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_HOME_WALLPAPER)
if (!wallpaper.isNullOrEmpty()) {
setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
}
}
}
// Case: Set home and lock screen wallpapers using the same album (home screen album)
setHome && setLock && !scheduleSeparately -> {
if (homeAlbum == null) {
onDestroy()
return
}
val wallpaper = homeAlbum.album.homeWallpapersInQueue.firstOrNull()
if (wallpaper != null) {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString())
}
}
}
// Case: Set lock screen wallpaper (lock screen album)
setLock -> {
var wallpaper = lockAlbum.album.lockWallpapersInQueue.firstOrNull()
if (wallpaper == null) {
// Reshuffle the wallpapers and pick the first one
val newWallpapers = lockAlbum.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpapers.firstOrNull()
if (wallpaper == null) {
// Delete invalid album if no valid wallpaper
selectedRepository.cascadeDeleteAlbum(lockAlbum.album.initialAlbumName)
onDestroy()
return
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = newWallpapers.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
lockAlbum.copy(
album = lockAlbum.album.copy(
lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
else {
val success = setWallpaper(
context = context,
wallpaper = wallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
if (success) {
selectedRepository.upsertSelectedAlbum(lockAlbum.copy(album = lockAlbum.album.copy(lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.drop(1))))
settingsDataStoreImpl.putString(SettingsConstants.CURRENT_LOCK_WALLPAPER, wallpaper.toString())
}
else {
val wallpaperToDelete = lockAlbum.wallpapers.find { it.wallpaperUri == wallpaper }
if (wallpaperToDelete != null) {
albumRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.deleteWallpaper(wallpaperToDelete)
selectedRepository.upsertSelectedAlbum(
lockAlbum.copy(
album = lockAlbum.album.copy(
lockWallpapersInQueue = lockAlbum.album.lockWallpapersInQueue.filterNot { it == wallpaper }
),
wallpapers = lockAlbum.wallpapers.filterNot { it.wallpaperUri == wallpaper }
)
)
}
}
}
}
}
// Run notification
if (homeInterval != lockInterval) {
var nextSetTime1 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_1))
var nextSetTime2 = LocalDateTime.parse(settingsDataStoreImpl.getString(SettingsConstants.NEXT_SET_TIME_2))
val nextSetTime: LocalDateTime?
val formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
val currentTime = LocalDateTime.now()
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, currentTime.format(formatter))
if (setHome && setLock && !scheduleSeparately) {
nextSetTime1 = currentTime.plusMinutes(homeInterval.toLong())
nextSetTime2 = nextSetTime1
nextSetTime = nextSetTime1
nextSetTime?.let { settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, it.format(formatter)) }
}
else {
if (setHome) { nextSetTime1 = currentTime.plusMinutes(homeInterval.toLong()) }
else { nextSetTime2 = currentTime.plusMinutes(lockInterval.toLong()) }
nextSetTime = if (nextSetTime1 == null && nextSetTime2 != null) {
nextSetTime2
}
else if (nextSetTime1 != null && nextSetTime2 == null) {
nextSetTime1
}
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())
val notification = createNotification(nextSetTime)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification?.let { notificationManager.notify(1, it) }
}
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in changing wallpaper", e)
}
}
private suspend fun updateCurrentWallpaper(context: Context, setHomeOrLock: Boolean? = null) {
/**
* Updates the current wallpaper with current settings
*/
private suspend fun updateCurrentWallpaper(context: Context) {
try {
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum == null) {
val selectedAlbum = selectedRepository.getSelectedAlbum().first()
if (selectedAlbum.isEmpty()) {
onDestroy()
return
}
else {
val enableChanger = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_CHANGER) ?: false
val setHome = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_HOME_WALLPAPER) ?: false
val setLock = settingsDataStoreImpl.getBoolean(SettingsConstants.ENABLE_LOCK_WALLPAPER) ?: false
if (!setHome && !setLock) {
if (!enableChanger || (!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
val currentLockWallpaper = settingsDataStoreImpl.getString(SettingsConstants.CURRENT_LOCK_WALLPAPER) ?: ""
setWallpaper(
context = context,
wallpaper = currentLockWallpaper.toUri(),
darken = darken,
darkenPercent = darkenPercentage,
scaling = scaling,
blur = blur,
blurPercent = blurPercentage
)
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error in updating", e)
@@ -257,8 +484,6 @@ class LockWallpaperService: Service() {
darken: Boolean,
darkenPercent: Int,
scaling: ScalingConstants,
setHome: Boolean, setLock: Boolean,
setLockOrHome: Boolean? = null,
blur: Boolean = false,
blurPercent: Int,
): Boolean {
@@ -267,7 +492,7 @@ class LockWallpaperService: Service() {
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 targetWidth = min(2 * device.widthPixels, imageSize.width)
val targetHeight = (targetWidth * aspectRatio).toInt()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
@@ -300,20 +525,13 @@ class LockWallpaperService: Service() {
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.setBitmap(image, null, true, WallpaperManager.FLAG_LOCK)
wallpaperManager.forgetLoadedWallpaper()
image.recycle()
}
bitmap.recycle()
return true
}
return true
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error setting wallpaper", e)
return false
@@ -357,4 +575,85 @@ class LockWallpaperService: Service() {
return null
}
}
/**
* Refreshes the album by deleting invalid wallpapers and updating folder cover uri and wallpapers uri-
*/
private fun refreshAlbum(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
try {
var albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first()
albumWithWallpapers.forEach { albumWithWallpaper ->
// Delete wallpaper if the URI is invalid
val invalidWallpapers = albumWithWallpaper.wallpapers.filterNot { wallpaper ->
val file = DocumentFileCompat.fromSingleUri(context, wallpaper.wallpaperUri.toUri())
file?.exists() == true
}
if (invalidWallpapers.isNotEmpty()) {
albumRepository.deleteWallpaperList(invalidWallpapers)
}
// Update folder cover uri and wallpapers uri
albumWithWallpaper.folders.forEach { folder ->
try {
DocumentFileCompat.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory()) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
} catch (e: Exception) {
DocumentFile.fromTreeUri(context, folder.folderUri.toUri())?.let { folderDirectory ->
if (!folderDirectory.isDirectory) {
albumRepository.deleteFolder(folder)
} else {
val wallpapers = getWallpaperFromFolder(folder.folderUri, context)
val folderCoverFile = folder.coverUri?.let { DocumentFileCompat.fromSingleUri(context, it.toUri()) }
val folderCover = folderCoverFile?.takeIf { it.exists() }?.uri?.toString() ?: wallpapers.randomOrNull()
albumRepository.updateFolder(folder.copy(coverUri = folderCover, wallpapers = wallpapers))
}
}
}
}
// Delete empty albums
if (albumWithWallpaper.wallpapers.isEmpty() && albumWithWallpaper.folders.all { it.wallpapers.isEmpty() }) {
albumRepository.deleteAlbum(albumWithWallpaper.album)
}
}
// Update selected album
albumWithWallpapers = albumRepository.getAlbumsWithWallpaperAndFolder().first()
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
if (selectedAlbum != null) {
albumWithWallpapers.find { it.album.initialAlbumName == selectedAlbum.album.initialAlbumName }
?.let { foundAlbum ->
val albumNameHashCode = foundAlbum.album.initialAlbumName.hashCode()
val wallpapers: List<Wallpaper> =
foundAlbum.wallpapers + foundAlbum.folders.flatMap { folder ->
folder.wallpapers.map { wallpaper ->
Wallpaper(
initialAlbumName = foundAlbum.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaper.hashCode() + albumNameHashCode,
)
}
}
val wallpapersUri = wallpapers.map { it.wallpaperUri }.toSet()
if (wallpapersUri.isEmpty()) {
selectedRepository.deleteAll()
onDestroy()
}
} ?: run { onDestroy() }
}
} catch (e: Exception) {
Log.e("PaperizeWallpaperChanger", "Error refreshing album", e)
}
}
}
}
+1
View File
@@ -159,4 +159,5 @@
<string name="change_next_short">Change wallpaper</string>
<string name="change_next_long">Change to the next wallpaper in the album</string>
<string name="cannot_change_wallpaper">Cannot change wallpaper</string>
<string name="enable_wallpaper_changer">Enable Wallpaper Changer</string>
</resources>