fix: various bugs

This commit is contained in:
Anthonyy232 committed 2025-12-26 22:19:56 -08:00
1 parent 0385acd539
commit c947b6fc6f
11 files changed
+113 -42

No files matched your search

@@ -0,0 +1,11 @@
package com.anthonyla.paperize.core
/**
* Exception thrown when an album has no wallpapers available
*/
class EmptyAlbumException(message: String) : Exception(message)
/**
* Exception thrown when no valid wallpaper can be found after retries
*/
class NoValidWallpaperException(message: String) : Exception(message)
@@ -89,7 +89,8 @@ interface WallpaperQueueDao {
if (items.isEmpty()) return
// Check if normalization is needed (positions should be 0, 1, 2, ...)
val needsNormalization = items.any { it.queuePosition != items.indexOf(it) }
// Use indexed access instead of indexOf() for O(n) instead of O(n²)
val needsNormalization = items.indices.any { items[it].queuePosition != it }
if (!needsNormalization) return
// Rebuild queue with normalized positions
@@ -117,12 +117,16 @@ class WallpaperRepositoryImpl @Inject constructor(
override suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result<Int> {
return try {
val totalCount = wallpaperDao.getWallpaperCountByAlbum(albumId)
var totalRemoved = 0
val batchSize = 100 // Process in smaller batches to avoid memory spikes
var offset = 0
for (offset in 0 until totalCount step batchSize) {
// Use while loop to handle deletions correctly
// When items are deleted, we don't advance offset since indices shift
while (true) {
val wallpapers = wallpaperDao.getWallpapersByAlbumPaged(albumId, batchSize, offset)
if (wallpapers.isEmpty()) break
val invalidUris = wallpapers
.filter { !it.uri.toUri().isValid(contentResolver) }
.map { it.uri }
@@ -130,6 +134,10 @@ class WallpaperRepositoryImpl @Inject constructor(
if (invalidUris.isNotEmpty()) {
wallpaperDao.deleteWallpapersByUris(invalidUris)
totalRemoved += invalidUris.size
// Don't advance offset when deleting - remaining items shift down
} else {
// Only advance offset if no deletions (all items in batch were valid)
offset += batchSize
}
}
@@ -208,7 +216,8 @@ class WallpaperRepositoryImpl @Inject constructor(
// Prune mutexes for this album to prevent memory leak
// Keys are either albumId (shuffled) or $albumId:$screenType (sequential)
queueRebuildMutexes.keys.filter { it.startsWith(albumId) }.forEach {
// Use exact match or prefix with colon to avoid false positives (e.g., album1 vs album10)
queueRebuildMutexes.keys.filter { it == albumId || it.startsWith("$albumId:") }.forEach {
queueRebuildMutexes.remove(it)
}
@@ -4,6 +4,8 @@ import android.content.Context
import android.graphics.Bitmap
import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.EmptyAlbumException
import com.anthonyla.paperize.core.NoValidWallpaperException
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
@@ -73,7 +75,7 @@ class ChangeWallpaperUseCase @Inject constructor(
if (candidate == null) {
queueRebuildAttempts++
if (queueRebuildAttempts > 2) {
return Result.Error(Exception(context.getString(R.string.no_wallpapers_in_album)))
return Result.Error(EmptyAlbumException(context.getString(R.string.no_wallpapers_in_album)))
}
val rebuildResult = wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
if (rebuildResult is Result.Error) {
@@ -135,7 +137,7 @@ class ChangeWallpaperUseCase @Inject constructor(
}
if (finalBitmap == null) {
return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
return Result.Error(NoValidWallpaperException(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
}
// Check if queue needs refilling
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.presentation.screens.album_view
import com.anthonyla.paperize.core.constants.Constants
import android.content.Context
import android.util.Log
import androidx.core.net.toUri
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
@@ -39,6 +40,10 @@ class AlbumViewViewModel @Inject constructor(
@param:ApplicationContext private val context: Context
) : ViewModel() {
companion object {
private const val TAG = "AlbumViewViewModel"
}
private val albumRoute = savedStateHandle.toRoute<AlbumRoute>()
private val albumId: String = albumRoute.albumId
@@ -92,9 +97,11 @@ class AlbumViewViewModel @Inject constructor(
mediaType = mediaType
)
}
when (albumRepository.addWallpapersToAlbum(albumId, wallpapers)) {
when (val result = albumRepository.addWallpapersToAlbum(albumId, wallpapers)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error adding wallpapers to album", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
@@ -135,9 +142,11 @@ class AlbumViewViewModel @Inject constructor(
wallpapers = wallpapers
)
when (albumRepository.addFolderToAlbum(albumId, folder)) {
when (val result = albumRepository.addFolderToAlbum(albumId, folder)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error adding folder to album", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
@@ -145,9 +154,11 @@ class AlbumViewViewModel @Inject constructor(
fun deleteAlbum() {
viewModelScope.launch {
when (albumRepository.deleteAlbum(albumId)) {
when (val result = albumRepository.deleteAlbum(albumId)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error deleting album", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
@@ -117,9 +117,11 @@ class HomeViewModel @Inject constructor(
fun createAlbum(name: String) {
viewModelScope.launch {
when (createAlbumUseCase(name)) {
when (val result = createAlbumUseCase(name)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error creating album", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
@@ -145,9 +147,11 @@ class HomeViewModel @Inject constructor(
}
// Delete the album
when (deleteAlbumUseCase(albumId)) {
when (val result = deleteAlbumUseCase(albumId)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error deleting album", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.presentation.screens.settings
import com.anthonyla.paperize.core.constants.Constants
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.WallpaperMode
@@ -26,6 +27,10 @@ class SettingsViewModel @Inject constructor(
private val wallpaperScheduler: WallpaperScheduler
) : ViewModel() {
companion object {
private const val TAG = "SettingsViewModel"
}
val appSettings: StateFlow<AppSettings?> = settingsRepository.getAppSettingsFlow()
.stateIn(
scope = viewModelScope,
@@ -79,9 +84,11 @@ class SettingsViewModel @Inject constructor(
wallpaperScheduler.cancelAllWallpaperChanges()
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
when (albumRepository.deleteAllAlbums()) {
when (val result = albumRepository.deleteAllAlbums()) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error deleting albums during mode switch", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
@@ -103,9 +110,11 @@ class SettingsViewModel @Inject constructor(
wallpaperScheduler.cancelAllWallpaperChanges()
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
when (albumRepository.deleteAllAlbums()) {
when (val result = albumRepository.deleteAllAlbums()) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error deleting albums during reset", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.presentation.screens.sort
import com.anthonyla.paperize.core.constants.Constants
import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
@@ -25,6 +26,11 @@ class SortViewModel @Inject constructor(
private val albumRepository: AlbumRepository,
private val wallpaperRepository: WallpaperRepository
) : ViewModel() {
companion object {
private const val TAG = "SortViewModel"
}
private val sortRoute = savedStateHandle.toRoute<SortRoute>()
private val albumId: String = sortRoute.albumId
@@ -57,18 +63,24 @@ class SortViewModel @Inject constructor(
// Update folders with new display orders
state.value.folders.forEach { folder ->
when (albumRepository.updateFolder(folder)) {
when (val result = albumRepository.updateFolder(folder)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> hasError = true
is com.anthonyla.paperize.core.Result.Error -> {
hasError = true
Log.e(TAG, "Error updating folder", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
// Update wallpapers with new display orders
state.value.wallpapers.forEach { wallpaper ->
when (wallpaperRepository.updateWallpaper(wallpaper)) {
when (val result = wallpaperRepository.updateWallpaper(wallpaper)) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> hasError = true
is com.anthonyla.paperize.core.Result.Error -> {
hasError = true
Log.e(TAG, "Error updating wallpaper", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection
import com.anthonyla.paperize.core.constants.Constants
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.WallpaperMode
@@ -16,6 +17,10 @@ class WallpaperModeSelectionViewModel @Inject constructor(
private val wallpaperScheduler: com.anthonyla.paperize.service.worker.WallpaperScheduler
) : ViewModel() {
companion object {
private const val TAG = "WModeSelectionViewModel"
}
/**
* Set wallpaper mode (STATIC or LIVE)
*/
@@ -25,9 +30,11 @@ class WallpaperModeSelectionViewModel @Inject constructor(
wallpaperScheduler.cancelAllWallpaperChanges()
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
when (albumRepository.deleteAllAlbums()) {
when (val result = albumRepository.deleteAllAlbums()) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Error -> {
Log.e(TAG, "Error deleting albums during mode selection", result.exception)
}
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
@@ -12,6 +12,7 @@ import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.EmptyAlbumException
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.domain.repository.SettingsRepository
@@ -156,15 +157,15 @@ class WallpaperChangeService : Service() {
WallpaperManager.FLAG_LOCK
)
// Recycle bitmap after setting to free memory
bitmap.recycle()
Log.d(TAG, "Same wallpaper set for both screens")
} catch (e: Exception) {
Log.e(TAG, "Error setting wallpaper for both screens", e)
} finally {
// Always recycle bitmap to prevent memory leaks
bitmap.recycle()
}
}.onError { error ->
if (error.message?.contains("No wallpapers available in album") == true) {
if (error is EmptyAlbumException) {
handleEmptyAlbumError()
} else {
Log.e(TAG, "Error getting wallpaper bitmap", error)
@@ -222,7 +223,7 @@ class WallpaperChangeService : Service() {
bitmap.recycle()
}
}.onError { error ->
if (error.message?.contains("No wallpapers available in album") == true) {
if (error is EmptyAlbumException) {
handleEmptyAlbumError()
} else {
Log.e(TAG, "Error getting home wallpaper bitmap", error)
@@ -256,7 +257,7 @@ class WallpaperChangeService : Service() {
bitmap.recycle()
}
}.onError { error ->
if (error.message?.contains("No wallpapers available in album") == true) {
if (error is EmptyAlbumException) {
handleEmptyAlbumError()
} else {
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
@@ -13,6 +13,8 @@ import dagger.assisted.AssistedInject
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.first
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
/**
* Background worker that validates and refreshes all albums daily
@@ -45,12 +47,12 @@ class AlbumRefreshWorker @AssistedInject constructor(
}
var totalRemoved = 0
var totalAdded = 0
var failedCount = 0
val totalAdded = AtomicInteger(0)
val failedCount = AtomicInteger(0)
// Refresh each album
albums.forEach { album ->
var albumHasNewWallpapers = false
val albumHasNewWallpapers = AtomicBoolean(false)
// Step 1: Validate and remove invalid URIs
when (val result = refreshAlbumUseCase(album.id)) {
@@ -63,7 +65,7 @@ class AlbumRefreshWorker @AssistedInject constructor(
}
is CoreResult.Error -> {
Log.e(TAG, "Error validating album '${album.name}'", result.exception)
failedCount++
failedCount.incrementAndGet()
}
is CoreResult.Loading -> {
/* Loading state not used */
@@ -89,12 +91,12 @@ class AlbumRefreshWorker @AssistedInject constructor(
when (wallpaperRepository.addWallpaper(wallpaperToAdd)) {
is CoreResult.Success -> {
totalAdded++
albumHasNewWallpapers = true
totalAdded.incrementAndGet()
albumHasNewWallpapers.set(true)
}
is CoreResult.Error -> {
Log.e(TAG, "Error adding wallpaper to album '${album.name}'")
failedCount++
failedCount.incrementAndGet()
}
is CoreResult.Loading -> { /* Not used */ }
}
@@ -110,8 +112,10 @@ class AlbumRefreshWorker @AssistedInject constructor(
}.forEach { it.await() }
}
// Step 3: Refresh folder covers if new wallpapers were added
if (albumHasNewWallpapers) {
// Step 3: Normalize queues and refresh covers if new wallpapers were added
if (albumHasNewWallpapers.get()) {
// Normalize queues so new wallpapers appear in rotation
wallpaperRepository.normalizeAllQueuesForAlbum(album.id)
when (albumRepository.refreshFolderCovers(album.id)) {
is CoreResult.Success -> {
Log.d(TAG, "Album '${album.name}': folder covers refreshed")
@@ -126,7 +130,7 @@ class AlbumRefreshWorker @AssistedInject constructor(
}
}
Log.d(TAG, "Daily album refresh completed: removed $totalRemoved items, added $totalAdded new wallpapers across ${albums.size} albums ($failedCount failures)")
Log.d(TAG, "Daily album refresh completed: removed $totalRemoved items, added ${totalAdded.get()} new wallpapers across ${albums.size} albums (${failedCount.get()} failures)")
// Return success even if some albums failed (partial success)
androidx.work.ListenableWorker.Result.success()