Added toggle for enabling wallpaper changer

Refactored code for adding album
Removed redundant code in WallpaperScreen
Fixed wallpaper service handling when wallpaper is inaccessible
Fixed issue where users could select albums with no valid wallpapers
Updated version to 1.1.0
Updated album model to include current set wallpaper. Added database migration accordingly
Added function to change wallpaper on home/lock preview depending on latest wallpaper set
This commit is contained in:
Anthonyy232 committed 2024-05-10 20:34:25 -07:00
1 parent 4fd1e06b8e
commit fc57f14d2a
23 files changed
+275 -140

No files matched your search

@@ -15,4 +15,5 @@ object SettingsConstants {
const val FIRST_ALBUM_SET = "first_album_set"
const val LAST_SET_TIME = "last_set_time"
const val NEXT_SET_TIME = "next_set_time"
const val ENABLE_CHANGER = "enable_changer"
}
@@ -3,6 +3,8 @@ package com.anthonyla.paperize.di
import android.app.Application
import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.data.settings.SettingsDataStoreImpl
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDatabase
@@ -31,7 +33,7 @@ object AppModule {
app,
AlbumDatabase::class.java,
AlbumDatabase.DATABASE_NAME
).build()
).addMigrations(MIGRATION_1_2).build()
}
@Provides
@@ -41,7 +43,7 @@ object AppModule {
app,
SelectedAlbumDatabase::class.java,
SelectedAlbumDatabase.DATABASE_NAME
).build()
).addMigrations(MIGRATION_1_2).build()
}
@Provides
@@ -79,4 +81,10 @@ object AppModule {
fun provideContext(
@ApplicationContext context: Context,
): Context { return context }
}
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE Album ADD COLUMN currentWallpaper TEXT")
}
}
@@ -13,7 +13,7 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
*/
@Database(
entities = [Album::class, Wallpaper::class, Folder::class],
version = 1
version = 2
)
@TypeConverters(Converters::class)
abstract class AlbumDatabase: RoomDatabase() {
@@ -12,7 +12,7 @@ import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
*/
@Database(
entities = [Album::class, Wallpaper::class],
version = 1
version = 2
)
@TypeConverters(Converters::class)
abstract class SelectedAlbumDatabase: RoomDatabase() {
@@ -19,4 +19,5 @@ data class Album(
val coverUri: String?,
val initialized: Boolean = false,
val wallpapersInQueue: List<String> = emptyList(),
val currentWallpaper: String? = null
)
@@ -14,7 +14,6 @@ import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
@@ -45,8 +44,7 @@ class MainActivity : ComponentActivity() {
contentResolver.releasePersistableUriPermission(permission.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
}
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle(this)
PaperizeTheme(settingsState.value.darkMode, settingsState.value.dynamicTheming) {
PaperizeTheme(settingsViewModel.state) {
Surface(tonalElevation = 5.dp) {
PaperizeApp(isFirstLaunch)
}
@@ -77,7 +77,8 @@ fun PaperizeApp(
albumState.value.albumsWithWallpapers.asSequence().forEach { albumWithWallpapers ->
if (!albumWithWallpapers.album.initialized && (albumWithWallpapers.wallpapers.isNotEmpty() || albumWithWallpapers.folders.isNotEmpty())) {
albumsViewModel.onEvent(AlbumsEvent.InitializeAlbum(albumWithWallpapers))
} else if (albumWithWallpapers.album.initialized && albumWithWallpapers.wallpapers.isEmpty() && albumWithWallpapers.folders.isEmpty()) {
}
else if (albumWithWallpapers.wallpapers.isEmpty() && albumWithWallpapers.folders.isEmpty() && albumWithWallpapers.album.initialized) {
if (navController.currentDestination?.route == Home::class.simpleName) {
navController.popBackStack<Home>(inclusive = false)
}
@@ -86,42 +87,42 @@ fun PaperizeApp(
}
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 ->
val wallpaperHashCode = wallpaper.hashCode()
Wallpaper(
initialAlbumName = foundAlbum.album.initialAlbumName,
wallpaperUri = wallpaper,
key = wallpaperHashCode + albumNameHashCode,
)
}
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 wallpaperUriSet = wallpapers.map { it.wallpaperUri }.toSet()
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
wallpapersInQueue = selectedAlbum.album.wallpapersInQueue.filter { it in wallpaperUriSet }
),
wallpapers = wallpapers
)
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(newSelectedAlbum))
settingsViewModel.onEvent(SettingsEvent.SetWallpaperInterval(settingsState.value.interval))
}
val wallpaperUriSet = wallpapers.map { it.wallpaperUri }.toSet()
val newSelectedAlbum = SelectedAlbum(
album = foundAlbum.album.copy(
wallpapersInQueue = selectedAlbum.album.wallpapersInQueue.filter { it in wallpaperUriSet },
currentWallpaper = selectedAlbum.album.currentWallpaper
),
wallpapers = wallpapers
)
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(newSelectedAlbum))
settingsViewModel.onEvent(SettingsEvent.SetWallpaperInterval(settingsState.value.interval))
if (settingsState.value.enableChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", settingsState.value.interval)
}
context.startForegroundService(intent)
}
?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
} ?: run {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
}
}
}
@@ -206,14 +207,17 @@ fun PaperizeApp(
},
onScheduleWallpaperChanger = { timeInMinutes ->
settingsViewModel.onEvent(SettingsEvent.SetWallpaperInterval(timeInMinutes))
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", timeInMinutes)
if (settingsState.value.enableChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", timeInMinutes)
}
context.startForegroundService(intent)
}
context.startForegroundService(intent)
},
onStop = {
wallpaperScreenViewModel.onEvent(WallpaperEvent.Reset)
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
@@ -227,7 +231,24 @@ fun PaperizeApp(
onSetLockWithHome = {
settingsViewModel.onEvent(SettingsEvent.SetLockWithHome(it))
},
selectedAlbum = selectedState.value.selectedAlbum
selectedAlbum = selectedState.value.selectedAlbum,
enableChanger = settingsState.value.enableChanger,
onToggleChanger = { enableWallpaperChanger ->
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
if (enableWallpaperChanger) {
val intent = Intent(context, WallpaperService::class.java).apply {
action = WallpaperService.Actions.START.toString()
putExtra("timeInMinutes", settingsState.value.interval)
}
context.startForegroundService(intent)
}
else {
Intent(context, WallpaperService::class.java).also {
it.action = WallpaperService.Actions.STOP.toString()
context.startForegroundService(it)
}
}
}
)
}
// Navigate to the add album screen to create a new album and add wallpapers to it
@@ -249,10 +270,7 @@ fun PaperizeApp(
AddAlbumScreen(
initialAlbumName = addEdit.wallpaper,
onBackClick = { navController.navigateUp() },
onConfirmation = {
navController.navigateUp()
settingsViewModel.onEvent(SettingsEvent.SetFirstAlbum)
},
onConfirmation = { navController.navigateUp() },
onShowWallpaperView = {
navController.navigate(WallpaperView(it))
},
@@ -63,6 +63,7 @@ fun AddAlbumScreen(
} else {
onBackClick()
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
showSpotlight = false
}
}
@@ -79,7 +80,6 @@ fun AddAlbumScreen(
if (uriList.isNotEmpty()) {
addAlbumViewModel.onEvent(AddAlbumEvent.AddWallpapers(uriList))
}
showSpotlight = true
}
)
@@ -95,7 +95,6 @@ fun AddAlbumScreen(
addAlbumViewModel.onEvent(AddAlbumEvent.AddFolder(uri.toString()))
}
}
showSpotlight = true
}
)
@@ -107,12 +106,13 @@ fun AddAlbumScreen(
selectionMode = selectionMode,
albumState = addAlbumViewModel.state,
showSpotlight = showSpotlight,
albumFirstSet = settingsState.value.firstAlbumSet,
onBackClick = {
showSpotlight = false
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
onBackClick()
},
onConfirmationClick = {
showSpotlight = false
addAlbumViewModel.onEvent(AddAlbumEvent.ReflectAlbumName(it))
addAlbumViewModel.onEvent(AddAlbumEvent.SaveAlbum)
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
@@ -156,10 +156,12 @@ fun AddAlbumScreen(
onImageClick = {
selectionMode = false
imagePickerLauncher.launch(arrayOf("image/*"))
showSpotlight = true
},
onFolderClick = {
selectionMode = false
folderPickerLauncher.launch(null)
showSpotlight = true
},
animate = false
)
@@ -65,7 +65,6 @@ fun AddAlbumSmallTopBar(
isEmpty: Boolean,
selectionMode: Boolean,
showSpotlight: Boolean,
albumFirstSet: Boolean,
onSelectAllClick: () -> Unit,
onBackClick: () -> Unit,
onDeleteSelected: () -> Unit,
@@ -186,7 +185,7 @@ fun AddAlbumSmallTopBar(
modifier = Modifier.padding(6.dp)
)
}
if (!albumFirstSet && showSpotlight) {
if (!showSpotlight) {
Canvas(modifier = Modifier.matchParentSize()) {
drawCircle(
color = primaryColor,
@@ -36,13 +36,15 @@ fun HomeScreen(
onAlbumViewClick: (String) -> Unit,
onScheduleWallpaperChanger: (Int) -> Unit,
onSetLockWithHome: (Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
onStop: () -> Unit,
animate : Boolean,
interval: Int,
setLockWithHome: Boolean,
lastSetTime: String?,
nextSetTime: String?,
selectedAlbum: SelectedAlbum?
selectedAlbum: SelectedAlbum?,
enableChanger: Boolean
) {
var tabIndex by rememberSaveable { mutableIntStateOf(0) }
val pagerState = rememberPagerState { tabItems.size }
@@ -116,8 +118,10 @@ fun HomeScreen(
setLockWithHome = setLockWithHome,
lastSetTime = lastSetTime,
nextSetTime = nextSetTime,
onSetLockWithHome = { onSetLockWithHome(it) },
selectedAlbum = selectedAlbum
onSetLockWithHome = onSetLockWithHome,
selectedAlbum = selectedAlbum,
enableChanger = enableChanger,
onToggleChanger = onToggleChanger
)
1 -> LibraryScreen(
onAddNewAlbumClick = { addAlbumDialog = true },
@@ -5,10 +5,10 @@ sealed class SettingsEvent {
data object Refresh: SettingsEvent()
data object Reset: SettingsEvent()
data object SetFirstLaunch: SettingsEvent()
data object SetFirstAlbum: SettingsEvent()
data class SetDarkMode(val darkMode: Boolean?): SettingsEvent()
data class SetDynamicTheming(val dynamicTheming: Boolean): SettingsEvent()
data class SetAnimate(val animate: Boolean): SettingsEvent()
data class SetWallpaperInterval(val interval: Int): SettingsEvent()
data class SetLockWithHome(val lockWithHome: Boolean): SettingsEvent()
data class SetChangerToggle(val toggle: Boolean): SettingsEvent()
}
@@ -3,12 +3,12 @@ import com.anthonyla.paperize.core.SettingsConstants.WALLPAPER_CHANGE_INTERVAL_D
data class SettingsState (
val firstLaunch: Boolean = true,
val firstAlbumSet: Boolean = false,
val darkMode: Boolean? = null,
val dynamicTheming: Boolean = false,
val animate: Boolean = true,
val interval: Int = WALLPAPER_CHANGE_INTERVAL_DEFAULT,
val setLockWithHome: Boolean = false,
val lastSetTime: String? = null,
val nextSetTime: String? = null
val nextSetTime: String? = null,
val enableChanger: Boolean = false
)
@@ -35,11 +35,11 @@ class SettingsViewModel @Inject constructor (
val dynamicTheming = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DYNAMIC_THEME_TYPE) ?: false }
val wallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
val firstLaunch = async { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) ?: true }
val firstAlbumSet = async { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_ALBUM_SET) ?: false }
val setLockWithHome = async { settingsDataStoreImpl.getBoolean(SettingsConstants.SET_LOCK_WITH_HOME) ?: false }
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) ?: false }
_state.update {
it.copy(
@@ -48,10 +48,10 @@ class SettingsViewModel @Inject constructor (
interval = wallpaperInterval.await(),
setLockWithHome = setLockWithHome.await(),
firstLaunch = firstLaunch.await(),
firstAlbumSet = firstAlbumSet.await(),
lastSetTime = lastSetTime.await(),
nextSetTime = nextSetTime.await(),
animate = animate.await()
animate = animate.await(),
enableChanger = enableChanger.await()
)
}
setKeepOnScreenCondition = false
@@ -70,12 +70,16 @@ class SettingsViewModel @Inject constructor (
}
}
}
is SettingsEvent.SetFirstAlbum -> {
is SettingsEvent.SetChangerToggle -> {
viewModelScope.launch {
settingsDataStoreImpl.putBoolean(SettingsConstants.FIRST_ALBUM_SET, true)
when (event.toggle) {
true -> { settingsDataStoreImpl.putBoolean(SettingsConstants.ENABLE_CHANGER, true) }
false -> { settingsDataStoreImpl.putBoolean(SettingsConstants.ENABLE_CHANGER, false) }
}
_state.update {
it.copy(
firstAlbumSet = true
enableChanger = event.toggle
)
}
}
@@ -87,11 +91,11 @@ class SettingsViewModel @Inject constructor (
val dynamicTheming = async { settingsDataStoreImpl.getBoolean(SettingsConstants.DYNAMIC_THEME_TYPE) ?: false }
val wallpaperInterval = async { settingsDataStoreImpl.getInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL) ?: SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT }
val firstLaunch = async { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) ?: true }
val firstAlbumSet = async { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_ALBUM_SET) ?: false }
val setLockWithHome = async { settingsDataStoreImpl.getBoolean(SettingsConstants.SET_LOCK_WITH_HOME) ?: false }
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) ?: false }
_state.update {
it.copy(
@@ -100,10 +104,10 @@ class SettingsViewModel @Inject constructor (
interval = wallpaperInterval.await(),
setLockWithHome = setLockWithHome.await(),
firstLaunch = firstLaunch.await(),
firstAlbumSet = firstAlbumSet.await(),
lastSetTime = lastSetTime.await(),
nextSetTime = nextSetTime.await(),
animate = animate.await()
animate = animate.await(),
enableChanger = enableChanger.await()
)
}
}
@@ -190,12 +194,12 @@ class SettingsViewModel @Inject constructor (
settingsDataStoreImpl.deleteBoolean(SettingsConstants.DARK_MODE_TYPE)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.DYNAMIC_THEME_TYPE)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.FIRST_LAUNCH)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.FIRST_ALBUM_SET)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.SET_LOCK_WITH_HOME)
settingsDataStoreImpl.deleteString(SettingsConstants.LAST_SET_TIME)
settingsDataStoreImpl.deleteString(SettingsConstants.NEXT_SET_TIME)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ANIMATE_TYPE)
settingsDataStoreImpl.deleteInt(SettingsConstants.WALLPAPER_CHANGE_INTERVAL)
settingsDataStoreImpl.deleteBoolean(SettingsConstants.ENABLE_CHANGER)
_state.update {
it.copy(
darkMode = null,
@@ -203,10 +207,10 @@ class SettingsViewModel @Inject constructor (
interval = SettingsConstants.WALLPAPER_CHANGE_INTERVAL_DEFAULT,
setLockWithHome = false,
firstLaunch = true,
firstAlbumSet = false,
lastSetTime = null,
nextSetTime = null,
animate = true
animate = true,
enableChanger = false
)
}
}
@@ -63,7 +63,7 @@ fun PaperizeListItem(onGitHubClick: () -> Unit, onPlaystoreClick: () -> Unit, on
fontSize = MaterialTheme.typography.titleLarge.fontSize
)
Text(
text = "Version: 1.0.1",
text = "Version: 1.1.0",
style = MaterialTheme.typography.bodySmall,
fontSize = MaterialTheme.typography.bodyMedium.fontSize
)
@@ -15,6 +15,9 @@ import androidx.compose.runtime.SideEffect
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
import kotlinx.coroutines.flow.StateFlow
private val LightColors = lightColorScheme(
@@ -88,14 +91,14 @@ private val DarkColors = darkColorScheme(
*/
@Composable
fun PaperizeTheme(
darkMode: Boolean?,
dynamicTheming: Boolean,
settingsState: StateFlow<SettingsState>,
content: @Composable () -> Unit
) {
val state = settingsState.collectAsStateWithLifecycle()
val context = LocalContext.current
val isDarkMode = isDarkMode(darkMode = darkMode)
val isDynamicTheming = isDynamicTheming(dynamicTheming = dynamicTheming)
val isDarkMode = isDarkMode(darkMode = state.value.darkMode)
val isDynamicTheming = isDynamicTheming(dynamicTheming = state.value.dynamicTheming)
val dynamicThemingSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val colors = when {
isDynamicTheming && dynamicThemingSupported && isDarkMode -> dynamicDarkColorScheme(context)
@@ -22,9 +22,11 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.anthonyla.paperize.R
import com.anthonyla.paperize.feature.wallpaper.domain.model.SelectedAlbum
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
@@ -44,18 +46,21 @@ fun WallpaperScreen(
settingsViewModel: SettingsViewModel = hiltViewModel(),
onScheduleWallpaperChanger: (Int) -> Unit,
onSetLockWithHome: (Boolean) -> Unit,
onToggleChanger: (Boolean) -> Unit,
onStop: () -> Unit,
animate: Boolean,
interval: Int,
setLockWithHome: Boolean,
lastSetTime: String?,
nextSetTime: String?,
selectedAlbum: SelectedAlbum?
selectedAlbum: SelectedAlbum?,
enableChanger: Boolean
) {
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
var openBottomSheet by rememberSaveable { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() }
val context = LocalContext.current
Scaffold(
snackbarHost = {
@@ -88,15 +93,29 @@ fun WallpaperScreen(
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = "${selectedAlbum.album.displayedAlbumName} has been unselected.",
actionLabel = "Dismiss",
message = context.getString(R.string.has_been_unselected, selectedAlbum.album.displayedAlbumName),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
onStop()
}
},
animate = animate
animate = animate,
enableChanger = enableChanger,
onToggleChanger = {
if (!it) {
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = context.getString(R.string.wallpaper_changer_has_been_disabled),
actionLabel = context.getString(R.string.dismiss),
duration = SnackbarDuration.Short
)
}
}
onToggleChanger(it)
}
)
}
item {
@@ -126,7 +145,7 @@ fun WallpaperScreen(
) {
if (selectedAlbum != null) {
SetLockScreenSwitch(
albumUri = selectedAlbum.album.coverUri,
albumUri = selectedAlbum.album.currentWallpaper,
checked = setLockWithHome,
onCheckedChange = { onSetLockWithHome(it) },
animate = true
@@ -137,7 +156,7 @@ fun WallpaperScreen(
else {
if (selectedAlbum != null) {
SetLockScreenSwitch(
albumUri = selectedAlbum.album.coverUri,
albumUri = selectedAlbum.album.currentWallpaper,
checked = setLockWithHome,
onCheckedChange = { onSetLockWithHome(it) },
animate = false
@@ -156,9 +175,6 @@ fun WallpaperScreen(
timeInMinutes = interval,
onTimeChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
settingsViewModel.onEvent(
SettingsEvent.SetWallpaperInterval(totalMinutes)
)
onScheduleWallpaperChanger(totalMinutes)
}
)
@@ -170,9 +186,6 @@ fun WallpaperScreen(
timeInMinutes = interval,
onTimeChange = { days, hours, minutes ->
val totalMinutes = 24 * days * 60 + hours * 60 + minutes
settingsViewModel.onEvent(
SettingsEvent.SetWallpaperInterval(totalMinutes)
)
onScheduleWallpaperChanger(totalMinutes)
}
)
@@ -195,23 +208,19 @@ fun WallpaperScreen(
)
}
}.toList()
val shuffledWallpapers = wallpapers.map { it.wallpaperUri }.shuffled()
val newSelectedAlbum = SelectedAlbum(
album = album.album.copy(
wallpapersInQueue = wallpapers.map { it.wallpaperUri }.shuffled()
wallpapersInQueue = shuffledWallpapers,
currentWallpaper = shuffledWallpapers.firstOrNull()
),
wallpapers = wallpapers
)
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(true))
wallpaperScreenViewModel.onEvent(WallpaperEvent.UpdateSelectedAlbum(newSelectedAlbum))
openBottomSheet = false
scope.launch {
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(
message = "${album.album.displayedAlbumName} has been selected.",
actionLabel = "Dismiss",
duration = SnackbarDuration.Short
)
}
onScheduleWallpaperChanger(interval)
onToggleChanger(true)
},
animate = animate
)
@@ -72,6 +72,7 @@ fun AlbumBottomSheet(
tonalElevation = 5.dp
) {
albums.forEach {
if (it.folders.sumOf { folder -> folder.wallpapers.size } + it.wallpapers.size == 0) return@forEach
ListItem(
modifier = Modifier
.padding(4.dp)
@@ -3,7 +3,9 @@ package com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.c
import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
@@ -19,11 +21,14 @@ import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
@@ -43,9 +48,11 @@ import com.skydoves.landscapist.glide.GlideImage
@Composable
fun CurrentSelectedAlbum(
selectedAlbum: SelectedAlbum?,
enableChanger: Boolean,
onOpenBottomSheet: () -> Unit,
onStop: () -> Unit,
animate: Boolean
animate: Boolean,
onToggleChanger: (Boolean) -> Unit
) {
fun isValidUri(context: Context, uriString: String?): Boolean {
val uri = uriString?.toUri()
@@ -62,9 +69,15 @@ fun CurrentSelectedAlbum(
ListItem(
modifier = Modifier
.padding(16.dp)
.padding(PaddingValues(vertical = 8.dp, horizontal = 16.dp))
.clip(RoundedCornerShape(16.dp))
.clickable { onOpenBottomSheet() },
.clickable {
if (selectedAlbum != null) {
onToggleChanger(!enableChanger)
} else {
onOpenBottomSheet()
}
},
headlineContent = {
Text(
text = selectedAlbum?.album?.displayedAlbumName ?: stringResource(R.string.no_album_selected),
@@ -119,7 +132,10 @@ fun CurrentSelectedAlbum(
}
},
trailingContent = {
Row {
Row (
horizontalArrangement = Arrangement.spacedBy((-8).dp),
verticalAlignment = Alignment.CenterVertically
) {
if (selectedAlbum != null) {
IconButton(onClick = { onStop() }) {
Icon(imageVector = Icons.Default.Stop, contentDescription = stringResource(R.string.stop_the_album))
@@ -131,6 +147,15 @@ fun CurrentSelectedAlbum(
imageVector = Icons.Filled.ArrowDropDown,
)
}
if (selectedAlbum != null) {
Switch(
checked = enableChanger,
onCheckedChange = onToggleChanger,
modifier = Modifier
.rotate(270f)
.scale(0.75f)
)
}
}
},
tonalElevation = 10.dp
@@ -57,7 +57,7 @@ fun SetLockScreenSwitch(
}
if (animate) {
AnimatedVisibility(
visible = checked,
visible = checked && albumUri != null,
enter = expandVertically(animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)),
exit = shrinkVertically(animationSpec = tween(durationMillis = 700, easing = LinearOutSlowInEasing))
) {
@@ -19,9 +19,10 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineScope
import com.anthonyla.paperize.R
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -51,21 +52,25 @@ fun TimeSliders(
val displayHours = (totalMinutes % (24 * 60)) / 60
val displayMinutes = totalMinutes % 60
val formattedDays = when {
displayDays > 1 -> "$displayDays days"
displayDays == 1 -> "$displayDays day"
displayDays > 1 -> stringResource(R.string.days, displayDays)
displayDays == 1 -> stringResource(R.string.day, displayDays)
else -> ""
}
val formattedHours = when {
displayHours > 1 -> "$displayHours hours"
displayHours == 1 -> "$displayHours hour"
displayHours > 1 -> stringResource(R.string.hours, displayHours)
displayHours == 1 -> stringResource(R.string.hour, displayHours)
else -> ""
}
val formattedMinutes = when {
displayMinutes > 1 -> "$displayMinutes minutes"
displayMinutes == 1 -> "$displayMinutes minute"
displayMinutes > 1 -> stringResource(R.string.minutes, displayMinutes)
displayMinutes == 1 -> stringResource(R.string.minute, displayMinutes)
else -> ""
}
val formattedTime = "Interval | ${listOf(formattedDays, formattedHours, formattedMinutes).filter { it.isNotEmpty() }.joinToString(", ")}"
val formattedTime = stringResource(
R.string.interval,
listOf(formattedDays, formattedHours, formattedMinutes).filter { it.isNotEmpty() }
.joinToString(", ")
)
Text(
text = formattedTime,
@@ -78,8 +83,8 @@ fun TimeSliders(
onValueChange = { newDays ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
days = newDays
val totalMinutes = (newDays.toInt() * 24 * 60) + (hours.toInt() * 60) + minutes.toInt()
if (totalMinutes < 15) {
val totalMinute = (newDays.toInt() * 24 * 60) + (hours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (hours.toInt() * 60)
}
job?.cancel()
@@ -98,8 +103,8 @@ fun TimeSliders(
onValueChange = { newHours ->
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
hours = newHours
val totalMinutes = (days.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes.toInt()
if (totalMinutes < 15) {
val totalMinute = (days.toInt() * 24 * 60) + (newHours.toInt() * 60) + minutes.toInt()
if (totalMinute < 15) {
minutes = 15f - (newHours.toInt() * 60)
}
job?.cancel()
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.feature.wallpaper.wallpaperservice
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
import android.content.Context
@@ -19,7 +20,9 @@ import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.SettingsConstants
import com.anthonyla.paperize.data.settings.SettingsDataStore
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
import com.anthonyla.paperize.feature.wallpaper.domain.repository.SelectedAlbumRepository
import com.anthonyla.paperize.feature.wallpaper.presentation.MainActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -33,7 +36,8 @@ import javax.inject.Inject
@AndroidEntryPoint
class WallpaperService: Service() {
@Inject lateinit var repository: SelectedAlbumRepository
@Inject lateinit var selectedRepository: SelectedAlbumRepository
@Inject lateinit var albumRepository: AlbumRepository
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
private val handler = Handler(Looper.getMainLooper())
private lateinit var runnableCode: Runnable
@@ -110,7 +114,6 @@ class WallpaperService: Service() {
* Clean up the service when it is destroyed
*/
override fun onDestroy() {
Log.d("PaperizeWallpaperChanger", "Service destroyed")
super.onDestroy()
handler.removeCallbacks(runnableCode)
CoroutineScope(Dispatchers.IO).launch {
@@ -123,10 +126,13 @@ class WallpaperService: Service() {
* Creates a notification for the wallpaper service
*/
private fun createNotification(current: Int = 0, total: Int = 0): Notification {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(this, "wallpaper_service_channel")
.setContentTitle("Paperize")
.setContentText("Rotation: $current/$total wallpapers\nInterval: ${formatTime(timeInMinutes)}")
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pendingIntent)
.build()
}
@@ -140,43 +146,84 @@ class WallpaperService: Service() {
settingsDataStoreImpl.putString(SettingsConstants.LAST_SET_TIME, time.format(formatter))
settingsDataStoreImpl.putString(SettingsConstants.NEXT_SET_TIME, time.plusMinutes(timeInMinutes.toLong()).format(formatter))
val setLockWithHome = settingsDataStoreImpl.getBoolean(SettingsConstants.SET_LOCK_WITH_HOME) ?: false
val album = repository.getSelectedAlbum().first().firstOrNull()
album?.let {
val notification = createNotification(it.album.wallpapersInQueue.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
val selectedAlbum = selectedRepository.getSelectedAlbum().first().firstOrNull()
selectedAlbum?.let { it ->
var wallpaper = it.album.wallpapersInQueue.firstOrNull()
// Pick the next wallpaper in the queue
if (wallpaper != null) {
setWallpaper(context, wallpaper.toUri(), setLockWithHome)
repository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1)
)
)
)
}
else {
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
setWallpaper(context, wallpaper.toUri(), setLockWithHome)
repository.upsertSelectedAlbum(
val notification = createNotification(it.album.wallpapersInQueue.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
if (!setWallpaper(context, wallpaper.toUri(), setLockWithHome)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 },
)
)
albumRepository.deleteWallpaper(it1)
}
}
else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = newWallpaperInQueue.drop(1)
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = wallpaper
)
)
)
}
}
// No more wallpapers in the queue -- reshuffle the wallpapers
else {
val notification = createNotification(it.wallpapers.size, it.wallpapers.size)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification)
val newWallpaperInQueue = it.wallpapers.map { it.wallpaperUri }.shuffled()
wallpaper = newWallpaperInQueue.firstOrNull()
if (wallpaper != null) {
if (!setWallpaper(context, wallpaper.toUri(), setLockWithHome)) {
selectedAlbum.wallpapers.firstOrNull{ it.wallpaperUri == wallpaper }
?.let { it1 ->
selectedRepository.deleteWallpaper(it1)
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = it.album.wallpapersInQueue.drop(1),
currentWallpaper = null
),
wallpapers = it.wallpapers.filter { it == it1 }
)
)
albumRepository.deleteWallpaper(it1)
}
}
else {
selectedRepository.upsertSelectedAlbum(
it.copy(
album = it.album.copy(
wallpapersInQueue = newWallpaperInQueue.drop(1),
currentWallpaper = wallpaper
)
)
)
}
} else { onDestroy() }
}
}
}
/**
* Sets the wallpaper to the given uri
*/
private fun setWallpaper(context: Context, wallpaper: Uri, setLockWithHome: Boolean) {
private fun setWallpaper(context: Context, wallpaper: Uri, setLockWithHome: Boolean): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
try {
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
@@ -198,9 +245,8 @@ class WallpaperService: Service() {
false -> WallpaperManager.FLAG_SYSTEM
})
}
} catch (e: IOException) {
Log.e("PaperizeWallpaperChanger", "Error changing wallpaper", e)
}
return true
} catch (e: IOException) { return false }
}
/**
+11
View File
@@ -65,4 +65,15 @@
<string name="circle_2_animation">Circle 2 animation</string>
<string name="circle_1_animation">Circle 1 animation</string>
<string name="circle_3_animation">Circle 3 animation</string>
<string name="wallpaper_changer_has_been_enabled">Wallpaper changer has been enabled.</string>
<string name="wallpaper_changer_has_been_disabled">Wallpaper changer has been disabled.</string>
<string name="dismiss">Dismiss</string>
<string name="has_been_unselected">%1$s has been unselected.</string>
<string name="interval">Interval | %1$s</string>
<string name="minutes">%1$s minutes</string>
<string name="minute">%1$s minute</string>
<string name="hour">%1$s hour</string>
<string name="hours">%1$s hours</string>
<string name="day">%1$s day</string>
<string name="days">%1$s days</string>
</resources>