Refactored app flow and album logic

This commit is contained in:
Anthony La committed 2025-01-24 12:07:59 -08:00
1 parent a8989b0810
commit 9be3a9c6d3
21 files changed
+639 -554

No files matched your search

@@ -419,26 +419,21 @@ suspend fun getWallpaperFromFolder(folderUri: String, context: Context): List<Wa
}
/**
* Get the last modified date of a folder
* @param folderUri URI of the folder
* @param context Android context
* Get the folder name from the folder URI
*/
suspend fun getFolderLastModified(folderUri: String, context: Context): Long = withContext(Dispatchers.IO) {
val contentResolver = context.contentResolver
val projection = arrayOf(
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
)
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
folderUri.toUri(),
DocumentsContract.getTreeDocumentId(folderUri.toUri())
)
val cursor = contentResolver.query(childrenUri, projection, null, null, null)
cursor?.use {
if (it.moveToFirst()) {
return@use it.getLong(it.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED))
suspend fun getFolderMetadata(folderUri: String, context: Context): Metadata = withContext(Dispatchers.IO) {
return@withContext try {
val uri = folderUri.toUri()
try {
val file = DocumentFileCompat.fromTreeUri(context, uri)
Metadata(file?.name?.substringBeforeLast('.', file.name).toString(), file?.lastModified ?: 0)
} catch (_: Exception) {
val file = DocumentFile.fromTreeUri(context, uri)
Metadata(file?.name?.substringBeforeLast('.', file.name.toString()) ?: "", file?.lastModified() ?: 0)
}
} catch (_: Exception) {
Metadata("", 0)
}
return@withContext 0
}
/**
@@ -451,13 +446,13 @@ suspend fun getImageMetadata(context: Context, uriString: String): Metadata = wi
val uri = uriString.toUri()
try {
val file = DocumentFileCompat.fromSingleUri(context, uri)
return@withContext Metadata(file?.name?.substringBeforeLast('.', file.name).toString(), file?.lastModified ?: 0)
Metadata(file?.name?.substringBeforeLast('.', file.name).toString(), file?.lastModified ?: 0)
} catch (_: Exception) {
val file = DocumentFile.fromSingleUri(context, uri)
return@withContext Metadata(file?.name?.substringBeforeLast('.', file.name.toString()) ?: "", file?.lastModified() ?: 0)
Metadata(file?.name?.substringBeforeLast('.', file.name.toString()) ?: "", file?.lastModified() ?: 0)
}
} catch (_: Exception) {
return@withContext Metadata("", 0)
Metadata("", 0)
}
}
@@ -482,23 +477,12 @@ suspend fun findFirstValidUri(
return@withContext null
}
/**
* Get the folder name from the folder URI
*/
suspend fun getFolderNameFromUri(folderUri: String, context: Context): String? = withContext(Dispatchers.IO) {
return@withContext try {
DocumentFileCompat.fromTreeUri(context, folderUri.toUri())?.name
} catch (_: Exception) {
DocumentFile.fromTreeUri(context, folderUri.toUri())?.name
}
}
/**
* Check if a URI is valid
*/
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.decompress("content://com.android.externalstorage.documents/")?.toUri()
if (uri == null) { return false }
?: return false
return try {
DocumentFileCompat.fromSingleUri(context, uri)?.exists() ?: false
} catch (_: Exception) {
@@ -506,9 +490,11 @@ fun isValidUri(context: Context, uriString: String?): Boolean {
}
}
/**
* Check if a URI is a directory
*/
fun isDirectory(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
if (uri == null) { return false }
val uri = uriString?.toUri() ?: return false
return try {
DocumentFileCompat.fromSingleUri(context, uri)?.isDirectory() ?: false
} catch (_: Exception) {
@@ -20,20 +20,22 @@ import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.core.animation.doOnEnd
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.core.Type
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
@@ -42,7 +44,6 @@ import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmSchedulerImpl
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
@@ -51,6 +52,7 @@ import javax.inject.Inject
class MainActivity : ComponentActivity() {
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private val settingsViewModel: SettingsViewModel by viewModels()
private val context = this
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge(
@@ -79,9 +81,11 @@ class MainActivity : ComponentActivity() {
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
val scheduler = WallpaperAlarmSchedulerImpl(context)
LifecycleEventEffect(Lifecycle.Event.ON_CREATE) {
lifecycleScope.launch {
var hasScheduleRun by remember { mutableStateOf(false) }
LaunchedEffect(settingsState.value) {
if (!hasScheduleRun && settingsState.value.initialized) {
handleWallpaperScheduling(settingsState.value, scheduler)
hasScheduleRun = true
}
}
@@ -38,6 +38,7 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.notifications_scree
import com.anthonyla.paperize.feature.wallpaper.presentation.privacy_screen.PrivacyScreen
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsScreen
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortViewModel
@@ -58,6 +59,7 @@ import com.anthonyla.paperize.feature.wallpaper.util.navigation.WallpaperView
import com.anthonyla.paperize.feature.wallpaper.util.navigation.animatedScreen
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmSchedulerImpl
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -82,7 +84,6 @@ fun PaperizeApp(
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
val sortState = sortViewModel.state.collectAsStateWithLifecycle()
val folderState = folderViewModel.state.collectAsStateWithLifecycle()
albumsViewModel.onEvent(AlbumsEvent.Refresh)
NavHost(
navController = navController,
@@ -124,45 +125,32 @@ fun PaperizeApp(
onHomeTimeChange = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetHomeWallpaperInterval(timeInMinutes))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
delay(3000)
val alarmItem = WallpaperAlarmItem(
homeInterval = timeInMinutes,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.value.scheduleSettings.scheduleSeparately,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{scheduler.updateWallpaperAlarm(it)}
scheduler.scheduleRefresh()
}
job = scope.updateWallpaperAlarm(
job = job,
settingsState = settingsState.value.copy(
scheduleSettings = settingsState.value.scheduleSettings.copy(
homeInterval = timeInMinutes
)
),
scheduler = scheduler
)
}
},
onLockTimeChange = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetLockWallpaperInterval(timeInMinutes))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
delay(3000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = timeInMinutes,
scheduleSeparately = settingsState.value.scheduleSettings.scheduleSeparately,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{scheduler.updateWallpaperAlarm(it)}
scheduler.scheduleRefresh()
}
job = scope.updateWallpaperAlarm(
job = job,
settingsState = settingsState.value.copy(
scheduleSettings = settingsState.value.scheduleSettings.copy(
lockInterval = timeInMinutes
)
),
scheduler = scheduler
)
}
},
onStop = { lock, home ->
onDeselect = { lock, home ->
if (albumState.value.selectedAlbum.isNotEmpty()) {
val notSameAlbum = settingsState.value.wallpaperSettings.homeAlbumName != settingsState.value.wallpaperSettings.lockAlbumName
when {
@@ -194,116 +182,105 @@ fun PaperizeApp(
if (albumState.value.selectedAlbum.isNotEmpty() && !settingsState.value.wallpaperSettings.homeAlbumName.isNullOrEmpty() && !settingsState.value.wallpaperSettings.lockAlbumName.isNullOrEmpty()) {
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
if (enableWallpaperChanger) {
job?.cancel()
job = scope.launch {
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.value.scheduleSettings.scheduleSeparately,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
) }
scheduler.scheduleRefresh()
}
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
enableChanger = true
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler,
refreshNextTime = true
)
}
else { scheduler.cancelWallpaperAlarm() }
}
},
onSelectAlbum = { album, lock, home ->
val notSameAlbum = settingsState.value.wallpaperSettings.homeAlbumName != settingsState.value.wallpaperSettings.lockAlbumName
when {
lock && home -> {
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = album.album.initialAlbumName,
lockAlbumName = album.album.initialAlbumName,
))
albumsViewModel.onEvent(AlbumsEvent.AddSelectedAlbum(
album = album,
deselectAlbumName = if (notSameAlbum) settingsState.value.wallpaperSettings.lockAlbumName else null)
)
}
lock -> {
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = null,
lockAlbumName = album.album.initialAlbumName,
))
albumsViewModel.onEvent(AlbumsEvent.AddSelectedAlbum(
album = album,
deselectAlbumName = if (notSameAlbum) settingsState.value.wallpaperSettings.lockAlbumName else null)
)
}
home -> {
settingsViewModel.onEvent(SettingsEvent.SetAlbumName(
homeAlbumName = album.album.initialAlbumName,
lockAlbumName = null,
))
albumsViewModel.onEvent(AlbumsEvent.AddSelectedAlbum(
album = album,
deselectAlbumName = if (notSameAlbum) settingsState.value.wallpaperSettings.homeAlbumName else null)
)
}
val currentSettings = settingsState.value.wallpaperSettings
val albumName = album.album.initialAlbumName
val notSameAlbum = currentSettings.homeAlbumName != currentSettings.lockAlbumName
val newHomeAlbum = if (home) albumName else null
val newLockAlbum = if (lock) albumName else null
settingsViewModel.onEvent(SettingsEvent.SetAlbum(
homeAlbumName = newHomeAlbum,
lockAlbumName = newLockAlbum
))
val deselectName = when {
notSameAlbum && home -> currentSettings.homeAlbumName
notSameAlbum && lock -> currentSettings.lockAlbumName
else -> null
}
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
scope.launch {
delay(1000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.value.scheduleSettings.scheduleSeparately,
setHome = home,
setLock = lock,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
albumsViewModel.onEvent(AlbumsEvent.AddSelectedAlbum(
album = album,
deselectAlbumName = deselectName
))
val shouldSchedule = (home && !currentSettings.lockAlbumName.isNullOrEmpty()) ||
(lock && !currentSettings.homeAlbumName.isNullOrEmpty()) ||
(lock && home)
if (shouldSchedule) {
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = currentSettings.copy(
homeAlbumName = newHomeAlbum ?: currentSettings.homeAlbumName,
lockAlbumName = newLockAlbum ?: currentSettings.lockAlbumName
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler,
refreshNextTime = true,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
)
alarmItem.let {
scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
)
}
scheduler.scheduleRefresh()
}
},
onDarkenPercentage = { home, lock ->
settingsViewModel.onEvent(SettingsEvent.SetDarkenPercentage(home, lock))
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.darken) {
job?.cancel()
job = scope.launch {
delay(3000)
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
lockDarkenPercentage = lock,
homeDarkenPercentage = home
)
),
scheduler = scheduler
)
}
},
onDarkCheck = {
settingsViewModel.onEvent(SettingsEvent.SetDarken(it))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
darken = it
)
),
scheduler = scheduler
)
}
},
onScalingChange = {
if (settingsState.value.wallpaperSettings.wallpaperScaling != it) {
settingsViewModel.onEvent(SettingsEvent.SetWallpaperScaling(it))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
wallpaperScaling = it
)
),
scheduler = scheduler
)
}
}
},
@@ -314,49 +291,33 @@ fun PaperizeApp(
albumState.value.selectedAlbum.let { albumsViewModel.onEvent(AlbumsEvent.Reset) }
scheduler.cancelWallpaperAlarm()
}
else if (albumState.value.selectedAlbum.isNotEmpty() && (setHome && !settingsState.value.wallpaperSettings.setLockWallpaper) || (!setHome && settingsState.value.wallpaperSettings.setLockWallpaper)) {
else if (albumState.value.selectedAlbum.isNotEmpty() && ((setHome && !settingsState.value.wallpaperSettings.setLockWallpaper) || (!setHome && settingsState.value.wallpaperSettings.setLockWallpaper))) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
/*if (!setHome && settingsState.value.wallpaperSettings.setLockWallpaper) {
val homeAlbum = albumState.value.selectedAlbum?.find { it.album.initialAlbumName == settingsState.value.wallpaperSettings.homeAlbumName }
if (homeAlbum != null) {
albumsViewModel.onEvent(AlbumsEvent.UpdateSelectedAlbum(
album = homeAlbum.copy(
album = homeAlbum.album.copy(
lockWallpapersInQueue = homeAlbum.album.homeWallpapersInQueue,
homeWallpapersInQueue = homeAlbum.wallpapers.map { it.wallpaperUri }.shuffled()
)
),
))
}
}
delay(1000)*/
scheduler.updateWallpaper(false, setHome, settingsState.value.wallpaperSettings.setLockWallpaper)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = false,
setHome = setHome,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = false,
cancelImmediate = true,
firstLaunch = true
) }
scheduler.scheduleRefresh()
}
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
setHomeWallpaper = setHome
),
scheduleSettings = settingsState.value.scheduleSettings.copy(
scheduleSeparately = false
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
)
}
else if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, setHome, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
setHomeWallpaper = setHome
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
)
}
},
onLockCheckedChange = { setLock ->
@@ -368,158 +329,165 @@ fun PaperizeApp(
}
scheduler.cancelWallpaperAlarm()
}
else if ((setLock && !settingsState.value.wallpaperSettings.setHomeWallpaper) || (!setLock && settingsState.value.wallpaperSettings.setHomeWallpaper)) {
else if (albumState.value.selectedAlbum.isNotEmpty() && ((setLock && !settingsState.value.wallpaperSettings.setHomeWallpaper) || (!setLock && settingsState.value.wallpaperSettings.setHomeWallpaper))) {
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
job?.cancel()
job = scope.launch {
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, setLock)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = false,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = setLock,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{ scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = false,
cancelImmediate = true,
firstLaunch = true
) }
scheduler.scheduleRefresh()
}
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
setLockWallpaper = setLock
),
scheduleSettings = settingsState.value.scheduleSettings.copy(
scheduleSeparately = false
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
)
}
else if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
delay(1000)
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
setLockWallpaper = setLock
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler
)
}
},
onScheduleSeparatelyChange = { changeSeparately ->
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(changeSeparately))
if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
delay(1000)
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = changeSeparately,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.value.scheduleSettings.changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = it,
origin = null,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
) }
scheduler.scheduleRefresh()
}
job = scope.scheduleWallpaperUpdate(
job = job,
settingsState = settingsState.value.copy(
scheduleSettings = settingsState.value.scheduleSettings.copy(
scheduleSeparately = changeSeparately
)
),
settingsViewModel = settingsViewModel,
scheduler = scheduler,
changeImmediate = true,
cancelImmediate = true,
firstLaunch = true
)
}
},
onBlurChange = {
settingsViewModel.onEvent(SettingsEvent.SetBlur(it))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
blur = it
)
),
scheduler = scheduler
)
}
},
onBlurPercentageChange = { home, lock ->
settingsViewModel.onEvent(SettingsEvent.SetBlurPercentage(home, lock))
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.blur) {
job?.cancel()
job = scope.launch {
delay(3000)
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
lockBlurPercentage = lock,
homeBlurPercentage = home
)
),
scheduler = scheduler
)
}
},
onVignetteChange = {
settingsViewModel.onEvent(SettingsEvent.SetVignette(it))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
vignette = it
)
),
scheduler = scheduler
)
}
},
onVignettePercentageChange = { home, lock ->
settingsViewModel.onEvent(SettingsEvent.SetVignettePercentage(home, lock))
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.vignette) {
job?.cancel()
job = scope.launch {
delay(3000)
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
lockVignettePercentage = lock,
homeVignettePercentage = home
)
),
scheduler = scheduler
)
}
},
onGrayscaleChange = {
settingsViewModel.onEvent(SettingsEvent.SetGrayscale(it))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
grayscale = it
)
),
scheduler = scheduler
)
}
},
onGrayscalePercentageChange = { home, lock ->
settingsViewModel.onEvent(SettingsEvent.SetGrayscalePercentage(home, lock))
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.grayscale) {
job?.cancel()
job = scope.launch {
delay(3000)
scheduler.updateWallpaper(settingsState.value.scheduleSettings.scheduleSeparately, settingsState.value.wallpaperSettings.setHomeWallpaper, settingsState.value.wallpaperSettings.setLockWallpaper)
}
job = scope.updateWallpaper(
job = job,
settingsState = settingsState.value.copy(
effectSettings = settingsState.value.effectSettings.copy(
lockGrayscalePercentage = lock,
homeGrayscalePercentage = home
)
),
scheduler = scheduler
)
}
},
onStartTimeChange = { time ->
settingsViewModel.onEvent(SettingsEvent.SetStartTime(time.hour, time.minute))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.value.scheduleSettings.scheduleSeparately,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = true,
startTime = Pair(time.hour, time.minute)
)
alarmItem.let{scheduler.updateWallpaperAlarm(it, true)}
scheduler.scheduleRefresh()
}
job = scope.updateWallpaperAlarm(
job = job,
settingsState = settingsState.value.copy(
scheduleSettings = settingsState.value.scheduleSettings.copy(
startTime = Pair(time.hour, time.minute))
),
scheduler = scheduler
)
}
},
onChangeStartTimeToggle = { changeStartTime ->
settingsViewModel.onEvent(SettingsEvent.SetChangeStartTime(changeStartTime))
if (settingsState.value.wallpaperSettings.enableChanger) {
job?.cancel()
job = scope.launch {
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.value.scheduleSettings.homeInterval,
lockInterval = settingsState.value.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.value.scheduleSettings.scheduleSeparately,
setHome = settingsState.value.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.value.wallpaperSettings.setLockWallpaper,
changeStartTime = changeStartTime,
startTime = settingsState.value.scheduleSettings.startTime
)
alarmItem.let{scheduler.updateWallpaperAlarm(it, true)}
scheduler.scheduleRefresh()
}
job = scope.updateWallpaperAlarm(
job = job,
settingsState = settingsState.value.copy(
scheduleSettings = settingsState.value.scheduleSettings.copy(
changeStartTime = changeStartTime
)
),
scheduler = scheduler
)
}
},
)
@@ -700,4 +668,86 @@ fun PaperizeApp(
)
}
}
}
private fun CoroutineScope.scheduleWallpaperUpdate(
job: Job?,
settingsState: SettingsState,
settingsViewModel: SettingsViewModel,
scheduler: WallpaperAlarmSchedulerImpl,
refreshNextTime: Boolean = false,
changeImmediate: Boolean = true,
cancelImmediate: Boolean = true,
firstLaunch: Boolean = true,
origin: Int? = null,
delay: Long = 0L
): Job {
job?.cancel()
return launch {
if (delay > 0) delay(delay)
if (refreshNextTime) {
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
}
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.scheduleSettings.homeInterval,
lockInterval = settingsState.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.scheduleSettings.scheduleSeparately,
setHome = settingsState.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.scheduleSettings.changeStartTime,
startTime = settingsState.scheduleSettings.startTime
)
scheduler.scheduleWallpaperAlarm(
wallpaperAlarmItem = alarmItem,
origin = origin,
changeImmediate = changeImmediate,
cancelImmediate = cancelImmediate,
firstLaunch = firstLaunch
)
scheduler.scheduleRefresh()
}
}
private fun CoroutineScope.updateWallpaperAlarm(
job: Job?,
settingsState: SettingsState,
scheduler: WallpaperAlarmSchedulerImpl,
firstLaunch: Boolean = true,
): Job {
job?.cancel()
return launch {
val alarmItem = WallpaperAlarmItem(
homeInterval = settingsState.scheduleSettings.homeInterval,
lockInterval = settingsState.scheduleSettings.lockInterval,
scheduleSeparately = settingsState.scheduleSettings.scheduleSeparately,
setHome = settingsState.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.wallpaperSettings.setLockWallpaper,
changeStartTime = settingsState.scheduleSettings.changeStartTime,
startTime = settingsState.scheduleSettings.startTime
)
scheduler.updateWallpaperAlarm(
wallpaperAlarmItem = alarmItem,
firstLaunch = firstLaunch
)
scheduler.scheduleRefresh()
}
}
private fun CoroutineScope.updateWallpaper(
job: Job?,
settingsState: SettingsState,
scheduler: WallpaperAlarmSchedulerImpl,
): Job {
job?.cancel()
return launch {
scheduler.updateWallpaper(
scheduleSeparately = settingsState.scheduleSettings.scheduleSeparately,
setHome = settingsState.wallpaperSettings.setHomeWallpaper,
setLock = settingsState.wallpaperSettings.setLockWallpaper,
)
}
}
@@ -5,8 +5,7 @@ import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.compress
import com.anthonyla.paperize.core.getFolderLastModified
import com.anthonyla.paperize.core.getFolderNameFromUri
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getImageMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
@@ -45,7 +44,7 @@ class AddAlbumViewModel @Inject constructor(
initialAlbumName = event.initialAlbumName,
key = event.initialAlbumName.hashCode() + it.wallpaperUri.hashCode()
)
}
}.sortedBy { it.order }
val folders = _state.value.folders.map { folder ->
folder.copy(
initialAlbumName = event.initialAlbumName,
@@ -54,11 +53,14 @@ class AddAlbumViewModel @Inject constructor(
wallpapers = folder.wallpapers.map {
it.copy(
initialAlbumName = event.initialAlbumName,
key = event.initialAlbumName.hashCode() + folder.folderUri.hashCode() + it.wallpaperUri.hashCode()
key = event.initialAlbumName.hashCode() + folder.folderUri.hashCode() + it.wallpaperUri.hashCode(),
order = it.order + _state.value.wallpapers.size
)
}
}.sortedBy { it.order }
)
}
}.sortedBy { it.order }
val totalWallpapers = folders.flatMap { it.wallpapers } + wallpapers
val albumWithWallpaperAndFolder = AlbumWithWallpaperAndFolder(
album = Album(
initialAlbumName = event.initialAlbumName,
@@ -70,7 +72,7 @@ class AddAlbumViewModel @Inject constructor(
),
wallpapers = wallpapers,
folders = folders,
totalWallpapers = emptyList()
totalWallpapers = totalWallpapers
)
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
_state.update { AddAlbumState() }
@@ -135,15 +137,14 @@ class AddAlbumViewModel @Inject constructor(
}
_state.update { it.copy(isLoading = true) }
val wallpapers = getWallpaperFromFolder(event.directoryUri, context)
val folderName = getFolderNameFromUri(event.directoryUri, context)
val lastModified = getFolderLastModified(event.directoryUri, context)
val metadata = getFolderMetadata(event.directoryUri, context)
val folder = Folder(
initialAlbumName = "",
folderName = folderName,
folderName = metadata.filename,
folderUri = event.directoryUri,
wallpapers = wallpapers,
coverUri = wallpapers.firstOrNull()?.wallpaperUri ?: "",
dateModified = lastModified,
dateModified = metadata.lastModified,
order = _state.value.folders.size + 1,
key = 0
)
@@ -13,6 +13,7 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@@ -126,6 +127,8 @@ fun AddAlbumAnimatedFab(
text = stringResource(R.string.add_images_btn),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(end = 16.dp, top = 12.dp, bottom = 12.dp)
)
}
@@ -158,6 +161,8 @@ fun AddAlbumAnimatedFab(
text = stringResource(R.string.add_folder_btn),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(end = 16.dp, top = 12.dp, bottom = 12.dp)
)
}
@@ -5,6 +5,7 @@ import android.content.Context
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.findFirstValidUri
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.core.isDirectory
import com.anthonyla.paperize.core.isValidUri
@@ -13,11 +14,9 @@ import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepositor
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -96,7 +95,6 @@ class AlbumsViewModel @Inject constructor (
viewModelScope.launch {
_state.value.albumsWithWallpapers.forEach { album ->
// Remove invalid wallpapers
val album = album
val validWallpapers = async {
album.wallpapers
.asSequence()
@@ -113,37 +111,42 @@ class AlbumsViewModel @Inject constructor (
.filterNot { isDirectory(context, it.folderUri) }
.map { folder ->
async {
val existingWallpapers = folder.wallpapers
.asSequence()
.filter { isValidUri(context, it.wallpaperUri) }
.mapIndexed { index, wallpaper -> wallpaper.copy(order = index) }
.toList()
val newWallpapers =
getWallpaperFromFolder(folder.folderUri, context)
val metadata = getFolderMetadata(folder.folderUri, context)
if (metadata.lastModified != folder.dateModified) {
val existingWallpapers = folder.wallpapers
.asSequence()
.filterNot { new -> existingWallpapers.any { it.wallpaperUri == new.wallpaperUri } }
.mapIndexed { index, wallpaper ->
wallpaper.copy(
initialAlbumName = album.album.initialAlbumName,
order = existingWallpapers.size + 1 + index,
key = album.album.initialAlbumName.hashCode() +
folder.folderUri.hashCode() +
wallpaper.wallpaperUri.hashCode()
)
}
.filter { isValidUri(context, it.wallpaperUri) }
.mapIndexed { index, wallpaper -> wallpaper.copy(order = index) }
.toList()
val combinedWallpapers = existingWallpapers + newWallpapers
folder.copy(
coverUri = combinedWallpapers.firstOrNull()?.wallpaperUri ?: "",
wallpapers = combinedWallpapers
)
val newWallpapers =
getWallpaperFromFolder(folder.folderUri, context)
.asSequence()
.filterNot { new -> existingWallpapers.any { it.wallpaperUri == new.wallpaperUri } }
.mapIndexed { index, wallpaper ->
wallpaper.copy(
initialAlbumName = album.album.initialAlbumName,
order = existingWallpapers.size + 1 + index,
key = album.album.initialAlbumName.hashCode() +
folder.folderUri.hashCode() +
wallpaper.wallpaperUri.hashCode()
)
}.toList()
val combinedWallpapers = (existingWallpapers + newWallpapers).sortedBy { it.order }
folder.copy(
coverUri = combinedWallpapers.firstOrNull()?.wallpaperUri ?: "",
wallpapers = combinedWallpapers,
dateModified = metadata.lastModified,
folderName = metadata.filename
)
}
else { folder }
}
}
.toList()
.awaitAll()
}
val folders = validFolders.await()
val folders = validFolders.await().sortedBy { it.order }
val wallpapers = validWallpapers.await()
val coverUri = findFirstValidUri(context, folders, wallpapers)
val totalWallpapers = folders.flatMap { it.wallpapers } + wallpapers
@@ -3,19 +3,16 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
import android.app.Application
import android.content.Context
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.compress
import com.anthonyla.paperize.core.getFolderLastModified
import com.anthonyla.paperize.core.getFolderNameFromUri
import com.anthonyla.paperize.core.getFolderMetadata
import com.anthonyla.paperize.core.getImageMetadata
import com.anthonyla.paperize.core.getWallpaperFromFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumEvent
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.SelectionState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
@@ -105,14 +102,13 @@ class AlbumScreenViewModel @Inject constructor(
key = _state.value.initialAlbumName.hashCode() + event.directoryUri.hashCode() + it.wallpaperUri.hashCode()
)
}
val folderName = getFolderNameFromUri(event.directoryUri, context)
val lastModified = getFolderLastModified(event.directoryUri, context)
val metadata = getFolderMetadata(event.directoryUri, context)
val folder = Folder(
initialAlbumName = _state.value.initialAlbumName,
folderUri = event.directoryUri,
folderName = folderName,
folderName = metadata.filename,
coverUri = wallpapers.map { it.wallpaperUri }.firstOrNull() ?: "",
dateModified = lastModified,
dateModified = metadata.lastModified,
wallpapers = wallpapers,
order = album.folders.size + 1,
key = _state.value.initialAlbumName.hashCode() + event.directoryUri.hashCode()
@@ -227,7 +223,8 @@ class AlbumScreenViewModel @Inject constructor(
repository.deleteFolderList(foldersToDelete)
repository.deleteWallpaperList(wallpapersToDelete)
if (album.album.coverUri in (foldersToDelete.map { it.folderUri } + wallpapersToDelete.map { it.wallpaperUri })) {
val newCover = album.folders.minus(foldersToDelete).firstOrNull()?.coverUri ?: album.wallpapers.minus(wallpapersToDelete).firstOrNull()?.wallpaperUri ?: ""
val newCover = album.folders.minus(foldersToDelete.toSet()).firstOrNull()?.coverUri ?: album.wallpapers.minus(wallpapersToDelete.toSet()
).firstOrNull()?.wallpaperUri ?: ""
repository.updateAlbum(album.album.copy(coverUri = newCover))
}
}
@@ -279,7 +276,7 @@ class AlbumScreenViewModel @Inject constructor(
is AlbumViewEvent.LoadFoldersAndWallpapers -> {
viewModelScope.launch {
_state.update {
_state.update { state ->
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
if (album == null) { return@launch }
repository.upsertAlbumWithWallpaperAndFolder(
@@ -293,7 +290,7 @@ class AlbumScreenViewModel @Inject constructor(
wallpapers = event.wallpapers
)
)
it.copy(
state.copy(
selectionState = SelectionState(),
isLoading = false
)
@@ -58,7 +58,7 @@ fun HomeScreen(
onHomeTimeChange: (Int) -> Unit,
onLockTimeChange: (Int) -> Unit,
onSettingsClick: () -> Unit,
onStop: (Boolean, Boolean) -> Unit,
onDeselect: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
onBlurPercentageChange: (Int, Int) -> Unit,
onBlurChange: (Boolean) -> Unit,
@@ -148,7 +148,7 @@ fun HomeScreen(
onSelectAlbum = onSelectAlbum,
onHomeTimeChange = onHomeTimeChange,
onLockTimeChange = onLockTimeChange,
onStop = onStop,
onDeselect = onDeselect,
onToggleChanger = onToggleChanger,
onBlurPercentageChange = onBlurPercentageChange,
onBlurChange = onBlurChange,
@@ -19,7 +19,7 @@ sealed class SettingsEvent {
data class SetHome(val home: Boolean): SettingsEvent()
data class SetChangeStartTime(val changeStartTime: Boolean): 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 SetAlbum(val homeAlbumName: String? = null, val lockAlbumName: String? = null): 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()
@@ -5,6 +5,7 @@ import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_D
data class SettingsState(
val firstLaunch: Boolean = true,
val initialized: Boolean = false,
val themeSettings: ThemeSettings = ThemeSettings(),
val wallpaperSettings: WallpaperSettings = WallpaperSettings(),
val scheduleSettings: ScheduleSettings = ScheduleSettings(),
@@ -46,6 +46,7 @@ class SettingsViewModel @Inject constructor(
_state.update {
it.copy(
firstLaunch = firstLaunch ?: true,
initialized = true,
themeSettings = themeSettings,
wallpaperSettings = wallpaperSettings,
scheduleSettings = scheduleSettings,
@@ -148,6 +149,26 @@ class SettingsViewModel @Inject constructor(
)
}
private fun calculateNextSetTime(currentTime: LocalDateTime, scheduleSettings: ScheduleSettings): Triple<LocalDateTime, LocalDateTime, LocalDateTime> {
val homeNextTime = when {
scheduleSettings.changeStartTime -> currentTime
else -> currentTime.plusMinutes(scheduleSettings.homeInterval.toLong())
}
val lockNextTime = when {
scheduleSettings.changeStartTime -> currentTime
else -> currentTime.plusMinutes(scheduleSettings.lockInterval.toLong())
}
val nextSetTime = when {
scheduleSettings.changeStartTime -> currentTime
scheduleSettings.scheduleSeparately -> if (homeNextTime.isBefore(lockNextTime)) homeNextTime else lockNextTime
else -> homeNextTime
}
return Triple(nextSetTime, homeNextTime, lockNextTime)
}
fun onEvent(event: SettingsEvent) {
when (event) {
is SettingsEvent.SetFirstLaunch -> {
@@ -268,31 +289,18 @@ class SettingsViewModel @Inject constructor(
} else {
LocalDateTime.now()
}
val nextSetTime = when {
_state.value.scheduleSettings.changeStartTime -> {
settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME, currentTime.toString())
settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME, currentTime.toString())
currentTime
}
_state.value.scheduleSettings.scheduleSeparately -> {
settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME,
currentTime.plusMinutes(_state.value.scheduleSettings.homeInterval.toLong()).toString())
settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME,
currentTime.plusMinutes(_state.value.scheduleSettings.lockInterval.toLong()).toString())
val nextSetTime1 = currentTime.plusMinutes(_state.value.scheduleSettings.homeInterval.toLong())
val nextSetTime2 = currentTime.plusMinutes(_state.value.scheduleSettings.lockInterval.toLong())
if (nextSetTime1.isBefore(nextSetTime2)) nextSetTime1 else nextSetTime2
}
else -> {
settingsDataStoreImpl.putString(SettingsConstants.HOME_NEXT_SET_TIME,
currentTime.plusMinutes(_state.value.scheduleSettings.homeInterval.toLong()).toString())
settingsDataStoreImpl.putString(SettingsConstants.LOCK_NEXT_SET_TIME,
currentTime.plusMinutes(_state.value.scheduleSettings.lockInterval.toLong()).toString())
currentTime.plusMinutes(_state.value.scheduleSettings.homeInterval.toLong())
}
}.format(formatter)
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, LocalDateTime.now().format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, nextSetTime)
val (nextSetTime, homeNextTime, lockNextTime) = calculateNextSetTime(
currentTime,
_state.value.scheduleSettings
)
settingsDataStoreImpl.run {
putString(SettingsConstants.LAST_SET_TIME, LocalDateTime.now().format(formatter))
putString(SettingsConstants.NEXT_SET_TIME, nextSetTime.format(formatter))
putString(SettingsConstants.HOME_NEXT_SET_TIME, homeNextTime.toString())
putString(SettingsConstants.LOCK_NEXT_SET_TIME, lockNextTime.toString())
}
}
}
@@ -407,7 +415,7 @@ class SettingsViewModel @Inject constructor(
}
}
is SettingsEvent.SetAlbumName -> {
is SettingsEvent.SetAlbum -> {
viewModelScope.launch {
if (event.homeAlbumName != null) {
settingsDataStoreImpl.putString(SettingsConstants.HOME_ALBUM_NAME, event.homeAlbumName)
@@ -449,6 +457,7 @@ class SettingsViewModel @Inject constructor(
settingsDataStoreImpl.deleteString(SettingsConstants.CURRENT_HOME_WALLPAPER)
}
}
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ENABLE_CHANGER)
}
}
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen
import android.R.attr.onClick
import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.compose.animation.AnimatedContent
@@ -30,6 +29,8 @@ import androidx.compose.ui.res.stringResource
import com.anthonyla.paperize.R
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.SharedTransitionLayout
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
@@ -119,8 +120,7 @@ fun SortViewScreen(
state = reorderableLazyListStateFolder,
key = folder.folderUri
) { isDragging ->
val interactionSource =
remember { MutableInteractionSource() }
val interactionSource = remember { MutableInteractionSource() }
Card(
modifier = Modifier
.fillMaxWidth()
@@ -164,16 +164,14 @@ fun SortViewScreen(
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = folder.folderName ?: "",
modifier = Modifier.sharedElement(
rememberSharedContentState(
folder.folderName ?: ""
),
rememberSharedContentState(folder.folderName ?: ""),
animatedVisibilityScope = this@AnimatedContent,
)
)
@@ -258,6 +256,7 @@ fun SortViewScreen(
imageModel = { wallpaper.wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri() },
modifier = Modifier
.size(48.dp)
.border(BorderStroke(1.dp, MaterialTheme.colorScheme.onSecondaryContainer), CircleShape)
.clip(CircleShape)
)
}
@@ -285,7 +284,7 @@ fun SortViewScreen(
imageModel = { currentFolder.coverUri?.decompress("content://com.android.externalstorage.documents/")?.toUri() },
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(16.dp))
.clip(RoundedCornerShape(8.dp))
)
},
headlineContent = {
@@ -365,6 +364,7 @@ fun SortViewScreen(
modifier = Modifier
.size(48.dp)
.clip(CircleShape)
.border(BorderStroke(1.dp, MaterialTheme.colorScheme.onSecondaryContainer), CircleShape)
)
}
}
@@ -25,7 +25,6 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@@ -83,28 +82,28 @@ fun SortViewTopBar(
containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
) {
DropdownMenuItem(
text = { Text("Sort Alphabetically (A-Z)") },
text = { Text(stringResource(R.string.sort_alphabetically_a_z)) },
onClick = {
onSortAlphabetically()
showSortMenu = false
}
)
DropdownMenuItem(
text = { Text("Sort Alphabetically (Z-A)") },
text = { Text(stringResource(R.string.sort_alphabetically_z_a)) },
onClick = {
onSortAlphabeticallyReverse()
showSortMenu = false
}
)
DropdownMenuItem(
text = { Text("Sort by Last Modified (Newest)") },
text = { Text(stringResource(R.string.sort_by_last_modified_newest)) },
onClick = {
onSortByLastModified()
showSortMenu = false
}
)
DropdownMenuItem(
text = { Text("Sort by Last Modified (Oldest)") },
text = { Text(stringResource(R.string.sort_by_last_modified_oldest)) },
onClick = {
onSortByLastModifiedReverse()
showSortMenu = false
@@ -25,7 +25,6 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
@@ -50,7 +49,7 @@ import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.co
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.components.WallpaperPreviewAndScale
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WallpaperScreen(
albums: List<AlbumWithWallpaperAndFolder>,
@@ -69,7 +68,7 @@ fun WallpaperScreen(
onSelectAlbum: (AlbumWithWallpaperAndFolder, Boolean, Boolean) -> Unit,
onHomeTimeChange: (Int) -> Unit,
onLockTimeChange: (Int) -> Unit,
onStop: (Boolean, Boolean) -> Unit,
onDeselect: (Boolean, Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
onBlurPercentageChange: (Int, Int) -> Unit,
onBlurChange: (Boolean) -> Unit,
@@ -89,8 +88,8 @@ fun WallpaperScreen(
val snackbarHostState = remember { SnackbarHostState() }
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val showInterval = rememberSaveable { mutableStateOf(false) }
val lockEnabled = rememberSaveable { mutableStateOf(false) }
val homeEnabled = rememberSaveable { mutableStateOf(false) }
val lockSource = rememberSaveable { mutableStateOf(false) }
val homeSource = rememberSaveable { mutableStateOf(false) }
val handleAlbumSelection: (AlbumWithWallpaperAndFolder) -> Unit = { album ->
openBottomSheet = false
@@ -102,7 +101,7 @@ fun WallpaperScreen(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && alarmManager?.canScheduleExactAlarms() == false -> {
context.startActivity(Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM))
}
else -> onSelectAlbum(album, lockEnabled.value, homeEnabled.value)
else -> onSelectAlbum(album, lockSource.value, homeSource.value)
}
}
@@ -167,22 +166,15 @@ fun WallpaperScreen(
onOpenBottomSheet = { changeLock, changeHome ->
if (albums.firstOrNull() != null) {
openBottomSheet = true
lockEnabled.value = changeLock
homeEnabled.value = changeHome
lockSource.value = changeLock
homeSource.value = changeHome
} else {
showSnackBar(context.getString(R.string.no_albums_found))
}
},
onDeselect = { lock, home ->
if (homeSelectedAlbum != null || lockSelectedAlbum != null) {
val albumName = when {
home && lock -> homeSelectedAlbum?.album?.displayedAlbumName
home -> homeSelectedAlbum?.album?.displayedAlbumName
lock -> lockSelectedAlbum?.album?.displayedAlbumName
else -> ""
} ?: ""
showSnackBar(context.getString(R.string.has_been_unselected, albumName))
onStop(lock, home)
onDeselect(lock, home)
}
},
scheduleSeparately = scheduleSettings.scheduleSeparately,
@@ -9,8 +9,8 @@ import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
@@ -30,17 +30,23 @@ fun ChangerSelectionRow(
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2),
onCheckedChange = onLockCheckedChange,
checked = lockEnabled,
modifier = Modifier.testTag("paperize:lock_button"),
) {
Text(stringResource(R.string.lock_screen_btn))
Text(
stringResource(R.string.lock_screen_btn),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
SegmentedButton(
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),
onCheckedChange = onHomeCheckedChange,
checked = homeEnabled,
modifier = Modifier.testTag("paperize:home_button"),
) {
Text(text = stringResource(R.string.home_screen_btn))
Text(
text = stringResource(R.string.home_screen_btn),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
}
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -94,7 +95,10 @@ fun CurrentSelectedAlbum(
}
if (scheduleSeparately) {
Row {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
// Lock screen album
ListItem(
modifier = baseListItemModifier(16)
@@ -151,8 +155,7 @@ fun CurrentSelectedAlbum(
}
} else {
ListItem(
modifier = baseListItemModifier(16)
.clickable { onOpenBottomSheet(true, true) },
modifier = baseListItemModifier(16).clickable { onOpenBottomSheet(true, true) },
headlineContent = {
Text(
text = homeSelectedAlbum?.album?.displayedAlbumName ?: stringResource(R.string.no_album_selected),
@@ -10,7 +10,6 @@ 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
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
@@ -25,13 +24,15 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
private val HorizontalPadding = 32.dp
private val VerticalPadding = 8.dp
/**
* Composable to toggle individual scheduling settings and toggle wallpaper changer when scheduling separately
*/
@@ -39,7 +40,7 @@ import com.anthonyla.paperize.R
fun IndividualSchedulingAndToggleRow(
animate: Boolean,
scheduleSeparately: Boolean,
enableChanger : Boolean,
enableChanger: Boolean,
onToggleChanger: (Boolean) -> Unit,
onScheduleSeparatelyChange: (Boolean) -> Unit,
) {
@@ -51,7 +52,7 @@ fun IndividualSchedulingAndToggleRow(
stiffness = Spring.StiffnessLow
)
)
} else { Modifier }
} else Modifier
}
Surface(
@@ -59,83 +60,79 @@ fun IndividualSchedulingAndToggleRow(
shape = RoundedCornerShape(16.dp),
modifier = Modifier
.fillMaxWidth()
.padding(PaddingValues(horizontal = 16.dp, vertical = 8.dp))
.padding(horizontal = 16.dp, vertical = VerticalPadding)
) {
Column(
modifier = columnModifier
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 32.dp, end = 32.dp, top = 8.dp, bottom = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.individual_scheduling),
fontWeight = FontWeight.W500,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Spacer(modifier = Modifier.padding(8.dp))
Switch(
checked = scheduleSeparately,
onCheckedChange = onScheduleSeparatelyChange,
modifier = Modifier.testTag("paperize:individual_scheduling_switch"),
)
}
if (animate) {
AnimatedVisibility(
visible = scheduleSeparately,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
Row(modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp)) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline, thickness = 2.dp)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 32.dp, end = 32.dp, top = 8.dp, bottom = 8.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
Column(modifier = columnModifier) {
SettingsRow(
text = stringResource(R.string.individual_scheduling),
checked = scheduleSeparately,
onCheckedChange = onScheduleSeparatelyChange
)
if (scheduleSeparately) {
if (animate) {
AnimatedVisibility(
visible = true,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
Text(
text = stringResource(R.string.enable_wallpaper_changer),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger
)
}
}
}
else {
if (scheduleSeparately) {
HorizontalDivider(color = MaterialTheme.colorScheme.outline)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.enable_wallpaper_changer),
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.W500
)
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger
)
ChangerToggleSection(enableChanger, onToggleChanger)
}
} else {
ChangerToggleSection(enableChanger, onToggleChanger)
}
}
}
}
}
@Composable
private fun SettingsRow(
text: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
start = HorizontalPadding,
end = HorizontalPadding,
top = VerticalPadding,
bottom = VerticalPadding
),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = text,
fontWeight = FontWeight.W500,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Spacer(modifier = Modifier.padding(VerticalPadding))
Switch(
checked = checked,
onCheckedChange = onCheckedChange
)
}
}
@Composable
private fun ChangerToggleSection(
enableChanger: Boolean,
onToggleChanger: (Boolean) -> Unit
) {
HorizontalDivider(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 48.dp),
color = MaterialTheme.colorScheme.outline,
thickness = 2.dp
)
SettingsRow(
text = stringResource(R.string.enable_wallpaper_changer),
checked = enableChanger,
onCheckedChange = onToggleChanger
)
}
@@ -11,6 +11,18 @@ import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.LockWallpaperS
import java.time.LocalDateTime
import java.time.ZoneId
data class ServiceConfig(
val homeInterval: Int? = null,
val lockInterval: Int? = null,
val scheduleSeparately: Boolean? = null,
val type: Int? = null
)
sealed class WallpaperAction {
data object START : WallpaperAction()
data object UPDATE : WallpaperAction()
}
/**
* This class is responsible for scheduling wallpaper alarms.
* It uses the AlarmManager to schedule alarms for the [WallpaperReceiver].
@@ -118,60 +130,66 @@ class WallpaperAlarmSchedulerImpl (
* Schedules the wallpaper alarm based on type and time
*/
private fun scheduleWallpaper(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int? = null, firstLaunch: Boolean = false) {
val startTime = LocalDateTime.now()
val nextTime = when {
wallpaperAlarmItem.changeStartTime && firstLaunch -> {
var calculatedStartTime = LocalDateTime.now().withHour(wallpaperAlarmItem.startTime.first).withMinute(wallpaperAlarmItem.startTime.second)
if (calculatedStartTime.isBefore(LocalDateTime.now())) {
calculatedStartTime = calculatedStartTime.plusDays(1)
try {
val nextTime = calculateNextAlarmTime(wallpaperAlarmItem, type, firstLaunch)
val intent = createWallpaperIntent(wallpaperAlarmItem, type, origin)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!alarmManager.canScheduleExactAlarms()) {
cancelWallpaperAlarm()
return
}
calculatedStartTime
}
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately -> startTime.plusMinutes(wallpaperAlarmItem.lockInterval.toLong())
type == Type.HOME && wallpaperAlarmItem.scheduleSeparately -> startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong()).plusSeconds(10)
else -> startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong())
scheduleExactAlarm(nextTime, intent)
} catch (e: Exception) {
cancelWallpaperAlarm()
}
val intent = Intent(context, WallpaperReceiver::class.java).apply {
}
private fun calculateNextAlarmTime(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, firstLaunch: Boolean): LocalDateTime {
val startTime = LocalDateTime.now()
return when {
wallpaperAlarmItem.changeStartTime && firstLaunch -> {
startTime.withHour(wallpaperAlarmItem.startTime.first)
.withMinute(wallpaperAlarmItem.startTime.second)
.let { if (it.isBefore(startTime)) it.plusDays(1) else it }
.withSecond(0)
.withNano(0)
}
type == Type.LOCK && wallpaperAlarmItem.scheduleSeparately ->
startTime.plusMinutes(wallpaperAlarmItem.lockInterval.toLong()).withSecond(0).withNano(0)
type == Type.HOME && wallpaperAlarmItem.scheduleSeparately ->
startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong()).plusSeconds(10).withNano(0)
else -> startTime.plusMinutes(wallpaperAlarmItem.homeInterval.toLong()).plusSeconds(10).withNano(0)
}
}
private fun createWallpaperIntent(wallpaperAlarmItem: WallpaperAlarmItem, type: Type, origin: Int?): Intent {
return Intent(context, WallpaperReceiver::class.java).apply {
putExtra("homeInterval", wallpaperAlarmItem.homeInterval)
putExtra("lockInterval", wallpaperAlarmItem.lockInterval)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("type", type.ordinal)
putExtra("setHome", wallpaperAlarmItem.setHome)
putExtra("setLock", wallpaperAlarmItem.setLock)
putExtra("changeStartTime", wallpaperAlarmItem.changeStartTime)
putExtra("startTime", wallpaperAlarmItem.startTime)
putExtra("scheduleSeparately", wallpaperAlarmItem.scheduleSeparately)
putExtra("origin", origin)
putExtra("type", type.ordinal)
putExtra("changeStartTime", wallpaperAlarmItem.changeStartTime)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!alarmManager.canScheduleExactAlarms()) {
cancelWallpaperAlarm()
}
else {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
type.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
}
else {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
PendingIntent.getBroadcast(
context,
type.ordinal,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
)
}
private fun scheduleExactAlarm(nextTime: LocalDateTime, intent: Intent) {
val pendingIntent = PendingIntent.getBroadcast(
context,
intent.getIntExtra("type", 0),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTime.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000,
pendingIntent
)
}
/**
@@ -201,14 +219,14 @@ class WallpaperAlarmSchedulerImpl (
private fun changeWallpaperImmediate(wallpaperAlarmItem: WallpaperAlarmItem, type: Type) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal)
if (wallpaperAlarmItem.setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal))
if (wallpaperAlarmItem.setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.SINGLE.ordinal))
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.START.toString(), wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.LOCK.ordinal)
startService(context, LockWallpaperService::class.java, WallpaperAction.START, ServiceConfig(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)
startService(context, HomeWallpaperService::class.java, WallpaperAction.START, ServiceConfig(wallpaperAlarmItem.homeInterval, wallpaperAlarmItem.lockInterval, wallpaperAlarmItem.scheduleSeparately, Type.HOME.ordinal))
}
}
}
@@ -219,14 +237,14 @@ class WallpaperAlarmSchedulerImpl (
private fun updateWallpaper(type: Type, setHome: Boolean, setLock: Boolean) {
when (type.ordinal) {
Type.SINGLE.ordinal -> {
if (setLock) startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
if (setHome) startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
if (setLock) startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE)
if (setHome) startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE)
}
Type.LOCK.ordinal -> {
startService(context, LockWallpaperService::class.java, LockWallpaperService.Actions.UPDATE.toString())
startService(context, LockWallpaperService::class.java, WallpaperAction.UPDATE)
}
Type.HOME.ordinal -> {
startService(context, HomeWallpaperService::class.java, HomeWallpaperService.Actions.UPDATE.toString())
startService(context, HomeWallpaperService::class.java, WallpaperAction.UPDATE)
}
}
}
@@ -247,13 +265,20 @@ class WallpaperAlarmSchedulerImpl (
/**
* Starts the service to change the wallpaper
*/
private fun startService(context: Context, serviceClass: Class<*>, action: String, homeInterval: Int? = null, lockInterval: Int? = null, scheduleSeparately: Boolean? = null, type: Int? = null) {
private fun startService(
context: Context,
serviceClass: Class<*>,
action: WallpaperAction,
config: ServiceConfig? = null
) {
val serviceIntent = Intent(context, serviceClass).apply {
this.action = action
homeInterval?.let { putExtra("homeInterval", it) }
lockInterval?.let { putExtra("lockInterval", it) }
scheduleSeparately?.let { putExtra("scheduleSeparately", it) }
type?.let { putExtra("type", it) }
this.action = action::class.java.simpleName
config?.let {
it.homeInterval?.let { interval -> putExtra("homeInterval", interval) }
it.lockInterval?.let { interval -> putExtra("lockInterval", interval) }
it.scheduleSeparately?.let { separate -> putExtra("scheduleSeparately", separate) }
it.type?.let { type -> putExtra("type", type) }
}
}
context.startService(serviceIntent)
}
@@ -69,6 +69,7 @@ class LockWallpaperService: Service() {
if (intent != null) {
when (intent.action) {
Actions.START.toString() -> {
Log.d("PaperizeWallpaperChanger", "Starting lock start wallpaper service")
homeInterval = intent.getIntExtra("homeInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
lockInterval = intent.getIntExtra("lockInterval", SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT)
scheduleSeparately = intent.getBooleanExtra("scheduleSeparately", false)
@@ -76,9 +77,11 @@ class LockWallpaperService: Service() {
workerTaskStart()
}
Actions.UPDATE.toString() -> {
Log.d("PaperizeWallpaperChanger", "Starting lock update wallpaper service")
workerTaskUpdate()
}
Actions.REFRESH.toString() -> {
Log.d("PaperizeWallpaperChanger", "Starting lock refresh wallpaper service")
workerTaskRefresh()
}
}