feat(test): added unit testing and added to cicd
This commit is contained in:
1 parent
c46006858f
commit
8a5db6b89e
34 files changed
+3808
-486
No files matched your search
@@ -17,8 +17,6 @@ object Constants {
|
||||
|
||||
// Services
|
||||
const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER"
|
||||
const val ACTION_CHANGE_LIVE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_LIVE_WALLPAPER"
|
||||
const val ACTION_UPDATE_LIVE_EFFECTS = "com.anthonyla.paperize.ACTION_UPDATE_LIVE_EFFECTS"
|
||||
const val ACTION_RELOAD_WALLPAPER = "com.anthonyla.paperize.ACTION_RELOAD_WALLPAPER"
|
||||
|
||||
// WorkManager
|
||||
@@ -32,7 +30,6 @@ object Constants {
|
||||
const val WORK_TAG_BOTH = "wallpaper_change_both_tag"
|
||||
const val WORK_TAG_LIVE = "wallpaper_change_live_tag"
|
||||
const val WORK_TAG_REFRESH = "album_refresh_tag"
|
||||
const val WORK_TAG_IMMEDIATE = "immediate_change"
|
||||
const val MAX_WORK_RETRY_ATTEMPTS = 3
|
||||
|
||||
// Intents
|
||||
@@ -46,9 +43,6 @@ object Constants {
|
||||
const val DEFAULT_GRAYSCALE_PERCENTAGE = 0
|
||||
const val MAX_EFFECT_PERCENTAGE = 100
|
||||
const val SLIDER_EFFECT_STEPS = 99
|
||||
const val HOME_SCREEN_ENTRY_DELAY_MS = 50L
|
||||
const val HOME_SCREEN_SLIDE_OFFSET_DIVISOR = 20
|
||||
const val GL_TEXTURE_SIZE_LIMIT = 4096 // Safe for API 31+ (all support at least 4096)
|
||||
const val DIALOG_MESSAGE_MAX_LINES = 10
|
||||
const val MIN_EFFECT_PERCENTAGE = 0
|
||||
const val FLOW_SUBSCRIPTION_TIMEOUT_MS = 5000L
|
||||
@@ -77,7 +71,6 @@ object Constants {
|
||||
|
||||
// Image processing
|
||||
const val MAX_BLUR_RADIUS = 25.0f
|
||||
const val RGB_MAX_VALUE = 255.0
|
||||
const val BRIGHTNESS_SAMPLE_SIZE = 10 // Pixel sample size for brightness calculation
|
||||
const val DEFAULT_BRIGHTNESS = 0.5f // Default brightness fallback
|
||||
|
||||
@@ -100,18 +93,21 @@ object Constants {
|
||||
val VIGNETTE_GRADIENT_POSITIONS = floatArrayOf(0f, 0.7f, 1f) // Vignette gradient positions
|
||||
|
||||
// Wallpaper loading retry
|
||||
const val WALLPAPER_READ_MAX_ATTEMPTS = 4 // Maximum retry attempts for wallpaper loading
|
||||
const val WALLPAPER_READ_INITIAL_DELAY_MS = 500L // Initial retry delay (with linear backoff)
|
||||
|
||||
// Render nodes
|
||||
const val RENDER_NODE_BLUR = "BlurEffect" // Identifier for blur render node
|
||||
|
||||
// Input validation
|
||||
const val MAX_DAYS_INPUT_LENGTH = 3
|
||||
const val MAX_HOURS_MINUTES_INPUT_LENGTH = 2
|
||||
|
||||
// File types
|
||||
val SUPPORTED_IMAGE_EXTENSIONS = setOf("jpg", "jpeg", "png", "webp", "avif")
|
||||
val SUPPORTED_IMAGE_EXTENSIONS = setOf(
|
||||
"jpg", "jpeg", "png", "webp", "avif",
|
||||
"heic", "heif", // HEIC/HEIF - Apple's high efficiency format
|
||||
"bmp", // Bitmap - legacy but still used
|
||||
"gif", // GIF - mostly for static images (first frame used)
|
||||
"tiff", "tif", // TIFF - high quality archival format
|
||||
"svg" // SVG - vector graphics (rasterized for wallpaper)
|
||||
)
|
||||
|
||||
// Renderer
|
||||
/** Crossfade animation duration in milliseconds - consistent across all refresh rates */
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.core.graphics.get
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
* Utility class for brightness calculations and adaptive adjustments.
|
||||
* Extracted from WallpaperUtil for better testability.
|
||||
*/
|
||||
object BrightnessCalculator {
|
||||
|
||||
/**
|
||||
* Calculate relative luminance of a single pixel using ITU-R BT.709 standard.
|
||||
* Use bitwise operations to avoid dependency on android.graphics.Color in core logic tests.
|
||||
*/
|
||||
fun calculateLuminance(pixel: Int): Double {
|
||||
val r = ((pixel shr 16) and 0xFF) / 255.0
|
||||
val g = ((pixel shr 8) and 0xFF) / 255.0
|
||||
val b = (pixel and 0xFF) / 255.0
|
||||
|
||||
return Constants.LUMINANCE_RED * r + Constants.LUMINANCE_GREEN * g + Constants.LUMINANCE_BLUE * b
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate brightness estimate of bitmap (0.0 - 1.0)
|
||||
* Uses luminance calculation based on RGB values.
|
||||
*/
|
||||
fun calculateBitmapBrightness(bitmap: Bitmap): Float {
|
||||
val sampleSize = Constants.BRIGHTNESS_SAMPLE_SIZE
|
||||
var totalLuminance = 0.0
|
||||
var pixelCount = 0
|
||||
|
||||
for (x in 0 until bitmap.width step sampleSize) {
|
||||
for (y in 0 until bitmap.height step sampleSize) {
|
||||
val pixel = bitmap[x, y]
|
||||
totalLuminance += calculateLuminance(pixel)
|
||||
pixelCount++
|
||||
}
|
||||
}
|
||||
|
||||
return if (pixelCount > 0) {
|
||||
(totalLuminance / pixelCount).toFloat()
|
||||
} else {
|
||||
Constants.DEFAULT_BRIGHTNESS
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get adaptive brightness multiplier factor based on system dark/light mode.
|
||||
*
|
||||
* @param isDarkMode Whether the system is in dark mode
|
||||
* @param brightness Current image brightness (0.0 to 1.0)
|
||||
* @return Multiplier factor to apply to colors
|
||||
*/
|
||||
fun getAdaptiveMultiplier(isDarkMode: Boolean, brightness: Float): Float {
|
||||
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
|
||||
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
|
||||
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
|
||||
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
|
||||
|
||||
// Avoid issues with very dark items or division by zero
|
||||
if (brightness < 0.01f) return 1.0f
|
||||
|
||||
return when {
|
||||
// In dark mode with very bright image: darken it
|
||||
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
|
||||
// In light mode with very dark image: brighten it
|
||||
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
|
||||
// No adjustment needed
|
||||
else -> 1.0f
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,11 @@ fun Uri.isValid(contentResolver: ContentResolver): Boolean {
|
||||
contentResolver.query(this, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
} ?: false
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Fallback to opening the stream if the provider doesn't support the specific query
|
||||
try {
|
||||
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
|
||||
} catch (e2: Exception) {
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ fun Uri.scanFolderForImages(context: Context): List<Uri> {
|
||||
when {
|
||||
file.isDirectory -> scanDirectory(file) // Recursively scan subdirectories
|
||||
file.isFile && file.type in supportedTypes -> {
|
||||
file.uri?.let { imageUris.add(it) }
|
||||
imageUris.add(file.uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
/**
|
||||
* Utility object for building and managing wallpaper queues
|
||||
* Extracted from WallpaperRepositoryImpl for testability
|
||||
*
|
||||
* Note: The DAO-specific operations remain in the repository,
|
||||
* but the pure logic functions are extracted here for testing.
|
||||
*/
|
||||
object QueueBuilder {
|
||||
|
||||
/**
|
||||
* Build a queue of wallpaper IDs based on display order (sequential mode)
|
||||
* @param wallpaperIds List of wallpaper IDs with their display orders
|
||||
* @return List of IDs sorted by display order
|
||||
*/
|
||||
fun buildSequentialQueue(wallpaperIds: List<Pair<String, Int>>): List<String> {
|
||||
return wallpaperIds.sortedBy { it.second }.map { it.first }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a shuffled queue of wallpaper IDs
|
||||
* @param wallpaperIds List of wallpaper IDs to shuffle
|
||||
* @return Shuffled list of IDs
|
||||
*/
|
||||
fun buildShuffledQueue(wallpaperIds: List<String>): List<String> {
|
||||
return wallpaperIds.shuffled()
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if queue positions need normalization
|
||||
* Positions need normalization if they have gaps (e.g., 0, 2, 4 instead of 0, 1, 2)
|
||||
* @param positions Current queue positions
|
||||
* @return True if normalization is needed, false otherwise
|
||||
*/
|
||||
fun needsNormalization(positions: List<Int>): Boolean {
|
||||
if (positions.isEmpty()) return false
|
||||
val sorted = positions.sorted()
|
||||
return sorted.indices.any { sorted[it] != it }
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize queue positions to be sequential starting from 0
|
||||
* @param positions Current queue positions (may have gaps)
|
||||
* @return Normalized positions (0, 1, 2, ...)
|
||||
*/
|
||||
fun normalizePositions(positions: List<Int>): List<Int> {
|
||||
return positions.indices.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge existing queue with new wallpapers while preserving existing order
|
||||
* Used when new wallpapers are added to an album during shuffle mode
|
||||
* @param existingQueueIds Current queue order (filtered to valid IDs)
|
||||
* @param allWallpaperIds All current wallpaper IDs in the album
|
||||
* @return Combined list with existing order preserved, new IDs shuffled at end
|
||||
*/
|
||||
fun mergeWithExistingQueue(
|
||||
existingQueueIds: List<String>,
|
||||
allWallpaperIds: List<String>
|
||||
): List<String> {
|
||||
// Filter existing queue to only include IDs that still exist
|
||||
val existingValid = existingQueueIds.filter { it in allWallpaperIds }
|
||||
|
||||
// Find new wallpapers not in existing queue
|
||||
val newWallpaperIds = allWallpaperIds.filter { it !in existingQueueIds }
|
||||
|
||||
// Return existing order with new wallpapers shuffled at the end
|
||||
return existingValid + newWallpaperIds.shuffled()
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic version of mergeWithExistingQueue for testing
|
||||
* New wallpapers are appended in their original order instead of shuffled
|
||||
*/
|
||||
fun mergeWithExistingQueueDeterministic(
|
||||
existingQueueIds: List<String>,
|
||||
allWallpaperIds: List<String>
|
||||
): List<String> {
|
||||
val existingValid = existingQueueIds.filter { it in allWallpaperIds }
|
||||
val newWallpaperIds = allWallpaperIds.filter { it !in existingQueueIds }
|
||||
return existingValid + newWallpaperIds
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a wallpaper queue based on shuffle and existing queues
|
||||
* @param wallpapers Current list of wallpapers in the album
|
||||
* @param shuffle Whether shuffle is enabled
|
||||
* @param otherScreenQueue Optional existing queue for another screen type to synchronize with
|
||||
* @return List of wallpaper IDs for the new queue
|
||||
*/
|
||||
fun buildQueue(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper>,
|
||||
shuffle: Boolean,
|
||||
otherScreenQueue: List<String>? = null
|
||||
): List<String> {
|
||||
return if (shuffle) {
|
||||
if (otherScreenQueue != null && otherScreenQueue.isNotEmpty()) {
|
||||
// Synchronize with existing queue from another screen
|
||||
mergeWithExistingQueue(otherScreenQueue, wallpapers.map { it.id })
|
||||
} else {
|
||||
// New shuffled order
|
||||
buildShuffledQueue(wallpapers.map { it.id })
|
||||
}
|
||||
} else {
|
||||
// Sequential order by displayOrder
|
||||
buildSequentialQueue(wallpapers.map { it.id to it.displayOrder })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Utility object for sorting wallpapers and folders
|
||||
* Extracted from ViewModels for testability
|
||||
*/
|
||||
object WallpaperSorter {
|
||||
|
||||
/**
|
||||
* Sort wallpapers by filename (alphabetically)
|
||||
* @param wallpapers List of wallpapers to sort
|
||||
* @param ascending True for A-Z, false for Z-A
|
||||
* @return New sorted list preserving original list
|
||||
*/
|
||||
fun sortWallpapersByName(
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): List<Wallpaper> {
|
||||
return if (ascending) {
|
||||
wallpapers.sortedBy { it.fileName.lowercase() }
|
||||
} else {
|
||||
wallpapers.sortedByDescending { it.fileName.lowercase() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort wallpapers by date added (addedAt timestamp)
|
||||
* @param wallpapers List of wallpapers to sort
|
||||
* @param ascending True for oldest first, false for newest first
|
||||
* @return New sorted list preserving original list
|
||||
*/
|
||||
fun sortWallpapersByDateAdded(
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): List<Wallpaper> {
|
||||
return if (ascending) {
|
||||
wallpapers.sortedBy { it.addedAt }
|
||||
} else {
|
||||
wallpapers.sortedByDescending { it.addedAt }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort wallpapers by date modified (dateModified timestamp)
|
||||
* @param wallpapers List of wallpapers to sort
|
||||
* @param ascending True for oldest first, false for newest first
|
||||
* @return New sorted list preserving original list
|
||||
*/
|
||||
fun sortWallpapersByDateModified(
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): List<Wallpaper> {
|
||||
return if (ascending) {
|
||||
wallpapers.sortedBy { it.dateModified }
|
||||
} else {
|
||||
wallpapers.sortedByDescending { it.dateModified }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort folders by name (alphabetically)
|
||||
*/
|
||||
fun sortFoldersByName(
|
||||
folders: List<Folder>,
|
||||
ascending: Boolean = true
|
||||
): List<Folder> {
|
||||
return if (ascending) {
|
||||
folders.sortedBy { it.name.lowercase() }
|
||||
} else {
|
||||
folders.sortedByDescending { it.name.lowercase() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort folders by date modified
|
||||
*/
|
||||
fun sortFoldersByDateModified(
|
||||
folders: List<Folder>,
|
||||
ascending: Boolean = true
|
||||
): List<Folder> {
|
||||
return if (ascending) {
|
||||
folders.sortedBy { it.dateModified }
|
||||
} else {
|
||||
folders.sortedByDescending { it.dateModified }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift a wallpaper within a list (drag and drop)
|
||||
* @param wallpapers Current list of wallpapers
|
||||
* @param fromUri URI of the wallpaper being moved
|
||||
* @param toUri URI of the target position
|
||||
* @return New list with wallpaper moved and display orders updated
|
||||
*/
|
||||
fun shiftWallpaper(
|
||||
wallpapers: List<Wallpaper>,
|
||||
fromUri: String,
|
||||
toUri: String
|
||||
): List<Wallpaper> {
|
||||
val mutableList = wallpapers.toMutableList()
|
||||
val fromIndex = mutableList.indexOfFirst { it.uri == fromUri }
|
||||
val toIndex = mutableList.indexOfFirst { it.uri == toUri }
|
||||
|
||||
if (fromIndex == -1 || toIndex == -1) return wallpapers
|
||||
|
||||
val movedItem = mutableList.removeAt(fromIndex)
|
||||
mutableList.add(toIndex, movedItem)
|
||||
|
||||
return applyDisplayOrder(mutableList)
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift a folder within a list (drag and drop)
|
||||
* @param folders Current list of folders
|
||||
* @param fromUri URI of the folder being moved
|
||||
* @param toUri URI of the target position
|
||||
* @return New list with folder moved and display orders updated
|
||||
*/
|
||||
fun shiftFolder(
|
||||
folders: List<Folder>,
|
||||
fromUri: String,
|
||||
toUri: String
|
||||
): List<Folder> {
|
||||
val mutableList = folders.toMutableList()
|
||||
val fromIndex = mutableList.indexOfFirst { it.uri == fromUri }
|
||||
val toIndex = mutableList.indexOfFirst { it.uri == toUri }
|
||||
|
||||
if (fromIndex == -1 || toIndex == -1) return folders
|
||||
|
||||
val movedItem = mutableList.removeAt(fromIndex)
|
||||
mutableList.add(toIndex, movedItem)
|
||||
|
||||
return applyFolderDisplayOrder(mutableList)
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift a wallpaper within a folder's wallpaper list
|
||||
* @param folders List of all folders
|
||||
* @param folderId ID of the folder containing the wallpaper
|
||||
* @param fromUri URI of the wallpaper being moved
|
||||
* @param toUri URI of the target position
|
||||
* @return Pair of updated folders list and the new cover URI for the folder
|
||||
*/
|
||||
fun shiftWallpaperInFolder(
|
||||
folders: List<Folder>,
|
||||
folderId: String,
|
||||
fromUri: String,
|
||||
toUri: String
|
||||
): List<Folder> {
|
||||
return folders.map { folder ->
|
||||
if (folder.id == folderId) {
|
||||
val updatedWallpapers = shiftWallpaper(folder.wallpapers, fromUri, toUri)
|
||||
folder.copy(
|
||||
wallpapers = updatedWallpapers,
|
||||
coverUri = updatedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
} else {
|
||||
folder
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort all folders and wallpapers alphabetically
|
||||
*/
|
||||
fun sortAllAlphabetically(
|
||||
folders: List<Folder>,
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByName(folder.wallpapers, ascending)
|
||||
folder.copy(wallpapers = applyDisplayOrder(sortedWallpapers))
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
sortedFolders.sortedBy { it.name.lowercase() }
|
||||
} else {
|
||||
sortedFolders.sortedByDescending { it.name.lowercase() }
|
||||
}
|
||||
|
||||
val finalWallpapers = sortWallpapersByName(wallpapers, ascending)
|
||||
|
||||
return Pair(
|
||||
applyFolderDisplayOrder(finalFolders),
|
||||
applyDisplayOrder(finalWallpapers)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort all folders and wallpapers by date modified
|
||||
*/
|
||||
fun sortAllByDateModified(
|
||||
folders: List<Folder>,
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByDateModified(folder.wallpapers, ascending)
|
||||
folder.copy(wallpapers = applyDisplayOrder(sortedWallpapers))
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
sortedFolders.sortedBy { it.dateModified }
|
||||
} else {
|
||||
sortedFolders.sortedByDescending { it.dateModified }
|
||||
}
|
||||
|
||||
val finalWallpapers = sortWallpapersByDateModified(wallpapers, ascending)
|
||||
|
||||
return Pair(
|
||||
applyFolderDisplayOrder(finalFolders),
|
||||
applyDisplayOrder(finalWallpapers)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply displayOrder indices to sorted wallpapers
|
||||
* @param wallpapers Sorted list of wallpapers
|
||||
* @return New list with displayOrder updated to match list position
|
||||
*/
|
||||
fun applyDisplayOrder(wallpapers: List<Wallpaper>): List<Wallpaper> {
|
||||
return wallpapers.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply displayOrder indices to sorted folders
|
||||
* @param folders Sorted list of folders
|
||||
* @return New list with folder moved and display orders updated
|
||||
*/
|
||||
fun applyFolderDisplayOrder(folders: List<Folder>): List<Folder> {
|
||||
return folders.mapIndexed { index, folder ->
|
||||
folder.copy(displayOrder = index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
@@ -44,7 +43,6 @@ import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
*/
|
||||
|
||||
private const val TAG = "WallpaperUtil"
|
||||
private val SharedPaintFilterAntiAlias = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
|
||||
/**
|
||||
* Get the dimensions of the image from the URI
|
||||
@@ -272,128 +270,8 @@ private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fit method
|
||||
* The bitmap will fit into the given dimensions while maintaining aspect ratio
|
||||
*/
|
||||
/**
|
||||
* Scale a bitmap using the fit method
|
||||
* The bitmap will fit into the given dimensions while maintaining aspect ratio
|
||||
*/
|
||||
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
|
||||
Log.w(TAG, "Invalid dimensions for fitBitmap: source=${source.width}x${source.height}, target=${width}x${height}")
|
||||
return source
|
||||
}
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val scaleX = width.toFloat() / source.width
|
||||
val scaleY = height.toFloat() / source.height
|
||||
// Use the smaller scale factor to ensure the entire image fits within the target dimensions
|
||||
val scale = minOf(scaleX, scaleY)
|
||||
|
||||
val scaledSourceWidth = source.width * scale
|
||||
val scaledSourceHeight = source.height * scale
|
||||
|
||||
val xOffset = (width - scaledSourceWidth) / 2f
|
||||
val yOffset = (height - scaledSourceHeight) / 2f
|
||||
|
||||
val matrix = Matrix().apply {
|
||||
postScale(scale, scale)
|
||||
postTranslate(xOffset, yOffset)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error fitting bitmap: $e")
|
||||
source
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM fitting bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fill method (crop to fill dimensions)
|
||||
*/
|
||||
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
|
||||
Log.w(TAG, "Invalid dimensions for fillBitmap: source=${source.width}x${source.height}, target=${width}x${height}")
|
||||
return source
|
||||
}
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val sourceAspect = source.width.toFloat() / source.height.toFloat()
|
||||
val targetAspect = width.toFloat() / height.toFloat()
|
||||
|
||||
val scale: Float
|
||||
val xOffset: Float
|
||||
val yOffset: Float
|
||||
|
||||
if (sourceAspect >= targetAspect) {
|
||||
scale = height.toFloat() / source.height.toFloat()
|
||||
xOffset = (width - source.width * scale) / 2f
|
||||
yOffset = 0f
|
||||
} else {
|
||||
scale = width.toFloat() / source.width.toFloat()
|
||||
xOffset = 0f
|
||||
yOffset = (height - source.height * scale) / 2f
|
||||
}
|
||||
|
||||
val matrix = Matrix().apply {
|
||||
postScale(scale, scale)
|
||||
postTranslate(xOffset, yOffset)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error filling bitmap: $e")
|
||||
source
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM filling bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stretch the bitmap to fit the given dimensions
|
||||
*/
|
||||
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
|
||||
Log.w(TAG, "Invalid dimensions for stretchBitmap: source=${source.width}x${source.height}, target=${width}x${height}")
|
||||
return source
|
||||
}
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val matrix = Matrix().apply {
|
||||
setScale(
|
||||
width.toFloat() / source.width,
|
||||
height.toFloat() / source.height
|
||||
)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error stretching bitmap: $e")
|
||||
source
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM stretching bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Darken the bitmap by a certain percentage
|
||||
@@ -444,7 +322,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
val renderNode = RenderNode("BlurEffect")
|
||||
val hardwareRenderer = HardwareRenderer()
|
||||
|
||||
var resultBitmap: Bitmap? = null
|
||||
var resultBitmap: Bitmap?
|
||||
try {
|
||||
hardwareRenderer.setSurface(imageReader.surface)
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
@@ -491,7 +369,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
imageReader.close()
|
||||
}
|
||||
|
||||
return resultBitmap ?: throw IllegalStateException("Blur operation failed - resultBitmap is null")
|
||||
return resultBitmap
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -573,30 +451,7 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
* Uses luminance calculation based on RGB values
|
||||
*/
|
||||
fun calculateBitmapBrightness(bitmap: Bitmap): Float {
|
||||
// Sample pixels to estimate brightness (sampling for performance)
|
||||
val sampleSize = Constants.BRIGHTNESS_SAMPLE_SIZE
|
||||
var totalLuminance = 0.0
|
||||
var pixelCount = 0
|
||||
|
||||
for (x in 0 until bitmap.width step sampleSize) {
|
||||
for (y in 0 until bitmap.height step sampleSize) {
|
||||
val pixel = bitmap.getPixel(x, y)
|
||||
val r = Color.red(pixel) / 255.0
|
||||
val g = Color.green(pixel) / 255.0
|
||||
val b = Color.blue(pixel) / 255.0
|
||||
|
||||
// Calculate relative luminance using ITU-R BT.709 standard
|
||||
val luminance = Constants.LUMINANCE_RED * r + Constants.LUMINANCE_GREEN * g + Constants.LUMINANCE_BLUE * b
|
||||
totalLuminance += luminance
|
||||
pixelCount++
|
||||
}
|
||||
}
|
||||
|
||||
return if (pixelCount > 0) {
|
||||
(totalLuminance / pixelCount).toFloat()
|
||||
} else {
|
||||
0.5f
|
||||
}
|
||||
return BrightnessCalculator.calculateBitmapBrightness(bitmap)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -621,15 +476,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
return source
|
||||
}
|
||||
|
||||
/**
|
||||
* Adaptive brightness adjustment based on system dark/light mode
|
||||
* In dark mode: darkens bright images for better viewing
|
||||
* In light mode: brightens dark images for better visibility
|
||||
*
|
||||
* @param context Application context
|
||||
* @param source Source bitmap
|
||||
* @return Adjusted bitmap (or original if no adjustment needed)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get adaptive brightness multiplier factor based on system dark/light mode
|
||||
*
|
||||
@@ -639,74 +486,24 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
*/
|
||||
fun getAdaptiveBrightnessMultiplier(context: Context, brightness: Float): Float {
|
||||
val isDarkMode = (context.resources.configuration.uiMode and
|
||||
android.content.res.Configuration.UI_MODE_NIGHT_MASK) == android.content.res.Configuration.UI_MODE_NIGHT_YES
|
||||
|
||||
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
|
||||
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
|
||||
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
|
||||
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
|
||||
|
||||
// Avoid issues with very dark items
|
||||
if (brightness < 0.01f) return 1.0f
|
||||
|
||||
return when {
|
||||
// In dark mode with very bright image: darken it
|
||||
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
|
||||
// In light mode with very dark image: brighten it
|
||||
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
|
||||
// No adjustment needed
|
||||
else -> 1.0f
|
||||
}
|
||||
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
|
||||
|
||||
return BrightnessCalculator.getAdaptiveMultiplier(isDarkMode, brightness)
|
||||
}
|
||||
|
||||
fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
|
||||
val isDarkMode = (context.resources.configuration.uiMode and
|
||||
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
|
||||
|
||||
val currentBrightness = calculateBitmapBrightness(source)
|
||||
val currentBrightness = BrightnessCalculator.calculateBitmapBrightness(source)
|
||||
val adjustmentFactor = BrightnessCalculator.getAdaptiveMultiplier(isDarkMode, currentBrightness)
|
||||
|
||||
// Thresholds from WallYou
|
||||
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
|
||||
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
|
||||
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
|
||||
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
|
||||
|
||||
// Avoid division by zero or very small numbers
|
||||
if (currentBrightness < 0.01f) {
|
||||
Log.d(TAG, "Image is too dark for adaptive brightness adjustment (brightness: $currentBrightness)")
|
||||
return source
|
||||
}
|
||||
|
||||
return when {
|
||||
// In dark mode with very bright image: darken it
|
||||
isDarkMode && currentBrightness > lightBrightnessMin -> {
|
||||
val adjustmentFactor = targetBrightnessDark / currentBrightness
|
||||
Log.d(TAG, "Dark mode: Darkening bright image from $currentBrightness to $targetBrightnessDark")
|
||||
adjustBitmapBrightness(source, adjustmentFactor)
|
||||
}
|
||||
// In light mode with very dark image: brighten it
|
||||
!isDarkMode && currentBrightness < darkBrightnessMax -> {
|
||||
val adjustmentFactor = targetBrightnessLight / currentBrightness
|
||||
Log.d(TAG, "Light mode: Brightening dark image from $currentBrightness to $targetBrightnessLight")
|
||||
adjustBitmapBrightness(source, adjustmentFactor)
|
||||
}
|
||||
// No adjustment needed
|
||||
else -> {
|
||||
Log.d(TAG, "No adaptive brightness adjustment needed (brightness: $currentBrightness, dark mode: $isDarkMode)")
|
||||
source
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply scaling to bitmap based on ScalingType
|
||||
*/
|
||||
fun scaleBitmap(source: Bitmap, width: Int, height: Int, scaling: ScalingType): Bitmap {
|
||||
return when (scaling) {
|
||||
ScalingType.FILL -> fillBitmap(source, width, height)
|
||||
ScalingType.FIT -> fitBitmap(source, width, height)
|
||||
ScalingType.STRETCH -> stretchBitmap(source, width, height)
|
||||
ScalingType.NONE -> source
|
||||
return if (adjustmentFactor != 1.0f) {
|
||||
Log.d(TAG, "Adaptive brightness adjustment factor: $adjustmentFactor (brightness: $currentBrightness, dark mode: $isDarkMode)")
|
||||
adjustBitmapBrightness(source, adjustmentFactor)
|
||||
} else {
|
||||
Log.d(TAG, "No adaptive brightness adjustment needed (brightness: $currentBrightness, dark mode: $isDarkMode)")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,7 +512,6 @@ fun scaleBitmap(source: Bitmap, width: Int, height: Int, scaling: ScalingType):
|
||||
* Properly manages bitmap lifecycle by recycling intermediate results
|
||||
*/
|
||||
fun processBitmap(
|
||||
context: Context,
|
||||
source: Bitmap,
|
||||
enableDarken: Boolean = false,
|
||||
darkenPercent: Int = 0,
|
||||
@@ -805,16 +601,6 @@ fun Uri.detectMediaType(context: Context): WallpaperMediaType? {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that media type is supported in the current wallpaper mode
|
||||
*/
|
||||
fun WallpaperMediaType.isSupportedInMode(mode: com.anthonyla.paperize.core.WallpaperMode): Boolean {
|
||||
return when (mode) {
|
||||
com.anthonyla.paperize.core.WallpaperMode.STATIC -> this.supportedInStaticMode
|
||||
com.anthonyla.paperize.core.WallpaperMode.LIVE -> this.supportedInLiveMode
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Paperize live wallpaper is currently active/selected
|
||||
* Returns true if the Paperize live wallpaper service is the current wallpaper
|
||||
|
||||
+18
-32
@@ -3,6 +3,7 @@ package com.anthonyla.paperize.data.repository
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
@@ -123,7 +124,7 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
for (offset in 0 until totalCount step batchSize) {
|
||||
val wallpapers = wallpaperDao.getWallpapersByAlbumPaged(albumId, batchSize, offset)
|
||||
val invalidUris = wallpapers
|
||||
.filter { !Uri.parse(it.uri).isValid(contentResolver) }
|
||||
.filter { !it.uri.toUri().isValid(contentResolver) }
|
||||
.map { it.uri }
|
||||
|
||||
if (invalidUris.isNotEmpty()) {
|
||||
@@ -160,45 +161,30 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
|
||||
// If shuffle is enabled, check if there's an existing queue for another screen type
|
||||
// with the same album to maintain synchronized order
|
||||
val wallpaperIds = if (shuffle) {
|
||||
// Check other screen types for existing queue with same album
|
||||
val otherScreenType = when (screenType) {
|
||||
val otherScreenType = if (shuffle) {
|
||||
when (screenType) {
|
||||
ScreenType.HOME -> ScreenType.LOCK
|
||||
ScreenType.LOCK -> ScreenType.HOME
|
||||
ScreenType.BOTH -> null
|
||||
ScreenType.LIVE -> null
|
||||
}
|
||||
} else null
|
||||
|
||||
val existingQueueIds = otherScreenType?.let {
|
||||
try {
|
||||
wallpaperQueueDao.getQueueItems(albumId, it)
|
||||
.map { queueItem -> queueItem.wallpaperId }
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
val otherScreenQueueIds = otherScreenType?.let {
|
||||
try {
|
||||
wallpaperQueueDao.getQueueItems(albumId, it)
|
||||
.map { queueItem -> queueItem.wallpaperId }
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
// If another screen type has a queue for the same album, use that order
|
||||
// Otherwise, create a new shuffled order
|
||||
if (existingQueueIds != null && existingQueueIds.isNotEmpty()) {
|
||||
// Filter to only include IDs that still exist in the current wallpaper list
|
||||
val currentWallpaperIds = wallpapers.map { it.id }.toSet()
|
||||
val filteredIds = existingQueueIds.filter { it in currentWallpaperIds }
|
||||
|
||||
// Add any new wallpapers that aren't in the existing queue
|
||||
val newWallpaperIds = wallpapers
|
||||
.map { it.id }
|
||||
.filter { it !in existingQueueIds }
|
||||
.shuffled()
|
||||
|
||||
filteredIds + newWallpaperIds
|
||||
} else {
|
||||
wallpapers.map { it.id }.shuffled()
|
||||
}
|
||||
} else {
|
||||
wallpapers.sortedBy { it.displayOrder }.map { it.id }
|
||||
}
|
||||
|
||||
val wallpaperIds = com.anthonyla.paperize.core.util.QueueBuilder.buildQueue(
|
||||
wallpapers = wallpapers.toDomainModels(),
|
||||
shuffle = shuffle,
|
||||
otherScreenQueue = otherScreenQueueIds
|
||||
)
|
||||
|
||||
wallpaperQueueDao.rebuildQueue(albumId, screenType, wallpaperIds)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
@@ -281,7 +267,7 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Skip failed items
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.Result
|
||||
@@ -12,7 +11,6 @@ import com.anthonyla.paperize.core.util.getDeviceScreenSize
|
||||
import com.anthonyla.paperize.core.util.isValid
|
||||
import com.anthonyla.paperize.core.util.processBitmap
|
||||
import com.anthonyla.paperize.core.util.retrieveBitmap
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
@@ -94,7 +92,6 @@ class ChangeWallpaperUseCase @Inject constructor(
|
||||
// Apply effects directly to the retrieved bitmap
|
||||
|
||||
var processedBitmap = processBitmap(
|
||||
context = context,
|
||||
source = bitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
@@ -125,7 +122,7 @@ class ChangeWallpaperUseCase @Inject constructor(
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
maxRetries--
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Error during processing, skip this wallpaper
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
maxRetries--
|
||||
|
||||
+38
-117
@@ -91,50 +91,31 @@ class SortViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
is SortEvent.ShiftFolder -> {
|
||||
val currentFolders = state.value.folders.toMutableList()
|
||||
val fromIndex = currentFolders.indexOfFirst { it.uri == event.from.key }
|
||||
val toIndex = currentFolders.indexOfFirst { it.uri == event.to.key }
|
||||
val movedFolder = currentFolders.removeAt(fromIndex)
|
||||
currentFolders.add(toIndex, movedFolder)
|
||||
currentFolders.forEachIndexed { index, folder ->
|
||||
currentFolders[index] = folder.copy(displayOrder = index)
|
||||
}
|
||||
_state.value = state.value.copy(folders = currentFolders)
|
||||
val updatedFolders = com.anthonyla.paperize.core.util.WallpaperSorter.shiftFolder(
|
||||
folders = state.value.folders,
|
||||
fromUri = event.from.key as String,
|
||||
toUri = event.to.key as String
|
||||
)
|
||||
_state.value = state.value.copy(folders = updatedFolders)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftFolderWallpaper -> {
|
||||
val folder = state.value.folders.find { it.id == event.folderId }
|
||||
val currentWallpapers = folder?.wallpapers?.toMutableList() ?: return
|
||||
val fromIndex = currentWallpapers.indexOfFirst { it.uri == event.from.key }
|
||||
val toIndex = currentWallpapers.indexOfFirst { it.uri == event.to.key }
|
||||
val movedWallpaper = currentWallpapers.removeAt(fromIndex)
|
||||
currentWallpapers.add(toIndex, movedWallpaper)
|
||||
currentWallpapers.forEachIndexed { index, wallpaper ->
|
||||
currentWallpapers[index] = wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
val updatedFolders = state.value.folders.map { folder ->
|
||||
if (folder.id == event.folderId) {
|
||||
folder.copy(
|
||||
wallpapers = currentWallpapers,
|
||||
coverUri = currentWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
} else {
|
||||
folder
|
||||
}
|
||||
}
|
||||
val updatedFolders = com.anthonyla.paperize.core.util.WallpaperSorter.shiftWallpaperInFolder(
|
||||
folders = state.value.folders,
|
||||
folderId = event.folderId,
|
||||
fromUri = event.from.key as String,
|
||||
toUri = event.to.key as String
|
||||
)
|
||||
_state.value = state.value.copy(folders = updatedFolders)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftWallpaper -> {
|
||||
val currentWallpapers = state.value.wallpapers.toMutableList()
|
||||
val fromIndex = currentWallpapers.indexOfFirst { it.uri == event.from.key }
|
||||
val toIndex = currentWallpapers.indexOfFirst { it.uri == event.to.key }
|
||||
val movedWallpaper = currentWallpapers.removeAt(fromIndex)
|
||||
currentWallpapers.add(toIndex, movedWallpaper)
|
||||
currentWallpapers.forEachIndexed { index, wallpaper ->
|
||||
currentWallpapers[index] = wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
_state.value = state.value.copy(wallpapers = currentWallpapers)
|
||||
val updatedWallpapers = com.anthonyla.paperize.core.util.WallpaperSorter.shiftWallpaper(
|
||||
wallpapers = state.value.wallpapers,
|
||||
fromUri = event.from.key as String,
|
||||
toUri = event.to.key as String
|
||||
)
|
||||
_state.value = state.value.copy(wallpapers = updatedWallpapers)
|
||||
}
|
||||
|
||||
is SortEvent.Reset -> {
|
||||
@@ -142,26 +123,11 @@ class SortViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
is SortEvent.SortAlphabetically -> {
|
||||
val sortedFolders = state.value.folders
|
||||
.map { folder ->
|
||||
val sortedFolderWallpapers = folder.wallpapers
|
||||
.sortedBy { it.fileName }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
folder.copy(wallpapers = sortedFolderWallpapers)
|
||||
}
|
||||
.sortedBy { it.name }
|
||||
.mapIndexed { index, folder ->
|
||||
folder.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val sortedWallpapers = state.value.wallpapers
|
||||
.sortedBy { it.fileName }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllAlphabetically(
|
||||
folders = state.value.folders,
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = true
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
@@ -169,26 +135,11 @@ class SortViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
is SortEvent.SortAlphabeticallyReverse -> {
|
||||
val sortedFolders = state.value.folders
|
||||
.map { folder ->
|
||||
val sortedFolderWallpapers = folder.wallpapers
|
||||
.sortedByDescending { it.fileName }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
folder.copy(wallpapers = sortedFolderWallpapers)
|
||||
}
|
||||
.sortedByDescending { it.name }
|
||||
.mapIndexed { index, folder ->
|
||||
folder.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val sortedWallpapers = state.value.wallpapers
|
||||
.sortedByDescending { it.fileName }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllAlphabetically(
|
||||
folders = state.value.folders,
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = false
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
@@ -196,26 +147,11 @@ class SortViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
is SortEvent.SortByLastModified -> {
|
||||
val sortedFolders = state.value.folders
|
||||
.map { folder ->
|
||||
val sortedFolderWallpapers = folder.wallpapers
|
||||
.sortedBy { it.dateModified }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
folder.copy(wallpapers = sortedFolderWallpapers)
|
||||
}
|
||||
.sortedBy { it.dateModified }
|
||||
.mapIndexed { index, folder ->
|
||||
folder.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val sortedWallpapers = state.value.wallpapers
|
||||
.sortedBy { it.dateModified }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllByDateModified(
|
||||
folders = state.value.folders,
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = true
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
@@ -223,26 +159,11 @@ class SortViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
is SortEvent.SortByLastModifiedReverse -> {
|
||||
val sortedFolders = state.value.folders
|
||||
.map { folder ->
|
||||
val sortedFolderWallpapers = folder.wallpapers
|
||||
.sortedByDescending { it.dateModified }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
folder.copy(wallpapers = sortedFolderWallpapers)
|
||||
}
|
||||
.sortedByDescending { it.dateModified }
|
||||
.mapIndexed { index, folder ->
|
||||
folder.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val sortedWallpapers = state.value.wallpapers
|
||||
.sortedByDescending { it.dateModified }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
|
||||
val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllByDateModified(
|
||||
folders = state.value.folders,
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = false
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
|
||||
+18
-2
@@ -1,7 +1,5 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.view.GestureDetector
|
||||
import android.view.MotionEvent
|
||||
@@ -43,6 +41,11 @@ import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.isValid
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.service.livewallpaper.gl.GLCompatibility
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
@EntryPoint
|
||||
@InstallIn(SingletonComponent::class)
|
||||
@@ -99,6 +102,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
private lateinit var renderController: PaperizeRenderController
|
||||
private val engineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
private var currentAlbumId: String? = null
|
||||
private var hasShownParallaxWarning = false
|
||||
|
||||
private val gestureDetector = GestureDetector(
|
||||
this@PaperizeLiveWallpaperService,
|
||||
@@ -284,6 +288,18 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
renderer.updateScalingType(scalingType)
|
||||
renderer.updateAdaptiveBrightness(settings.adaptiveBrightness)
|
||||
|
||||
// Show Toast warning if parallax is enabled but device has offset issues
|
||||
if (effects.enableParallax && !hasShownParallaxWarning && GLCompatibility.shouldWarnAboutParallax()) {
|
||||
hasShownParallaxWarning = true
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
Toast.makeText(
|
||||
applicationContext,
|
||||
R.string.parallax_may_not_work,
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
}
|
||||
|
||||
// Reload if album changed
|
||||
if (albumId != currentAlbumId) {
|
||||
Log.d(TAG, "Album changed from $currentAlbumId to $albumId, reloading")
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.gl
|
||||
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* Utility class for handling GL compatibility across different OEMs and GPU vendors.
|
||||
*
|
||||
* Provides OEM-specific workarounds for:
|
||||
* - Texture size limits (some OEMs misreport GL_MAX_TEXTURE_SIZE)
|
||||
* - EGL configuration fallbacks (different GPUs need different configs)
|
||||
* - Parallax support detection (some launchers don't report offsets)
|
||||
*/
|
||||
object GLCompatibility {
|
||||
|
||||
private const val TAG = "GLCompatibility"
|
||||
|
||||
// Known problematic manufacturers for various GL issues
|
||||
private val LOW_END_GPU_MANUFACTURERS = setOf(
|
||||
"MEDIATEK", // Mali-T/G series often have texture issues
|
||||
"ALLWINNER", // Low-end tablets
|
||||
"ROCKCHIP", // Budget tablets
|
||||
"SPREADTRUM" // Budget phones
|
||||
)
|
||||
|
||||
// Manufacturers with known parallax/offset issues
|
||||
private val PARALLAX_ISSUE_MANUFACTURERS = setOf(
|
||||
"SAMSUNG", // One UI often doesn't report offsets properly
|
||||
"XIAOMI", // MIUI Launcher has inconsistent offset reporting
|
||||
"HUAWEI", // EMUI has similar issues
|
||||
"OPPO", // ColorOS launcher issues
|
||||
"VIVO", // OriginOS/FuntouchOS issues
|
||||
"REALME", // RealmeUI uses OPPO's base
|
||||
"ONEPLUS" // OxygenOS (older versions)
|
||||
)
|
||||
|
||||
// Texture size limits by device tier
|
||||
private const val TEXTURE_SIZE_LOW_END = 2048
|
||||
private const val TEXTURE_SIZE_MID_RANGE = 4096
|
||||
|
||||
/**
|
||||
* Get the device manufacturer in uppercase for comparison.
|
||||
*/
|
||||
fun getManufacturer(): String = Build.MANUFACTURER.uppercase()
|
||||
|
||||
|
||||
/**
|
||||
* Check if the device likely has a low-end GPU that may have texture issues.
|
||||
*/
|
||||
fun isLowEndGPU(): Boolean {
|
||||
val manufacturer = getManufacturer()
|
||||
val isLowEnd = LOW_END_GPU_MANUFACTURERS.any { manufacturer.contains(it) }
|
||||
|
||||
// Also check for low RAM as a heuristic for low-end devices
|
||||
// Note: This is a simple heuristic; actual RAM check would require context
|
||||
|
||||
return isLowEnd
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a safe maximum texture size based on device capabilities.
|
||||
* This is more conservative than the GL-reported value to avoid OOM on problematic devices.
|
||||
*
|
||||
* @param glReportedMax The maximum texture size reported by GL_MAX_TEXTURE_SIZE
|
||||
* @return A safe texture size to use
|
||||
*/
|
||||
fun getSafeMaxTextureSize(glReportedMax: Int = 0): Int {
|
||||
val manufacturer = getManufacturer()
|
||||
|
||||
// Use conservative limits for known problematic manufacturers
|
||||
val safeLimit = when {
|
||||
isLowEndGPU() -> {
|
||||
Log.d(TAG, "Low-end GPU detected ($manufacturer), using conservative texture size")
|
||||
TEXTURE_SIZE_LOW_END
|
||||
}
|
||||
else -> TEXTURE_SIZE_MID_RANGE
|
||||
}
|
||||
|
||||
// If we have a GL-reported max, cap at that value
|
||||
return if (glReportedMax > 0) {
|
||||
min(safeLimit, glReportedMax)
|
||||
} else {
|
||||
safeLimit
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the device's default launcher likely supports reliable offset notifications
|
||||
* for parallax scrolling.
|
||||
*
|
||||
* Many OEM launchers don't properly call onOffsetsChanged(), making parallax
|
||||
* scrolling impossible or erratic.
|
||||
*
|
||||
* @return true if offsets are likely to work reliably
|
||||
*/
|
||||
fun supportsReliableOffsets(): Boolean {
|
||||
val manufacturer = getManufacturer()
|
||||
val hasIssues = PARALLAX_ISSUE_MANUFACTURERS.any { manufacturer.contains(it) }
|
||||
|
||||
if (hasIssues) {
|
||||
Log.d(TAG, "Manufacturer $manufacturer may have parallax/offset issues with stock launcher")
|
||||
}
|
||||
|
||||
// Return true anyway - we don't disable parallax outright, but we detect it
|
||||
// The caller can use this to show a toast or fallback gracefully
|
||||
return !hasIssues
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should warn the user about potential parallax issues.
|
||||
* Only returns true if parallax would likely not work on this device.
|
||||
*/
|
||||
fun shouldWarnAboutParallax(): Boolean {
|
||||
return !supportsReliableOffsets()
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Log device information for debugging.
|
||||
*/
|
||||
fun logDeviceInfo() {
|
||||
Log.i(TAG, "Device: ${Build.MANUFACTURER} ${Build.MODEL}")
|
||||
Log.i(TAG, "Android: ${Build.VERSION.SDK_INT} (${Build.VERSION.RELEASE})")
|
||||
Log.i(TAG, "Board: ${Build.BOARD}, Hardware: ${Build.HARDWARE}")
|
||||
Log.i(TAG, "Low-end GPU: ${isLowEndGPU()}")
|
||||
Log.i(TAG, "Supports reliable offsets: ${supportsReliableOffsets()}")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.gl
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.opengl.GLES20
|
||||
@@ -56,7 +55,7 @@ class GLPicture(
|
||||
"Cannot create GLPicture from bitmap with invalid dimensions: ${bitmap.width}x${bitmap.height}"
|
||||
}
|
||||
|
||||
val maxTextureSize = min(getOptimalTileSize(), Constants.GL_TEXTURE_SIZE_LIMIT)
|
||||
val maxTextureSize = GLCompatibility.getSafeMaxTextureSize(getOptimalTileSize())
|
||||
val tileSize = maxTextureSize
|
||||
|
||||
cols = ceil(width.toFloat() / tileSize).toInt()
|
||||
|
||||
+59
-34
@@ -54,12 +54,6 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
this.eglContextClientVersion = version
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the EGL config chooser.
|
||||
*/
|
||||
fun setEGLConfigChooser(configChooser: EGLConfigChooser) {
|
||||
this.eglConfigChooser = configChooser
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplified EGL config chooser for RGB888 with no depth/stencil.
|
||||
@@ -156,6 +150,7 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
@Volatile var renderMode = RENDERMODE_WHEN_DIRTY
|
||||
|
||||
private val eventQueue = mutableListOf<Runnable>()
|
||||
@Suppress("UseKotlinAny")
|
||||
private val lock = Object()
|
||||
|
||||
@Volatile private var shouldExit = false
|
||||
@@ -372,7 +367,9 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple EGL config chooser that picks the first config matching the requirements.
|
||||
* Enhanced EGL config chooser with multiple fallback options.
|
||||
* Tries progressively simpler configurations to maximize compatibility
|
||||
* across different GPU vendors (Adreno, Mali, PowerVR, etc.)
|
||||
*/
|
||||
private class SimpleEGLConfigChooser(
|
||||
private val redSize: Int,
|
||||
@@ -391,8 +388,14 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
0x0004 // EGL_OPENGL_ES2_BIT
|
||||
}
|
||||
|
||||
// Try with EGL_RENDERABLE_TYPE
|
||||
var configSpec = intArrayOf(
|
||||
// Log device info for debugging
|
||||
GLCompatibility.logDeviceInfo()
|
||||
|
||||
// Build list of configs to try in order of preference
|
||||
val configSpecs = mutableListOf<IntArray>()
|
||||
|
||||
// Config 1: Full spec with EGL_RENDERABLE_TYPE (most common/preferred)
|
||||
configSpecs.add(intArrayOf(
|
||||
EGL10.EGL_RED_SIZE, redSize,
|
||||
EGL10.EGL_GREEN_SIZE, greenSize,
|
||||
EGL10.EGL_BLUE_SIZE, blueSize,
|
||||
@@ -401,36 +404,58 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
EGL10.EGL_STENCIL_SIZE, stencilSize,
|
||||
0x3142, renderableType, // EGL_RENDERABLE_TYPE
|
||||
EGL10.EGL_NONE
|
||||
)
|
||||
))
|
||||
|
||||
// Config 2: Without EGL_RENDERABLE_TYPE (older devices)
|
||||
configSpecs.add(intArrayOf(
|
||||
EGL10.EGL_RED_SIZE, redSize,
|
||||
EGL10.EGL_GREEN_SIZE, greenSize,
|
||||
EGL10.EGL_BLUE_SIZE, blueSize,
|
||||
EGL10.EGL_ALPHA_SIZE, alphaSize,
|
||||
EGL10.EGL_DEPTH_SIZE, depthSize,
|
||||
EGL10.EGL_STENCIL_SIZE, stencilSize,
|
||||
EGL10.EGL_NONE
|
||||
))
|
||||
|
||||
// Config 3: RGB565 (no alpha) - Mali GPU fallback
|
||||
if (GLCompatibility.isLowEndGPU()) {
|
||||
configSpecs.add(intArrayOf(
|
||||
EGL10.EGL_RED_SIZE, 5,
|
||||
EGL10.EGL_GREEN_SIZE, 6,
|
||||
EGL10.EGL_BLUE_SIZE, 5,
|
||||
EGL10.EGL_ALPHA_SIZE, 0,
|
||||
EGL10.EGL_DEPTH_SIZE, 0,
|
||||
EGL10.EGL_STENCIL_SIZE, 0,
|
||||
EGL10.EGL_NONE
|
||||
))
|
||||
Log.d(TAG, "Added RGB565 fallback config for low-end GPU")
|
||||
}
|
||||
|
||||
// Config 4: Minimal config (last resort)
|
||||
configSpecs.add(intArrayOf(
|
||||
EGL10.EGL_SURFACE_TYPE, EGL10.EGL_WINDOW_BIT,
|
||||
EGL10.EGL_NONE
|
||||
))
|
||||
|
||||
val numConfig = IntArray(1)
|
||||
if (!egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) {
|
||||
Log.w(TAG, "eglChooseConfig failed with EGL_RENDERABLE_TYPE, retrying without it")
|
||||
// Fallback: Try without EGL_RENDERABLE_TYPE
|
||||
configSpec = intArrayOf(
|
||||
EGL10.EGL_RED_SIZE, redSize,
|
||||
EGL10.EGL_GREEN_SIZE, greenSize,
|
||||
EGL10.EGL_BLUE_SIZE, blueSize,
|
||||
EGL10.EGL_ALPHA_SIZE, alphaSize,
|
||||
EGL10.EGL_DEPTH_SIZE, depthSize,
|
||||
EGL10.EGL_STENCIL_SIZE, stencilSize,
|
||||
EGL10.EGL_NONE
|
||||
)
|
||||
if (!egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) {
|
||||
throw RuntimeException("eglChooseConfig failed")
|
||||
|
||||
for ((index, configSpec) in configSpecs.withIndex()) {
|
||||
if (egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) {
|
||||
if (numConfig[0] > 0) {
|
||||
val configs = arrayOfNulls<EGLConfig>(numConfig[0])
|
||||
if (egl.eglChooseConfig(display, configSpec, configs, numConfig[0], numConfig)) {
|
||||
val config = configs[0]
|
||||
if (config != null) {
|
||||
Log.d(TAG, "EGL config chosen using fallback level $index")
|
||||
return config
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Log.w(TAG, "EGL config fallback $index failed, trying next...")
|
||||
}
|
||||
|
||||
if (numConfig[0] <= 0) {
|
||||
throw RuntimeException("No EGL configs match")
|
||||
}
|
||||
|
||||
val configs = arrayOfNulls<EGLConfig>(numConfig[0])
|
||||
if (!egl.eglChooseConfig(display, configSpec, configs, numConfig[0], numConfig)) {
|
||||
throw RuntimeException("eglChooseConfig failed")
|
||||
}
|
||||
|
||||
return configs[0] ?: throw RuntimeException("No config chosen")
|
||||
throw RuntimeException("No compatible EGL config found after all fallbacks")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -197,19 +197,6 @@ class WallpaperScheduler @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update existing wallpaper change schedule
|
||||
* Uses UPDATE policy to modify the existing work
|
||||
*/
|
||||
fun updateWallpaperChange(
|
||||
screenType: ScreenType,
|
||||
intervalMinutes: Int,
|
||||
networkRequired: Boolean = false,
|
||||
requireCharging: Boolean = false
|
||||
) {
|
||||
scheduleWallpaperChange(screenType, intervalMinutes, networkRequired, requireCharging)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel wallpaper change schedule for specific screen
|
||||
*/
|
||||
@@ -230,13 +217,6 @@ class WallpaperScheduler @Inject constructor(
|
||||
cancelAlbumRefresh()
|
||||
Log.d(TAG, "Cancelled all wallpaper change schedules")
|
||||
}
|
||||
|
||||
// ... scheduleAlbumRefresh and cancelAlbumRefresh omitted as they were not targeted for change ...
|
||||
// Wait, I should not delete them. I'll use the proper range.
|
||||
|
||||
// I will target up to cancelAllWallpaperChanges for this call.
|
||||
// The next tool call will fix triggerImmediateChange.
|
||||
|
||||
|
||||
/**
|
||||
* Schedule daily album refresh worker
|
||||
@@ -291,32 +271,6 @@ class WallpaperScheduler @Inject constructor(
|
||||
Log.d(TAG, "Cancelled daily album refresh")
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger immediate wallpaper change (one-time work)
|
||||
* Does not affect the periodic schedule
|
||||
*
|
||||
* @param screenType HOME, LOCK, or BOTH (for synchronized immediate change)
|
||||
*/
|
||||
fun triggerImmediateChange(screenType: ScreenType) {
|
||||
val inputData = Data.Builder()
|
||||
.putString(Constants.EXTRA_SCREEN_TYPE, screenType.name)
|
||||
.build()
|
||||
|
||||
val workRequest = androidx.work.OneTimeWorkRequestBuilder<WallpaperChangeWorker>()
|
||||
.setInputData(inputData)
|
||||
.addTag("${Constants.WORK_TAG_IMMEDIATE}_${screenType.name.lowercase()}")
|
||||
.build()
|
||||
|
||||
val uniqueWorkName = "${Constants.WORK_TAG_IMMEDIATE}_${screenType.name.lowercase()}"
|
||||
|
||||
workManager.enqueueUniqueWork(
|
||||
uniqueWorkName,
|
||||
androidx.work.ExistingWorkPolicy.REPLACE,
|
||||
workRequest
|
||||
)
|
||||
Log.d(TAG, "Triggered immediate $screenType wallpaper change")
|
||||
}
|
||||
|
||||
private fun getWorkName(screenType: ScreenType): String {
|
||||
return when (screenType) {
|
||||
ScreenType.HOME -> Constants.WORK_NAME_HOME
|
||||
|
||||
@@ -184,6 +184,9 @@
|
||||
<string name="error_no_valid_wallpaper_after_retries">Could not find a valid wallpaper after retries</string>
|
||||
<string name="error_failed_to_load_bitmap">Failed to load wallpaper image</string>
|
||||
|
||||
<!-- OEM Compatibility Warnings -->
|
||||
<string name="parallax_may_not_work">Parallax effect may not work with your OEM or launcher.</string>
|
||||
|
||||
<!-- Plurals -->
|
||||
<plurals name="items_count">
|
||||
<item quantity="one">%d item</item>
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for Result sealed class
|
||||
*/
|
||||
class ResultTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: Success
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `Success isSuccess returns true`() {
|
||||
val result: Result<String> = Result.Success("data")
|
||||
assertTrue(result.isSuccess)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Success isError returns false`() {
|
||||
val result: Result<String> = Result.Success("data")
|
||||
assertFalse(result.isError)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Success isLoading returns false`() {
|
||||
val result: Result<String> = Result.Success("data")
|
||||
assertFalse(result.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Success getOrNull returns data`() {
|
||||
val result: Result<String> = Result.Success("test data")
|
||||
assertEquals("test data", result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Success exceptionOrNull returns null`() {
|
||||
val result: Result<String> = Result.Success("data")
|
||||
assertNull(result.exceptionOrNull())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Error
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `Error isError returns true`() {
|
||||
val result: Result<String> = Result.Error(Exception("error"))
|
||||
assertTrue(result.isError)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Error isSuccess returns false`() {
|
||||
val result: Result<String> = Result.Error(Exception("error"))
|
||||
assertFalse(result.isSuccess)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Error isLoading returns false`() {
|
||||
val result: Result<String> = Result.Error(Exception("error"))
|
||||
assertFalse(result.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Error getOrNull returns null`() {
|
||||
val result: Result<String> = Result.Error(Exception("error"))
|
||||
assertNull(result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Error exceptionOrNull returns exception`() {
|
||||
val exception = Exception("test error")
|
||||
val result: Result<String> = Result.Error(exception)
|
||||
assertEquals(exception, result.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Error message defaults to exception message`() {
|
||||
val result = Result.Error(Exception("my error message"))
|
||||
assertEquals("my error message", result.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Error can have custom message`() {
|
||||
val result = Result.Error(Exception("original"), message = "custom message")
|
||||
assertEquals("custom message", result.message)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Loading
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `Loading isLoading returns true`() {
|
||||
val result: Result<String> = Result.Loading
|
||||
assertTrue(result.isLoading)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Loading isSuccess returns false`() {
|
||||
val result: Result<String> = Result.Loading
|
||||
assertFalse(result.isSuccess)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Loading isError returns false`() {
|
||||
val result: Result<String> = Result.Loading
|
||||
assertFalse(result.isError)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Loading getOrNull returns null`() {
|
||||
val result: Result<String> = Result.Loading
|
||||
assertNull(result.getOrNull())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: onSuccess callback
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `onSuccess executes callback for Success`() {
|
||||
var callbackExecuted = false
|
||||
var receivedData: String? = null
|
||||
|
||||
Result.Success("my data").onSuccess {
|
||||
callbackExecuted = true
|
||||
receivedData = it
|
||||
}
|
||||
|
||||
assertTrue(callbackExecuted)
|
||||
assertEquals("my data", receivedData)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `onSuccess does not execute callback for Error`() {
|
||||
var callbackExecuted = false
|
||||
|
||||
Result.Error(Exception("error")).onSuccess {
|
||||
callbackExecuted = true
|
||||
}
|
||||
|
||||
assertFalse(callbackExecuted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `onSuccess returns same result for chaining`() {
|
||||
val result = Result.Success("data")
|
||||
val returned = result.onSuccess { }
|
||||
assertSame(result, returned)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: onError callback
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `onError executes callback for Error`() {
|
||||
var callbackExecuted = false
|
||||
val exception = Exception("test error")
|
||||
|
||||
Result.Error(exception).onError {
|
||||
callbackExecuted = true
|
||||
assertEquals(exception, it)
|
||||
}
|
||||
|
||||
assertTrue(callbackExecuted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `onError does not execute callback for Success`() {
|
||||
var callbackExecuted = false
|
||||
|
||||
Result.Success("data").onError {
|
||||
callbackExecuted = true
|
||||
}
|
||||
|
||||
assertFalse(callbackExecuted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `onError returns same result for chaining`() {
|
||||
val result: Result<String> = Result.Error(Exception("error"))
|
||||
val returned = result.onError { }
|
||||
assertSame(result, returned)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: map extension
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `map transforms Success data`() {
|
||||
val result = Result.Success(5)
|
||||
val mapped = result.map { it * 2 }
|
||||
|
||||
assertTrue(mapped.isSuccess)
|
||||
assertEquals(10, mapped.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `map preserves Error`() {
|
||||
val exception = Exception("error")
|
||||
val result: Result<Int> = Result.Error(exception, "custom message")
|
||||
val mapped = result.map { it * 2 }
|
||||
|
||||
assertTrue(mapped.isError)
|
||||
assertEquals(exception, mapped.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `map preserves Loading`() {
|
||||
val result: Result<Int> = Result.Loading
|
||||
val mapped = result.map { it * 2 }
|
||||
|
||||
assertTrue(mapped.isLoading)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: flatMap extension
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `flatMap transforms Success to Success`() {
|
||||
val result = Result.Success(5)
|
||||
val flatMapped = result.flatMap { Result.Success(it.toString()) }
|
||||
|
||||
assertTrue(flatMapped.isSuccess)
|
||||
assertEquals("5", flatMapped.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flatMap transforms Success to Error`() {
|
||||
val result = Result.Success(5)
|
||||
val flatMapped = result.flatMap { Result.Error(Exception("failed")) }
|
||||
|
||||
assertTrue(flatMapped.isError)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flatMap preserves Error`() {
|
||||
val exception = Exception("original error")
|
||||
val result: Result<Int> = Result.Error(exception)
|
||||
val flatMapped = result.flatMap { Result.Success(it.toString()) }
|
||||
|
||||
assertTrue(flatMapped.isError)
|
||||
assertEquals(exception, flatMapped.exceptionOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `flatMap preserves Loading`() {
|
||||
val result: Result<Int> = Result.Loading
|
||||
val flatMapped = result.flatMap { Result.Success(it.toString()) }
|
||||
|
||||
assertTrue(flatMapped.isLoading)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: runCatching companion
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `runCatching returns Success when block succeeds`() {
|
||||
val result = Result.runCatching { 42 }
|
||||
|
||||
assertTrue(result.isSuccess)
|
||||
assertEquals(42, result.getOrNull())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `runCatching returns Error when block throws`() {
|
||||
val result = Result.runCatching { throw IllegalStateException("boom") }
|
||||
|
||||
assertTrue(result.isError)
|
||||
assertTrue(result.exceptionOrNull() is IllegalStateException)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for ScalingType enum
|
||||
*/
|
||||
class ScalingTypeTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: fromString
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromString with FILL returns FILL`() {
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("FILL"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with FIT returns FIT`() {
|
||||
assertEquals(ScalingType.FIT, ScalingType.fromString("FIT"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with STRETCH returns STRETCH`() {
|
||||
assertEquals(ScalingType.STRETCH, ScalingType.fromString("STRETCH"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with NONE returns NONE`() {
|
||||
assertEquals(ScalingType.NONE, ScalingType.fromString("NONE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive`() {
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("fill"))
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("Fill"))
|
||||
assertEquals(ScalingType.FIT, ScalingType.fromString("fit"))
|
||||
assertEquals(ScalingType.FIT, ScalingType.fromString("Fit"))
|
||||
assertEquals(ScalingType.STRETCH, ScalingType.fromString("stretch"))
|
||||
assertEquals(ScalingType.NONE, ScalingType.fromString("none"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with null returns FILL as default`() {
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with empty string returns FILL as default`() {
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with invalid value returns FILL as default`() {
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("invalid"))
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("crop"))
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("center"))
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString("123"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with whitespace returns FILL as default`() {
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString(" "))
|
||||
assertEquals(ScalingType.FILL, ScalingType.fromString(" FILL "))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Enum values
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `enum has exactly four values`() {
|
||||
assertEquals(4, ScalingType.entries.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enum values are FILL, FIT, STRETCH, NONE`() {
|
||||
assertTrue(ScalingType.entries.contains(ScalingType.FILL))
|
||||
assertTrue(ScalingType.entries.contains(ScalingType.FIT))
|
||||
assertTrue(ScalingType.entries.contains(ScalingType.STRETCH))
|
||||
assertTrue(ScalingType.entries.contains(ScalingType.NONE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enum names are correct`() {
|
||||
assertEquals("FILL", ScalingType.FILL.name)
|
||||
assertEquals("FIT", ScalingType.FIT.name)
|
||||
assertEquals("STRETCH", ScalingType.STRETCH.name)
|
||||
assertEquals("NONE", ScalingType.NONE.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for ScreenType enum
|
||||
*/
|
||||
class ScreenTypeTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: fromString
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromString with HOME returns HOME`() {
|
||||
assertEquals(ScreenType.HOME, ScreenType.fromString("HOME"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with LOCK returns LOCK`() {
|
||||
assertEquals(ScreenType.LOCK, ScreenType.fromString("LOCK"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with BOTH returns BOTH`() {
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString("BOTH"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with LIVE returns LIVE`() {
|
||||
assertEquals(ScreenType.LIVE, ScreenType.fromString("LIVE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive for home`() {
|
||||
assertEquals(ScreenType.HOME, ScreenType.fromString("home"))
|
||||
assertEquals(ScreenType.HOME, ScreenType.fromString("Home"))
|
||||
assertEquals(ScreenType.HOME, ScreenType.fromString("HOME"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive for lock`() {
|
||||
assertEquals(ScreenType.LOCK, ScreenType.fromString("lock"))
|
||||
assertEquals(ScreenType.LOCK, ScreenType.fromString("Lock"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive for both`() {
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString("both"))
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString("Both"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive for live`() {
|
||||
assertEquals(ScreenType.LIVE, ScreenType.fromString("live"))
|
||||
assertEquals(ScreenType.LIVE, ScreenType.fromString("Live"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with null returns BOTH as default`() {
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with empty string returns BOTH as default`() {
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with invalid value returns BOTH as default`() {
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString("invalid"))
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString("screen"))
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString("123"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with whitespace returns BOTH as default`() {
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString(" "))
|
||||
assertEquals(ScreenType.BOTH, ScreenType.fromString(" HOME "))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Enum values
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `enum has exactly four values`() {
|
||||
assertEquals(4, ScreenType.entries.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enum values are HOME, LOCK, BOTH, LIVE`() {
|
||||
assertTrue(ScreenType.entries.contains(ScreenType.HOME))
|
||||
assertTrue(ScreenType.entries.contains(ScreenType.LOCK))
|
||||
assertTrue(ScreenType.entries.contains(ScreenType.BOTH))
|
||||
assertTrue(ScreenType.entries.contains(ScreenType.LIVE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enum names are correct`() {
|
||||
assertEquals("HOME", ScreenType.HOME.name)
|
||||
assertEquals("LOCK", ScreenType.LOCK.name)
|
||||
assertEquals("BOTH", ScreenType.BOTH.name)
|
||||
assertEquals("LIVE", ScreenType.LIVE.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for WallpaperMediaType enum
|
||||
*/
|
||||
class WallpaperMediaTypeTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - JPEG formats
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension with jpg returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("jpg"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with jpeg returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("jpeg"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - Modern formats
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension with png returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("png"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with webp returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("webp"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with avif returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("avif"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - Apple formats
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension with heic returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("heic"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with heif returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("heif"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - Legacy formats
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension with bmp returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("bmp"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with gif returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("gif"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with tiff returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("tiff"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with tif returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("tif"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - Vector format
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension with svg returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("svg"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - Case insensitivity
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension is case insensitive for uppercase`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("JPG"))
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("PNG"))
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("WEBP"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension is case insensitive for mixed case`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("Jpg"))
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("PnG"))
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("WebP"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromExtension - Unsupported/Invalid extensions
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromExtension with unsupported extension returns null`() {
|
||||
assertNull(WallpaperMediaType.fromExtension("mp4"))
|
||||
assertNull(WallpaperMediaType.fromExtension("mp3"))
|
||||
assertNull(WallpaperMediaType.fromExtension("pdf"))
|
||||
assertNull(WallpaperMediaType.fromExtension("txt"))
|
||||
assertNull(WallpaperMediaType.fromExtension("doc"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with empty string returns null`() {
|
||||
assertNull(WallpaperMediaType.fromExtension(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromExtension with whitespace returns null`() {
|
||||
assertNull(WallpaperMediaType.fromExtension(" "))
|
||||
assertNull(WallpaperMediaType.fromExtension(" "))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromString - Valid values
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromString with IMAGE returns IMAGE`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("IMAGE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive`() {
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("image"))
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("Image"))
|
||||
assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("iMaGe"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: fromString - Invalid/null values
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromString with null returns null`() {
|
||||
assertNull(WallpaperMediaType.fromString(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with empty string returns null`() {
|
||||
assertNull(WallpaperMediaType.fromString(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with invalid value returns null`() {
|
||||
assertNull(WallpaperMediaType.fromString("invalid"))
|
||||
assertNull(WallpaperMediaType.fromString("video"))
|
||||
assertNull(WallpaperMediaType.fromString("IMAGES"))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: supportedExtensions property
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `IMAGE supportedExtensions contains all expected formats`() {
|
||||
val extensions = WallpaperMediaType.IMAGE.supportedExtensions
|
||||
|
||||
// JPEG formats
|
||||
assertTrue(extensions.contains("jpg"))
|
||||
assertTrue(extensions.contains("jpeg"))
|
||||
|
||||
// Modern formats
|
||||
assertTrue(extensions.contains("png"))
|
||||
assertTrue(extensions.contains("webp"))
|
||||
assertTrue(extensions.contains("avif"))
|
||||
|
||||
// Apple formats
|
||||
assertTrue(extensions.contains("heic"))
|
||||
assertTrue(extensions.contains("heif"))
|
||||
|
||||
// Legacy formats
|
||||
assertTrue(extensions.contains("bmp"))
|
||||
assertTrue(extensions.contains("gif"))
|
||||
assertTrue(extensions.contains("tiff"))
|
||||
assertTrue(extensions.contains("tif"))
|
||||
|
||||
// Vector
|
||||
assertTrue(extensions.contains("svg"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `IMAGE supportedExtensions has expected count`() {
|
||||
// jpg, jpeg, png, webp, avif, heic, heif, bmp, gif, tiff, tif, svg = 12
|
||||
assertEquals(12, WallpaperMediaType.IMAGE.supportedExtensions.size)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: supportedInStaticMode property
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `IMAGE is supported in static mode`() {
|
||||
assertTrue(WallpaperMediaType.IMAGE.supportedInStaticMode)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: supportedInLiveMode property
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `IMAGE is supported in live mode`() {
|
||||
assertTrue(WallpaperMediaType.IMAGE.supportedInLiveMode)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Enum values
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `enum has exactly one value`() {
|
||||
assertEquals(1, WallpaperMediaType.entries.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enum value name is IMAGE`() {
|
||||
assertEquals("IMAGE", WallpaperMediaType.IMAGE.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for WallpaperMode enum
|
||||
*/
|
||||
class WallpaperModeTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: fromString
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `fromString with STATIC returns STATIC`() {
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("STATIC"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with LIVE returns LIVE`() {
|
||||
assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("LIVE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive for static`() {
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("static"))
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("Static"))
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("STATIC"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString is case insensitive for live`() {
|
||||
assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("live"))
|
||||
assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("Live"))
|
||||
assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("LIVE"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with null returns STATIC as default`() {
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with empty string returns STATIC as default`() {
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with invalid value returns STATIC as default`() {
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("invalid"))
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("dynamic"))
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("123"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fromString with whitespace returns STATIC as default`() {
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(" "))
|
||||
assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(" STATIC "))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Enum values
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `enum has exactly two values`() {
|
||||
assertEquals(2, WallpaperMode.entries.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `enum values are STATIC and LIVE`() {
|
||||
assertTrue(WallpaperMode.entries.contains(WallpaperMode.STATIC))
|
||||
assertTrue(WallpaperMode.entries.contains(WallpaperMode.LIVE))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `STATIC name is correct`() {
|
||||
assertEquals("STATIC", WallpaperMode.STATIC.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `LIVE name is correct`() {
|
||||
assertEquals("LIVE", WallpaperMode.LIVE.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class BrightnessCalculatorTest {
|
||||
|
||||
@Test
|
||||
fun `calculateLuminance returns correct value for white`() {
|
||||
// White = 0xFFFFFFFF
|
||||
val white = 0xFFFFFFFF.toInt()
|
||||
val luminance = BrightnessCalculator.calculateLuminance(white)
|
||||
// 0.2126 * 1 + 0.7152 * 1 + 0.0722 * 1 = 1.0
|
||||
assertEquals(1.0, luminance, 0.001)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `calculateLuminance returns correct value for black`() {
|
||||
// Black = 0xFF000000
|
||||
val black = 0xFF000000.toInt()
|
||||
val luminance = BrightnessCalculator.calculateLuminance(black)
|
||||
assertEquals(0.0, luminance, 0.001)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `calculateLuminance returns correct value for red`() {
|
||||
// Red = 0xFFFF0000
|
||||
val red = 0xFFFF0000.toInt()
|
||||
val luminance = BrightnessCalculator.calculateLuminance(red)
|
||||
assertEquals(Constants.LUMINANCE_RED, luminance, 0.001)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getAdaptiveMultiplier in dark mode darkens bright image`() {
|
||||
// If brightness > LIGHT_BRIGHTNESS_MIN (0.8), should return TARGET_BRIGHTNESS_DARK / brightness
|
||||
val brightness = 0.9f
|
||||
val multiplier = BrightnessCalculator.getAdaptiveMultiplier(true, brightness)
|
||||
val expected = Constants.TARGET_BRIGHTNESS_DARK / brightness
|
||||
assertEquals(expected, multiplier, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getAdaptiveMultiplier in dark mode does not change dark image`() {
|
||||
// If brightness <= LIGHT_BRIGHTNESS_MIN (0.8), should return 1.0
|
||||
val brightness = 0.5f
|
||||
val multiplier = BrightnessCalculator.getAdaptiveMultiplier(true, brightness)
|
||||
assertEquals(1.0f, multiplier, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getAdaptiveMultiplier in light mode brightens dark image`() {
|
||||
// If brightness < DARK_BRIGHTNESS_MAX (0.3), should return TARGET_BRIGHTNESS_LIGHT / brightness
|
||||
val brightness = 0.2f
|
||||
val multiplier = BrightnessCalculator.getAdaptiveMultiplier(false, brightness)
|
||||
val expected = Constants.TARGET_BRIGHTNESS_LIGHT / brightness
|
||||
assertEquals(expected, multiplier, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getAdaptiveMultiplier in light mode does not change bright image`() {
|
||||
// If brightness >= DARK_BRIGHTNESS_MAX (0.3), should return 1.0
|
||||
val brightness = 0.5f
|
||||
val multiplier = BrightnessCalculator.getAdaptiveMultiplier(false, brightness)
|
||||
assertEquals(1.0f, multiplier, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getAdaptiveMultiplier returns 1_0 for very dark items to avoid noise`() {
|
||||
val brightness = 0.005f
|
||||
val multiplier = BrightnessCalculator.getAdaptiveMultiplier(true, brightness)
|
||||
assertEquals(1.0f, multiplier, 0.001f)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for QueueBuilder utility
|
||||
*/
|
||||
class QueueBuilderTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: buildSequentialQueue
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `buildSequentialQueue sorts by display order`() {
|
||||
val wallpapers = listOf(
|
||||
"w3" to 2,
|
||||
"w1" to 0,
|
||||
"w2" to 1
|
||||
)
|
||||
|
||||
val queue = QueueBuilder.buildSequentialQueue(wallpapers)
|
||||
|
||||
assertEquals(listOf("w1", "w2", "w3"), queue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildSequentialQueue handles empty list`() {
|
||||
val queue = QueueBuilder.buildSequentialQueue(emptyList())
|
||||
assertTrue(queue.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildSequentialQueue handles single item`() {
|
||||
val queue = QueueBuilder.buildSequentialQueue(listOf("w1" to 5))
|
||||
assertEquals(listOf("w1"), queue)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildSequentialQueue handles non-contiguous display orders`() {
|
||||
val wallpapers = listOf(
|
||||
"w3" to 100,
|
||||
"w1" to 5,
|
||||
"w2" to 50
|
||||
)
|
||||
|
||||
val queue = QueueBuilder.buildSequentialQueue(wallpapers)
|
||||
|
||||
assertEquals(listOf("w1", "w2", "w3"), queue)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: buildShuffledQueue
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `buildShuffledQueue contains all original IDs`() {
|
||||
val ids = listOf("w1", "w2", "w3", "w4", "w5")
|
||||
|
||||
val shuffled = QueueBuilder.buildShuffledQueue(ids)
|
||||
|
||||
assertEquals(ids.size, shuffled.size)
|
||||
assertTrue(shuffled.containsAll(ids))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildShuffledQueue handles empty list`() {
|
||||
val shuffled = QueueBuilder.buildShuffledQueue(emptyList())
|
||||
assertTrue(shuffled.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildShuffledQueue handles single item`() {
|
||||
val shuffled = QueueBuilder.buildShuffledQueue(listOf("w1"))
|
||||
assertEquals(listOf("w1"), shuffled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildShuffledQueue produces different order over multiple calls`() {
|
||||
val ids = (1..100).map { "w$it" }
|
||||
|
||||
// Run multiple times and check if we ever get a different order
|
||||
// With 100 items, the chance of same order is astronomically low
|
||||
val results = (1..10).map { QueueBuilder.buildShuffledQueue(ids) }
|
||||
val allSame = results.all { it == results.first() }
|
||||
|
||||
assertFalse("Shuffle should produce different orders", allSame)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: needsNormalization
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns false for empty list`() {
|
||||
assertFalse(QueueBuilder.needsNormalization(emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns false for sequential positions`() {
|
||||
assertFalse(QueueBuilder.needsNormalization(listOf(0, 1, 2, 3)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns true for positions with gaps`() {
|
||||
assertTrue(QueueBuilder.needsNormalization(listOf(0, 2, 4)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns true for positions not starting at 0`() {
|
||||
assertTrue(QueueBuilder.needsNormalization(listOf(1, 2, 3)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns false for out of order but contiguous positions`() {
|
||||
// [2, 0, 1] when sorted becomes [0, 1, 2] - no gaps, so no normalization needed
|
||||
assertFalse(QueueBuilder.needsNormalization(listOf(2, 0, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns false for single item at 0`() {
|
||||
assertFalse(QueueBuilder.needsNormalization(listOf(0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `needsNormalization returns true for single item not at 0`() {
|
||||
assertTrue(QueueBuilder.needsNormalization(listOf(5)))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: normalizePositions
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `normalizePositions creates sequential indices`() {
|
||||
val normalized = QueueBuilder.normalizePositions(listOf(0, 2, 5))
|
||||
assertEquals(listOf(0, 1, 2), normalized)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `normalizePositions handles empty list`() {
|
||||
val normalized = QueueBuilder.normalizePositions(emptyList())
|
||||
assertTrue(normalized.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `normalizePositions handles already normalized`() {
|
||||
val normalized = QueueBuilder.normalizePositions(listOf(0, 1, 2))
|
||||
assertEquals(listOf(0, 1, 2), normalized)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: mergeWithExistingQueueDeterministic
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `mergeWithExistingQueue preserves existing order`() {
|
||||
val existing = listOf("w3", "w1", "w2")
|
||||
val all = listOf("w1", "w2", "w3")
|
||||
|
||||
val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all)
|
||||
|
||||
assertEquals(listOf("w3", "w1", "w2"), merged)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mergeWithExistingQueue filters removed wallpapers`() {
|
||||
val existing = listOf("w1", "w2", "w3")
|
||||
val all = listOf("w1", "w3") // w2 was removed
|
||||
|
||||
val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all)
|
||||
|
||||
assertEquals(listOf("w1", "w3"), merged)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mergeWithExistingQueue appends new wallpapers`() {
|
||||
val existing = listOf("w1", "w2")
|
||||
val all = listOf("w1", "w2", "w3", "w4") // w3, w4 are new
|
||||
|
||||
val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all)
|
||||
|
||||
assertEquals(listOf("w1", "w2", "w3", "w4"), merged)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mergeWithExistingQueue handles empty existing queue`() {
|
||||
val existing = emptyList<String>()
|
||||
val all = listOf("w1", "w2", "w3")
|
||||
|
||||
val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all)
|
||||
|
||||
assertEquals(all, merged)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mergeWithExistingQueue handles empty all list`() {
|
||||
val existing = listOf("w1", "w2")
|
||||
val all = emptyList<String>()
|
||||
|
||||
val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all)
|
||||
|
||||
assertTrue(merged.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mergeWithExistingQueue complex scenario`() {
|
||||
// Existing queue order: w3, w1, w5 (w2 was played)
|
||||
// Current album: w1, w3, w4, w5, w6 (w2 removed, w4 and w6 added)
|
||||
val existing = listOf("w3", "w1", "w5")
|
||||
val all = listOf("w1", "w3", "w4", "w5", "w6")
|
||||
|
||||
val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all)
|
||||
|
||||
// Should preserve w3, w1, w5 order, then add w4, w6
|
||||
assertEquals(listOf("w3", "w1", "w5", "w4", "w6"), merged)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: buildQueue
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `buildQueue sequential uses display order`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("w2", displayOrder = 1),
|
||||
createWallpaper("w1", displayOrder = 0)
|
||||
)
|
||||
|
||||
val result = QueueBuilder.buildQueue(wallpapers, shuffle = false)
|
||||
|
||||
assertEquals(listOf("w1", "w2"), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildQueue shuffle without other screen produces new shuffle`() {
|
||||
val wallpapers = (1..50).map { createWallpaper("w$it") }
|
||||
|
||||
val result = QueueBuilder.buildQueue(wallpapers, shuffle = true)
|
||||
|
||||
assertEquals(50, result.size)
|
||||
assertTrue(result.containsAll(wallpapers.map { it.id }))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `buildQueue shuffle with other screen synchronizes order`() {
|
||||
val wallpapers = (1..5).map { createWallpaper("w$it") }
|
||||
val otherQueue = listOf("w3", "w1", "w2", "w4", "w5")
|
||||
|
||||
val result = QueueBuilder.buildQueue(wallpapers, shuffle = true, otherScreenQueue = otherQueue)
|
||||
|
||||
assertEquals(otherQueue, result)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
private fun createWallpaper(id: String, displayOrder: Int = 0) = com.anthonyla.paperize.domain.model.Wallpaper(
|
||||
id = id,
|
||||
albumId = "album-1",
|
||||
uri = "content://test/$id",
|
||||
fileName = "$id.jpg",
|
||||
displayOrder = displayOrder,
|
||||
dateModified = System.currentTimeMillis()
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for WallpaperSorter utility
|
||||
*/
|
||||
class WallpaperSorterTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: sortWallpapersByName
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByName ascending sorts A to Z`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("z_photo.jpg"),
|
||||
createWallpaper("a_photo.jpg"),
|
||||
createWallpaper("m_photo.jpg")
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true)
|
||||
|
||||
assertEquals("a_photo.jpg", sorted[0].fileName)
|
||||
assertEquals("m_photo.jpg", sorted[1].fileName)
|
||||
assertEquals("z_photo.jpg", sorted[2].fileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByName descending sorts Z to A`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("a_photo.jpg"),
|
||||
createWallpaper("m_photo.jpg"),
|
||||
createWallpaper("z_photo.jpg")
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = false)
|
||||
|
||||
assertEquals("z_photo.jpg", sorted[0].fileName)
|
||||
assertEquals("m_photo.jpg", sorted[1].fileName)
|
||||
assertEquals("a_photo.jpg", sorted[2].fileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByName is case insensitive`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("Zebra.jpg"),
|
||||
createWallpaper("apple.jpg"),
|
||||
createWallpaper("BANANA.jpg")
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true)
|
||||
|
||||
assertEquals("apple.jpg", sorted[0].fileName)
|
||||
assertEquals("BANANA.jpg", sorted[1].fileName)
|
||||
assertEquals("Zebra.jpg", sorted[2].fileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByName with empty list returns empty list`() {
|
||||
val sorted = WallpaperSorter.sortWallpapersByName(emptyList(), ascending = true)
|
||||
assertTrue(sorted.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByName with single item returns same list`() {
|
||||
val wallpapers = listOf(createWallpaper("photo.jpg"))
|
||||
val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true)
|
||||
assertEquals(1, sorted.size)
|
||||
assertEquals("photo.jpg", sorted[0].fileName)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortWallpapersByDateAdded
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByDateAdded ascending sorts oldest first`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("c.jpg", addedAt = 3000L),
|
||||
createWallpaper("a.jpg", addedAt = 1000L),
|
||||
createWallpaper("b.jpg", addedAt = 2000L)
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByDateAdded(wallpapers, ascending = true)
|
||||
|
||||
assertEquals(1000L, sorted[0].addedAt)
|
||||
assertEquals(2000L, sorted[1].addedAt)
|
||||
assertEquals(3000L, sorted[2].addedAt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByDateAdded descending sorts newest first`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("a.jpg", addedAt = 1000L),
|
||||
createWallpaper("c.jpg", addedAt = 3000L),
|
||||
createWallpaper("b.jpg", addedAt = 2000L)
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByDateAdded(wallpapers, ascending = false)
|
||||
|
||||
assertEquals(3000L, sorted[0].addedAt)
|
||||
assertEquals(2000L, sorted[1].addedAt)
|
||||
assertEquals(1000L, sorted[2].addedAt)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortWallpapersByDateModified
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByDateModified ascending sorts oldest first`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("c.jpg", dateModified = 3000L),
|
||||
createWallpaper("a.jpg", dateModified = 1000L),
|
||||
createWallpaper("b.jpg", dateModified = 2000L)
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByDateModified(wallpapers, ascending = true)
|
||||
|
||||
assertEquals(1000L, sorted[0].dateModified)
|
||||
assertEquals(2000L, sorted[1].dateModified)
|
||||
assertEquals(3000L, sorted[2].dateModified)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortWallpapersByDateModified descending sorts newest first`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("a.jpg", dateModified = 1000L),
|
||||
createWallpaper("c.jpg", dateModified = 3000L),
|
||||
createWallpaper("b.jpg", dateModified = 2000L)
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByDateModified(wallpapers, ascending = false)
|
||||
|
||||
assertEquals(3000L, sorted[0].dateModified)
|
||||
assertEquals(2000L, sorted[1].dateModified)
|
||||
assertEquals(1000L, sorted[2].dateModified)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortFoldersByName
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortFoldersByName ascending sorts A to Z`() {
|
||||
val folders = listOf(
|
||||
createFolder("Wallpapers"),
|
||||
createFolder("Animals"),
|
||||
createFolder("Nature")
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortFoldersByName(folders, ascending = true)
|
||||
|
||||
assertEquals("Animals", sorted[0].name)
|
||||
assertEquals("Nature", sorted[1].name)
|
||||
assertEquals("Wallpapers", sorted[2].name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortFoldersByName descending sorts Z to A`() {
|
||||
val folders = listOf(
|
||||
createFolder("Animals"),
|
||||
createFolder("Nature"),
|
||||
createFolder("Wallpapers")
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortFoldersByName(folders, ascending = false)
|
||||
|
||||
assertEquals("Wallpapers", sorted[0].name)
|
||||
assertEquals("Nature", sorted[1].name)
|
||||
assertEquals("Animals", sorted[2].name)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortFoldersByDateModified
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortFoldersByDateModified ascending sorts oldest first`() {
|
||||
val folders = listOf(
|
||||
createFolder("C", dateModified = 3000L),
|
||||
createFolder("A", dateModified = 1000L),
|
||||
createFolder("B", dateModified = 2000L)
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortFoldersByDateModified(folders, ascending = true)
|
||||
|
||||
assertEquals(1000L, sorted[0].dateModified)
|
||||
assertEquals(2000L, sorted[1].dateModified)
|
||||
assertEquals(3000L, sorted[2].dateModified)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: applyDisplayOrder
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `applyDisplayOrder sets indices correctly`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("a.jpg", displayOrder = 5),
|
||||
createWallpaper("b.jpg", displayOrder = 10),
|
||||
createWallpaper("c.jpg", displayOrder = 15)
|
||||
)
|
||||
|
||||
val result = WallpaperSorter.applyDisplayOrder(wallpapers)
|
||||
|
||||
assertEquals(0, result[0].displayOrder)
|
||||
assertEquals(1, result[1].displayOrder)
|
||||
assertEquals(2, result[2].displayOrder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `applyDisplayOrder with empty list returns empty list`() {
|
||||
val result = WallpaperSorter.applyDisplayOrder(emptyList())
|
||||
assertTrue(result.isEmpty())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: applyFolderDisplayOrder
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `applyFolderDisplayOrder sets indices correctly`() {
|
||||
val folders = listOf(
|
||||
createFolder("A", displayOrder = 99),
|
||||
createFolder("B", displayOrder = 50),
|
||||
createFolder("C", displayOrder = 1)
|
||||
)
|
||||
|
||||
val result = WallpaperSorter.applyFolderDisplayOrder(folders)
|
||||
|
||||
assertEquals(0, result[0].displayOrder)
|
||||
assertEquals(1, result[1].displayOrder)
|
||||
assertEquals(2, result[2].displayOrder)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Integration - Sort then apply order
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sort then applyDisplayOrder produces correct order`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("z.jpg", displayOrder = 0),
|
||||
createWallpaper("a.jpg", displayOrder = 1),
|
||||
createWallpaper("m.jpg", displayOrder = 2)
|
||||
)
|
||||
|
||||
val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true)
|
||||
val withOrder = WallpaperSorter.applyDisplayOrder(sorted)
|
||||
|
||||
assertEquals("a.jpg", withOrder[0].fileName)
|
||||
assertEquals(0, withOrder[0].displayOrder)
|
||||
assertEquals("m.jpg", withOrder[1].fileName)
|
||||
assertEquals(1, withOrder[1].displayOrder)
|
||||
assertEquals("z.jpg", withOrder[2].fileName)
|
||||
assertEquals(2, withOrder[2].displayOrder)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: shiftWallpaper
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `shiftWallpaper moves item and updates indices`() {
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("a.jpg", displayOrder = 0),
|
||||
createWallpaper("b.jpg", displayOrder = 1),
|
||||
createWallpaper("c.jpg", displayOrder = 2)
|
||||
)
|
||||
|
||||
// Move 'a' to the end (index 2)
|
||||
val result = WallpaperSorter.shiftWallpaper(wallpapers, "content://test/a.jpg", "content://test/c.jpg")
|
||||
|
||||
assertEquals("b.jpg", result[0].fileName)
|
||||
assertEquals(0, result[0].displayOrder)
|
||||
assertEquals("c.jpg", result[1].fileName)
|
||||
assertEquals(1, result[1].displayOrder)
|
||||
assertEquals("a.jpg", result[2].fileName)
|
||||
assertEquals(2, result[2].displayOrder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `shiftWallpaper handles invalid URIs`() {
|
||||
val wallpapers = listOf(createWallpaper("a.jpg"))
|
||||
val result = WallpaperSorter.shiftWallpaper(wallpapers, "invalid", "invalid")
|
||||
assertEquals(wallpapers, result)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: shiftFolder
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `shiftFolder moves folder and updates indices`() {
|
||||
val folders = listOf(
|
||||
createFolder("A", displayOrder = 0),
|
||||
createFolder("B", displayOrder = 1),
|
||||
createFolder("C", displayOrder = 2)
|
||||
)
|
||||
|
||||
// Move 'C' to the beginning (index 0)
|
||||
val result = WallpaperSorter.shiftFolder(folders, "content://folder/C", "content://folder/A")
|
||||
|
||||
assertEquals("C", result[0].name)
|
||||
assertEquals(0, result[0].displayOrder)
|
||||
assertEquals("A", result[1].name)
|
||||
assertEquals(1, result[1].displayOrder)
|
||||
assertEquals("B", result[2].name)
|
||||
assertEquals(2, result[2].displayOrder)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: shiftWallpaperInFolder
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `shiftWallpaperInFolder updates correct folder and cover URI`() {
|
||||
val folders = listOf(
|
||||
createFolder("F1").copy(
|
||||
wallpapers = listOf(
|
||||
createWallpaper("w1"),
|
||||
createWallpaper("w2")
|
||||
)
|
||||
),
|
||||
createFolder("F2")
|
||||
)
|
||||
|
||||
val result = WallpaperSorter.shiftWallpaperInFolder(
|
||||
folders,
|
||||
"folder-F1",
|
||||
"content://test/w1",
|
||||
"content://test/w2"
|
||||
)
|
||||
|
||||
val f1 = result.find { it.name == "F1" }!!
|
||||
assertEquals("w2", f1.wallpapers[0].fileName)
|
||||
assertEquals("w1", f1.wallpapers[1].fileName)
|
||||
assertEquals("content://test/w2", f1.coverUri)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortAllAlphabetically
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortAllAlphabetically sorts everything correctly`() {
|
||||
val folders = listOf(
|
||||
createFolder("Z"),
|
||||
createFolder("A").copy(
|
||||
wallpapers = listOf(
|
||||
createWallpaper("w2"),
|
||||
createWallpaper("w1")
|
||||
)
|
||||
)
|
||||
)
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("z.jpg"),
|
||||
createWallpaper("a.jpg")
|
||||
)
|
||||
|
||||
val (sortedFolders, sortedWallpapers) = WallpaperSorter.sortAllAlphabetically(folders, wallpapers)
|
||||
|
||||
assertEquals("A", sortedFolders[0].name)
|
||||
assertEquals("w1", sortedFolders[0].wallpapers[0].fileName)
|
||||
assertEquals("Z", sortedFolders[1].name)
|
||||
assertEquals("a.jpg", sortedWallpapers[0].fileName)
|
||||
assertEquals("z.jpg", sortedWallpapers[1].fileName)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortAllByDateModified
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortAllByDateModified sorts everything correctly`() {
|
||||
val folders = listOf(
|
||||
createFolder("Old", dateModified = 100L),
|
||||
createFolder("New", dateModified = 500L).copy(
|
||||
wallpapers = listOf(
|
||||
createWallpaper("wNew", dateModified = 500L),
|
||||
createWallpaper("wOld", dateModified = 100L)
|
||||
)
|
||||
)
|
||||
)
|
||||
val wallpapers = listOf(
|
||||
createWallpaper("z.jpg", dateModified = 500L),
|
||||
createWallpaper("a.jpg", dateModified = 100L)
|
||||
)
|
||||
|
||||
val (sortedFolders, sortedWallpapers) = WallpaperSorter.sortAllByDateModified(folders, wallpapers, ascending = true)
|
||||
|
||||
assertEquals("Old", sortedFolders[0].name)
|
||||
assertEquals("New", sortedFolders[1].name)
|
||||
assertEquals("wOld", sortedFolders[1].wallpapers[0].fileName)
|
||||
assertEquals("a.jpg", sortedWallpapers[0].fileName)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
private fun createWallpaper(
|
||||
fileName: String,
|
||||
displayOrder: Int = 0,
|
||||
addedAt: Long = System.currentTimeMillis(),
|
||||
dateModified: Long = System.currentTimeMillis()
|
||||
) = Wallpaper(
|
||||
id = "id-$fileName",
|
||||
albumId = "album-1",
|
||||
uri = "content://test/$fileName",
|
||||
fileName = fileName,
|
||||
displayOrder = displayOrder,
|
||||
addedAt = addedAt,
|
||||
dateModified = dateModified
|
||||
)
|
||||
|
||||
private fun createFolder(
|
||||
name: String,
|
||||
displayOrder: Int = 0,
|
||||
dateModified: Long = System.currentTimeMillis()
|
||||
) = Folder(
|
||||
id = "folder-$name",
|
||||
albumId = "album-1",
|
||||
name = name,
|
||||
uri = "content://folder/$name",
|
||||
coverUri = null,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for AlbumMapper
|
||||
*/
|
||||
class AlbumMapperTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: AlbumEntity.toDomainModel()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel maps all fields correctly`() {
|
||||
val entity = createAlbumEntity()
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertEquals(entity.id, domain.id)
|
||||
assertEquals(entity.name, domain.name)
|
||||
assertEquals(entity.coverUri, domain.coverUri)
|
||||
assertEquals(entity.createdAt, domain.createdAt)
|
||||
assertEquals(entity.modifiedAt, domain.modifiedAt)
|
||||
assertTrue(domain.wallpapers.isEmpty())
|
||||
assertTrue(domain.folders.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel with wallpapers includes them`() {
|
||||
val entity = createAlbumEntity()
|
||||
val wallpapers = listOf(
|
||||
createWallpaper(id = "w1"),
|
||||
createWallpaper(id = "w2")
|
||||
)
|
||||
|
||||
val domain = entity.toDomainModel(wallpapers = wallpapers)
|
||||
|
||||
assertEquals(2, domain.wallpapers.size)
|
||||
assertEquals("w1", domain.wallpapers[0].id)
|
||||
assertEquals("w2", domain.wallpapers[1].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel with folders includes them`() {
|
||||
val entity = createAlbumEntity()
|
||||
val folders = listOf(
|
||||
createFolder(id = "f1"),
|
||||
createFolder(id = "f2")
|
||||
)
|
||||
|
||||
val domain = entity.toDomainModel(folders = folders)
|
||||
|
||||
assertEquals(2, domain.folders.size)
|
||||
assertEquals("f1", domain.folders[0].id)
|
||||
assertEquals("f2", domain.folders[1].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel with wallpapers and folders includes both`() {
|
||||
val entity = createAlbumEntity()
|
||||
val wallpapers = listOf(createWallpaper(id = "w1"))
|
||||
val folders = listOf(createFolder(id = "f1"))
|
||||
|
||||
val domain = entity.toDomainModel(wallpapers = wallpapers, folders = folders)
|
||||
|
||||
assertEquals(1, domain.wallpapers.size)
|
||||
assertEquals(1, domain.folders.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity with null coverUri maps correctly`() {
|
||||
val entity = createAlbumEntity(coverUri = null)
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertNull(domain.coverUri)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Album.toEntity()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `domain toEntity maps all fields correctly`() {
|
||||
val domain = createAlbumDomain()
|
||||
val entity = domain.toEntity()
|
||||
|
||||
assertEquals(domain.id, entity.id)
|
||||
assertEquals(domain.name, entity.name)
|
||||
assertEquals(domain.coverUri, entity.coverUri)
|
||||
assertEquals(domain.createdAt, entity.createdAt)
|
||||
assertEquals(domain.modifiedAt, entity.modifiedAt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `domain toEntity does not include nested collections`() {
|
||||
val domain = createAlbumDomain().copy(
|
||||
wallpapers = listOf(createWallpaper(id = "w1")),
|
||||
folders = listOf(createFolder(id = "f1"))
|
||||
)
|
||||
val entity = domain.toEntity()
|
||||
|
||||
// Entity should only have album fields, not nested collections
|
||||
assertEquals(domain.id, entity.id)
|
||||
assertEquals(domain.name, entity.name)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: List extensions
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `list of entities toDomainModels maps all items`() {
|
||||
val entities = listOf(
|
||||
createAlbumEntity(id = "a1", name = "Album 1"),
|
||||
createAlbumEntity(id = "a2", name = "Album 2"),
|
||||
createAlbumEntity(id = "a3", name = "Album 3")
|
||||
)
|
||||
|
||||
val domains = entities.toDomainModels()
|
||||
|
||||
assertEquals(3, domains.size)
|
||||
assertEquals("a1", domains[0].id)
|
||||
assertEquals("a2", domains[1].id)
|
||||
assertEquals("a3", domains[2].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty list toDomainModels returns empty list`() {
|
||||
val entities = emptyList<AlbumEntity>()
|
||||
val domains = entities.toDomainModels()
|
||||
|
||||
assertTrue(domains.isEmpty())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Round-trip conversion
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `entity to domain to entity preserves all data`() {
|
||||
val original = createAlbumEntity()
|
||||
val converted = original.toDomainModel().toEntity()
|
||||
|
||||
assertEquals(original.id, converted.id)
|
||||
assertEquals(original.name, converted.name)
|
||||
assertEquals(original.coverUri, converted.coverUri)
|
||||
assertEquals(original.createdAt, converted.createdAt)
|
||||
assertEquals(original.modifiedAt, converted.modifiedAt)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
private fun createAlbumEntity(
|
||||
id: String = "album-1",
|
||||
name: String = "Test Album",
|
||||
coverUri: String? = "content://cover/image.jpg"
|
||||
) = AlbumEntity(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
createdAt = 1000L,
|
||||
modifiedAt = 2000L
|
||||
)
|
||||
|
||||
private fun createAlbumDomain() = Album(
|
||||
id = "album-1",
|
||||
name = "Test Album",
|
||||
coverUri = "content://cover/image.jpg",
|
||||
createdAt = 1000L,
|
||||
modifiedAt = 2000L
|
||||
)
|
||||
|
||||
private fun createWallpaper(id: String) = Wallpaper.empty(id = id, albumId = "album-1")
|
||||
|
||||
private fun createFolder(id: String) = Folder.empty(id = id, albumId = "album-1")
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for FolderMapper
|
||||
*/
|
||||
class FolderMapperTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: FolderEntity.toDomainModel()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel maps all fields correctly`() {
|
||||
val entity = createFolderEntity()
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertEquals(entity.id, domain.id)
|
||||
assertEquals(entity.albumId, domain.albumId)
|
||||
assertEquals(entity.name, domain.name)
|
||||
assertEquals(entity.uri, domain.uri)
|
||||
assertEquals(entity.coverUri, domain.coverUri)
|
||||
assertEquals(entity.dateModified, domain.dateModified)
|
||||
assertEquals(entity.displayOrder, domain.displayOrder)
|
||||
assertEquals(entity.addedAt, domain.addedAt)
|
||||
assertTrue(domain.wallpapers.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel with wallpapers includes them`() {
|
||||
val entity = createFolderEntity()
|
||||
val wallpapers = listOf(
|
||||
createWallpaper(id = "w1"),
|
||||
createWallpaper(id = "w2")
|
||||
)
|
||||
|
||||
val domain = entity.toDomainModel(wallpapers)
|
||||
|
||||
assertEquals(2, domain.wallpapers.size)
|
||||
assertEquals("w1", domain.wallpapers[0].id)
|
||||
assertEquals("w2", domain.wallpapers[1].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity with null coverUri maps correctly`() {
|
||||
val entity = createFolderEntity(coverUri = null)
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertNull(domain.coverUri)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity with coverUri maps correctly`() {
|
||||
val entity = createFolderEntity(coverUri = "content://cover/image.jpg")
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertEquals("content://cover/image.jpg", domain.coverUri)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Folder.toEntity()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `domain toEntity maps all fields correctly`() {
|
||||
val domain = createFolderDomain()
|
||||
val entity = domain.toEntity()
|
||||
|
||||
assertEquals(domain.id, entity.id)
|
||||
assertEquals(domain.albumId, entity.albumId)
|
||||
assertEquals(domain.name, entity.name)
|
||||
assertEquals(domain.uri, entity.uri)
|
||||
assertEquals(domain.coverUri, entity.coverUri)
|
||||
assertEquals(domain.dateModified, entity.dateModified)
|
||||
assertEquals(domain.displayOrder, entity.displayOrder)
|
||||
assertEquals(domain.addedAt, entity.addedAt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `domain toEntity does not include wallpapers`() {
|
||||
val domain = createFolderDomain().copy(
|
||||
wallpapers = listOf(createWallpaper(id = "w1"))
|
||||
)
|
||||
val entity = domain.toEntity()
|
||||
|
||||
// Entity should not have wallpapers - they're stored separately
|
||||
assertEquals(domain.id, entity.id)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: List extensions
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `list of entities toDomainModels maps all items`() {
|
||||
val entities = listOf(
|
||||
createFolderEntity(id = "f1"),
|
||||
createFolderEntity(id = "f2"),
|
||||
createFolderEntity(id = "f3")
|
||||
)
|
||||
|
||||
val domains = entities.toDomainModels()
|
||||
|
||||
assertEquals(3, domains.size)
|
||||
assertEquals("f1", domains[0].id)
|
||||
assertEquals("f2", domains[1].id)
|
||||
assertEquals("f3", domains[2].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty list toDomainModels returns empty list`() {
|
||||
val entities = emptyList<FolderEntity>()
|
||||
val domains = entities.toDomainModels()
|
||||
|
||||
assertTrue(domains.isEmpty())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Round-trip conversion
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `entity to domain to entity preserves all data`() {
|
||||
val original = createFolderEntity()
|
||||
val converted = original.toDomainModel().toEntity()
|
||||
|
||||
assertEquals(original.id, converted.id)
|
||||
assertEquals(original.albumId, converted.albumId)
|
||||
assertEquals(original.name, converted.name)
|
||||
assertEquals(original.uri, converted.uri)
|
||||
assertEquals(original.coverUri, converted.coverUri)
|
||||
assertEquals(original.dateModified, converted.dateModified)
|
||||
assertEquals(original.displayOrder, converted.displayOrder)
|
||||
assertEquals(original.addedAt, converted.addedAt)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
private fun createFolderEntity(
|
||||
id: String = "folder-1",
|
||||
coverUri: String? = "content://cover/default.jpg"
|
||||
) = FolderEntity(
|
||||
id = id,
|
||||
albumId = "album-1",
|
||||
name = "Test Folder",
|
||||
uri = "content://folder/test",
|
||||
coverUri = coverUri,
|
||||
dateModified = 1000L,
|
||||
displayOrder = 0,
|
||||
addedAt = 2000L
|
||||
)
|
||||
|
||||
private fun createFolderDomain() = Folder(
|
||||
id = "folder-1",
|
||||
albumId = "album-1",
|
||||
name = "Test Folder",
|
||||
uri = "content://folder/test",
|
||||
coverUri = "content://cover/default.jpg",
|
||||
dateModified = 1000L,
|
||||
displayOrder = 0,
|
||||
addedAt = 2000L
|
||||
)
|
||||
|
||||
private fun createWallpaper(id: String) = Wallpaper.empty(id = id, albumId = "album-1")
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for WallpaperMapper
|
||||
*/
|
||||
class WallpaperMapperTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: WallpaperEntity.toDomainModel()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `entity toDomainModel maps all fields correctly`() {
|
||||
val entity = createWallpaperEntity()
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertEquals(entity.id, domain.id)
|
||||
assertEquals(entity.albumId, domain.albumId)
|
||||
assertEquals(entity.folderId, domain.folderId)
|
||||
assertEquals(entity.uri, domain.uri)
|
||||
assertEquals(entity.fileName, domain.fileName)
|
||||
assertEquals(entity.dateModified, domain.dateModified)
|
||||
assertEquals(entity.displayOrder, domain.displayOrder)
|
||||
assertEquals(entity.sourceType, domain.sourceType)
|
||||
assertEquals(entity.addedAt, domain.addedAt)
|
||||
assertEquals(entity.mediaType, domain.mediaType)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity with null folderId maps correctly`() {
|
||||
val entity = createWallpaperEntity(folderId = null)
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertNull(domain.folderId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `entity with FOLDER sourceType maps correctly`() {
|
||||
val entity = createWallpaperEntity(
|
||||
folderId = "folder-123",
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
val domain = entity.toDomainModel()
|
||||
|
||||
assertEquals("folder-123", domain.folderId)
|
||||
assertEquals(WallpaperSourceType.FOLDER, domain.sourceType)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Wallpaper.toEntity()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `domain toEntity maps all fields correctly`() {
|
||||
val domain = createWallpaperDomain()
|
||||
val entity = domain.toEntity()
|
||||
|
||||
assertEquals(domain.id, entity.id)
|
||||
assertEquals(domain.albumId, entity.albumId)
|
||||
assertEquals(domain.folderId, entity.folderId)
|
||||
assertEquals(domain.uri, entity.uri)
|
||||
assertEquals(domain.fileName, entity.fileName)
|
||||
assertEquals(domain.dateModified, entity.dateModified)
|
||||
assertEquals(domain.displayOrder, entity.displayOrder)
|
||||
assertEquals(domain.sourceType, entity.sourceType)
|
||||
assertEquals(domain.addedAt, entity.addedAt)
|
||||
assertEquals(domain.mediaType, entity.mediaType)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `domain with null folderId toEntity maps correctly`() {
|
||||
val domain = createWallpaperDomain(folderId = null)
|
||||
val entity = domain.toEntity()
|
||||
|
||||
assertNull(entity.folderId)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: List extensions
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `list of entities toDomainModels maps all items`() {
|
||||
val entities = listOf(
|
||||
createWallpaperEntity(id = "w1"),
|
||||
createWallpaperEntity(id = "w2"),
|
||||
createWallpaperEntity(id = "w3")
|
||||
)
|
||||
|
||||
val domains = entities.toDomainModels()
|
||||
|
||||
assertEquals(3, domains.size)
|
||||
assertEquals("w1", domains[0].id)
|
||||
assertEquals("w2", domains[1].id)
|
||||
assertEquals("w3", domains[2].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty list toDomainModels returns empty list`() {
|
||||
val entities = emptyList<WallpaperEntity>()
|
||||
val domains = entities.toDomainModels()
|
||||
|
||||
assertTrue(domains.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `list of domains toEntities maps all items`() {
|
||||
val domains = listOf(
|
||||
createWallpaperDomain(id = "w1"),
|
||||
createWallpaperDomain(id = "w2")
|
||||
)
|
||||
|
||||
val entities = domains.toEntities()
|
||||
|
||||
assertEquals(2, entities.size)
|
||||
assertEquals("w1", entities[0].id)
|
||||
assertEquals("w2", entities[1].id)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Round-trip conversion
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `entity to domain to entity preserves all data`() {
|
||||
val original = createWallpaperEntity()
|
||||
val converted = original.toDomainModel().toEntity()
|
||||
|
||||
assertEquals(original.id, converted.id)
|
||||
assertEquals(original.albumId, converted.albumId)
|
||||
assertEquals(original.folderId, converted.folderId)
|
||||
assertEquals(original.uri, converted.uri)
|
||||
assertEquals(original.fileName, converted.fileName)
|
||||
assertEquals(original.dateModified, converted.dateModified)
|
||||
assertEquals(original.displayOrder, converted.displayOrder)
|
||||
assertEquals(original.sourceType, converted.sourceType)
|
||||
assertEquals(original.addedAt, converted.addedAt)
|
||||
assertEquals(original.mediaType, converted.mediaType)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helpers
|
||||
// ============================================================
|
||||
|
||||
private fun createWallpaperEntity(
|
||||
id: String = "wallpaper-1",
|
||||
folderId: String? = null,
|
||||
sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT
|
||||
) = WallpaperEntity(
|
||||
id = id,
|
||||
albumId = "album-1",
|
||||
folderId = folderId,
|
||||
uri = "content://test/image.jpg",
|
||||
fileName = "image.jpg",
|
||||
dateModified = 1000L,
|
||||
displayOrder = 0,
|
||||
sourceType = sourceType,
|
||||
addedAt = 2000L,
|
||||
mediaType = WallpaperMediaType.IMAGE
|
||||
)
|
||||
|
||||
private fun createWallpaperDomain(
|
||||
id: String = "wallpaper-1",
|
||||
folderId: String? = null
|
||||
) = Wallpaper(
|
||||
id = id,
|
||||
albumId = "album-1",
|
||||
folderId = folderId,
|
||||
uri = "content://test/image.jpg",
|
||||
fileName = "image.jpg",
|
||||
dateModified = 1000L,
|
||||
displayOrder = 0,
|
||||
sourceType = WallpaperSourceType.DIRECT,
|
||||
addedAt = 2000L,
|
||||
mediaType = WallpaperMediaType.IMAGE
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for Album domain model
|
||||
*/
|
||||
class AlbumTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: totalWallpaperCount
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `totalWallpaperCount with empty album returns zero`() {
|
||||
val album = Album.empty(id = "1", name = "Test")
|
||||
assertEquals(0, album.totalWallpaperCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `totalWallpaperCount with direct wallpapers only`() {
|
||||
val wallpapers = listOf(
|
||||
Wallpaper.empty(id = "w1", albumId = "1"),
|
||||
Wallpaper.empty(id = "w2", albumId = "1")
|
||||
)
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
wallpapers = wallpapers
|
||||
)
|
||||
assertEquals(2, album.totalWallpaperCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `totalWallpaperCount with folders only`() {
|
||||
val folderWallpapers = listOf(
|
||||
Wallpaper.empty(id = "w1", albumId = "1"),
|
||||
Wallpaper.empty(id = "w2", albumId = "1"),
|
||||
Wallpaper.empty(id = "w3", albumId = "1")
|
||||
)
|
||||
val folders = listOf(
|
||||
Folder.empty(id = "f1", albumId = "1").copy(wallpapers = folderWallpapers)
|
||||
)
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
folders = folders
|
||||
)
|
||||
assertEquals(3, album.totalWallpaperCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `totalWallpaperCount with mixed direct and folder wallpapers`() {
|
||||
val directWallpapers = listOf(
|
||||
Wallpaper.empty(id = "w1", albumId = "1")
|
||||
)
|
||||
val folderWallpapers = listOf(
|
||||
Wallpaper.empty(id = "w2", albumId = "1"),
|
||||
Wallpaper.empty(id = "w3", albumId = "1")
|
||||
)
|
||||
val folders = listOf(
|
||||
Folder.empty(id = "f1", albumId = "1").copy(wallpapers = folderWallpapers)
|
||||
)
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
wallpapers = directWallpapers,
|
||||
folders = folders
|
||||
)
|
||||
assertEquals(3, album.totalWallpaperCount)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: allWallpapers
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `allWallpapers returns combined direct and folder wallpapers`() {
|
||||
val directWallpaper = Wallpaper.empty(id = "direct", albumId = "1")
|
||||
val folderWallpaper = Wallpaper.empty(id = "folder", albumId = "1")
|
||||
val folders = listOf(
|
||||
Folder.empty(id = "f1", albumId = "1").copy(wallpapers = listOf(folderWallpaper))
|
||||
)
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
wallpapers = listOf(directWallpaper),
|
||||
folders = folders
|
||||
)
|
||||
|
||||
val allWallpapers = album.allWallpapers
|
||||
assertEquals(2, allWallpapers.size)
|
||||
assertTrue(allWallpapers.any { it.id == "direct" })
|
||||
assertTrue(allWallpapers.any { it.id == "folder" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `allWallpapers with empty album returns empty list`() {
|
||||
val album = Album.empty()
|
||||
assertTrue(album.allWallpapers.isEmpty())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortedWallpapers
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortedWallpapers returns wallpapers sorted by displayOrder`() {
|
||||
val wallpapers = listOf(
|
||||
Wallpaper.empty(id = "w3", albumId = "1").copy(displayOrder = 3),
|
||||
Wallpaper.empty(id = "w1", albumId = "1").copy(displayOrder = 1),
|
||||
Wallpaper.empty(id = "w2", albumId = "1").copy(displayOrder = 2)
|
||||
)
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
wallpapers = wallpapers
|
||||
)
|
||||
|
||||
val sorted = album.sortedWallpapers
|
||||
assertEquals("w1", sorted[0].id)
|
||||
assertEquals("w2", sorted[1].id)
|
||||
assertEquals("w3", sorted[2].id)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: isEmpty
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `isEmpty returns true for empty album`() {
|
||||
val album = Album.empty()
|
||||
assertTrue(album.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEmpty returns false when album has wallpapers`() {
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
wallpapers = listOf(Wallpaper.empty(id = "w1", albumId = "1"))
|
||||
)
|
||||
assertFalse(album.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEmpty returns false when folder has wallpapers`() {
|
||||
val folderWithWallpapers = Folder.empty(id = "f1", albumId = "1").copy(
|
||||
wallpapers = listOf(Wallpaper.empty(id = "w1", albumId = "1"))
|
||||
)
|
||||
val album = Album(
|
||||
id = "1",
|
||||
name = "Test",
|
||||
coverUri = null,
|
||||
folders = listOf(folderWithWallpapers)
|
||||
)
|
||||
assertFalse(album.isEmpty)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Companion object
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `empty factory creates album with empty collections`() {
|
||||
val album = Album.empty(id = "test-id", name = "Test Album")
|
||||
assertEquals("test-id", album.id)
|
||||
assertEquals("Test Album", album.name)
|
||||
assertNull(album.coverUri)
|
||||
assertTrue(album.wallpapers.isEmpty())
|
||||
assertTrue(album.folders.isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for Folder domain model
|
||||
*/
|
||||
class FolderTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: displayName
|
||||
// ============================================================
|
||||
|
||||
// Note: displayName uses Uri.decode() which is an Android API
|
||||
// These tests verify behavior in JVM environment where Uri.decode() returns input unchanged
|
||||
|
||||
@Test
|
||||
fun `displayName returns name for simple names`() {
|
||||
val folder = createFolder(name = "Wallpapers")
|
||||
// In JVM tests, Uri.decode returns null, so fallback to name is used
|
||||
assertEquals("Wallpapers", folder.displayName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `displayName handles empty name gracefully`() {
|
||||
val folder = createFolder(name = "")
|
||||
assertEquals("", folder.displayName)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: wallpaperCount
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `wallpaperCount returns zero for empty folder`() {
|
||||
val folder = Folder.empty()
|
||||
assertEquals(0, folder.wallpaperCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `wallpaperCount returns correct count`() {
|
||||
val wallpapers = listOf(
|
||||
Wallpaper.empty(id = "w1", albumId = "a1"),
|
||||
Wallpaper.empty(id = "w2", albumId = "a1"),
|
||||
Wallpaper.empty(id = "w3", albumId = "a1")
|
||||
)
|
||||
val folder = createFolder().copy(wallpapers = wallpapers)
|
||||
assertEquals(3, folder.wallpaperCount)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: isEmpty
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `isEmpty returns true for folder with no wallpapers`() {
|
||||
val folder = Folder.empty()
|
||||
assertTrue(folder.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isEmpty returns false for folder with wallpapers`() {
|
||||
val folder = createFolder().copy(
|
||||
wallpapers = listOf(Wallpaper.empty(id = "w1", albumId = "a1"))
|
||||
)
|
||||
assertFalse(folder.isEmpty)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: sortedWallpapers
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `sortedWallpapers returns wallpapers sorted by displayOrder`() {
|
||||
val wallpapers = listOf(
|
||||
Wallpaper.empty(id = "w3", albumId = "a1").copy(displayOrder = 3),
|
||||
Wallpaper.empty(id = "w1", albumId = "a1").copy(displayOrder = 1),
|
||||
Wallpaper.empty(id = "w2", albumId = "a1").copy(displayOrder = 2)
|
||||
)
|
||||
val folder = createFolder().copy(wallpapers = wallpapers)
|
||||
|
||||
val sorted = folder.sortedWallpapers
|
||||
assertEquals("w1", sorted[0].id)
|
||||
assertEquals("w2", sorted[1].id)
|
||||
assertEquals("w3", sorted[2].id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `sortedWallpapers returns empty list for empty folder`() {
|
||||
val folder = Folder.empty()
|
||||
assertTrue(folder.sortedWallpapers.isEmpty())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Companion object
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `empty factory creates folder with default values`() {
|
||||
val folder = Folder.empty(id = "test-id", albumId = "album-1")
|
||||
assertEquals("test-id", folder.id)
|
||||
assertEquals("album-1", folder.albumId)
|
||||
assertEquals("", folder.name)
|
||||
assertEquals("", folder.uri)
|
||||
assertNull(folder.coverUri)
|
||||
assertEquals(0L, folder.dateModified)
|
||||
assertTrue(folder.wallpapers.isEmpty())
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helper
|
||||
// ============================================================
|
||||
|
||||
private fun createFolder(
|
||||
name: String = "TestFolder"
|
||||
) = Folder(
|
||||
id = "folder-1",
|
||||
albumId = "album-1",
|
||||
name = name,
|
||||
uri = "content://folder/$name",
|
||||
coverUri = null,
|
||||
dateModified = System.currentTimeMillis(),
|
||||
displayOrder = 0
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for ScheduleSettings domain model
|
||||
*/
|
||||
class ScheduleSettingsTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: validate()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `validate coerces interval below minimum to minimum`() {
|
||||
val settings = ScheduleSettings(
|
||||
homeIntervalMinutes = 5, // Below MIN_INTERVAL_MINUTES (15)
|
||||
lockIntervalMinutes = 10,
|
||||
liveIntervalMinutes = 1
|
||||
)
|
||||
|
||||
val validated = settings.validate()
|
||||
|
||||
assertEquals(Constants.MIN_INTERVAL_MINUTES, validated.homeIntervalMinutes)
|
||||
assertEquals(Constants.MIN_INTERVAL_MINUTES, validated.lockIntervalMinutes)
|
||||
assertEquals(Constants.MIN_INTERVAL_MINUTES, validated.liveIntervalMinutes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate keeps valid intervals unchanged`() {
|
||||
val settings = ScheduleSettings(
|
||||
homeIntervalMinutes = 60,
|
||||
lockIntervalMinutes = 120,
|
||||
liveIntervalMinutes = 30
|
||||
)
|
||||
|
||||
val validated = settings.validate()
|
||||
|
||||
assertEquals(60, validated.homeIntervalMinutes)
|
||||
assertEquals(120, validated.lockIntervalMinutes)
|
||||
assertEquals(30, validated.liveIntervalMinutes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate validates effect percentages`() {
|
||||
val effects = WallpaperEffects(
|
||||
darkenPercentage = 150, // Over 100
|
||||
blurPercentage = -10 // Negative
|
||||
)
|
||||
val settings = ScheduleSettings(homeEffects = effects)
|
||||
|
||||
val validated = settings.validate()
|
||||
|
||||
assertEquals(100, validated.homeEffects.darkenPercentage)
|
||||
assertEquals(0, validated.homeEffects.blurPercentage)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: hasSchedulingChanges()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns false for identical settings`() {
|
||||
val settings1 = ScheduleSettings.default()
|
||||
val settings2 = ScheduleSettings.default()
|
||||
|
||||
assertFalse(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns true when homeEnabled changes`() {
|
||||
val settings1 = ScheduleSettings(homeEnabled = true)
|
||||
val settings2 = ScheduleSettings(homeEnabled = false)
|
||||
|
||||
assertTrue(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns true when lockEnabled changes`() {
|
||||
val settings1 = ScheduleSettings(lockEnabled = true)
|
||||
val settings2 = ScheduleSettings(lockEnabled = false)
|
||||
|
||||
assertTrue(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns true when homeIntervalMinutes changes`() {
|
||||
val settings1 = ScheduleSettings(homeIntervalMinutes = 60)
|
||||
val settings2 = ScheduleSettings(homeIntervalMinutes = 120)
|
||||
|
||||
assertTrue(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns true when lockIntervalMinutes changes`() {
|
||||
val settings1 = ScheduleSettings(lockIntervalMinutes = 60)
|
||||
val settings2 = ScheduleSettings(lockIntervalMinutes = 30)
|
||||
|
||||
assertTrue(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns true when separateSchedules changes`() {
|
||||
val settings1 = ScheduleSettings(separateSchedules = true)
|
||||
val settings2 = ScheduleSettings(separateSchedules = false)
|
||||
|
||||
assertTrue(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns true when liveIntervalMinutes changes`() {
|
||||
val settings1 = ScheduleSettings(liveIntervalMinutes = 60)
|
||||
val settings2 = ScheduleSettings(liveIntervalMinutes = 120)
|
||||
|
||||
assertTrue(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasSchedulingChanges returns false when only display settings change`() {
|
||||
val settings1 = ScheduleSettings(
|
||||
homeScalingType = ScalingType.FILL,
|
||||
adaptiveBrightness = false
|
||||
)
|
||||
val settings2 = ScheduleSettings(
|
||||
homeScalingType = ScalingType.FIT,
|
||||
adaptiveBrightness = true
|
||||
)
|
||||
|
||||
assertFalse(settings1.hasSchedulingChanges(settings2))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: hasDisplayChanges()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns false for identical settings`() {
|
||||
val settings1 = ScheduleSettings.default()
|
||||
val settings2 = ScheduleSettings.default()
|
||||
|
||||
assertFalse(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when homeScalingType changes`() {
|
||||
val settings1 = ScheduleSettings(homeScalingType = ScalingType.FILL)
|
||||
val settings2 = ScheduleSettings(homeScalingType = ScalingType.FIT)
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when lockScalingType changes`() {
|
||||
val settings1 = ScheduleSettings(lockScalingType = ScalingType.FILL)
|
||||
val settings2 = ScheduleSettings(lockScalingType = ScalingType.STRETCH)
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when homeEffects change`() {
|
||||
val settings1 = ScheduleSettings(homeEffects = WallpaperEffects(enableBlur = false))
|
||||
val settings2 = ScheduleSettings(homeEffects = WallpaperEffects(enableBlur = true))
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when lockEffects change`() {
|
||||
val settings1 = ScheduleSettings(lockEffects = WallpaperEffects(darkenPercentage = 0))
|
||||
val settings2 = ScheduleSettings(lockEffects = WallpaperEffects(darkenPercentage = 50))
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when liveEffects change`() {
|
||||
val settings1 = ScheduleSettings(liveEffects = WallpaperEffects.none())
|
||||
val settings2 = ScheduleSettings(liveEffects = WallpaperEffects(enableVignette = true))
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when liveScalingType changes`() {
|
||||
val settings1 = ScheduleSettings(liveScalingType = ScalingType.FILL)
|
||||
val settings2 = ScheduleSettings(liveScalingType = ScalingType.NONE)
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns true when adaptiveBrightness changes`() {
|
||||
val settings1 = ScheduleSettings(adaptiveBrightness = false)
|
||||
val settings2 = ScheduleSettings(adaptiveBrightness = true)
|
||||
|
||||
assertTrue(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasDisplayChanges returns false when only scheduling settings change`() {
|
||||
val settings1 = ScheduleSettings(
|
||||
homeEnabled = true,
|
||||
homeIntervalMinutes = 60
|
||||
)
|
||||
val settings2 = ScheduleSettings(
|
||||
homeEnabled = false,
|
||||
homeIntervalMinutes = 120
|
||||
)
|
||||
|
||||
assertFalse(settings1.hasDisplayChanges(settings2))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Companion object
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `default factory creates settings with default values`() {
|
||||
val settings = ScheduleSettings.default()
|
||||
|
||||
assertFalse(settings.enableChanger)
|
||||
assertFalse(settings.separateSchedules)
|
||||
assertFalse(settings.shuffleEnabled)
|
||||
assertFalse(settings.homeEnabled)
|
||||
assertFalse(settings.lockEnabled)
|
||||
assertNull(settings.homeAlbumId)
|
||||
assertNull(settings.lockAlbumId)
|
||||
assertEquals(Constants.DEFAULT_INTERVAL_MINUTES, settings.homeIntervalMinutes)
|
||||
assertEquals(Constants.DEFAULT_INTERVAL_MINUTES, settings.lockIntervalMinutes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for WallpaperEffects domain model
|
||||
*/
|
||||
class WallpaperEffectsTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: hasEffects
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns false when all effects disabled`() {
|
||||
val effects = WallpaperEffects.none()
|
||||
assertFalse(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns false when blur enabled but percentage is zero`() {
|
||||
val effects = WallpaperEffects(enableBlur = true, blurPercentage = 0)
|
||||
assertFalse(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns true when blur enabled with non-zero percentage`() {
|
||||
val effects = WallpaperEffects(enableBlur = true, blurPercentage = 50)
|
||||
assertTrue(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns true when darken enabled with non-zero percentage`() {
|
||||
val effects = WallpaperEffects(enableDarken = true, darkenPercentage = 25)
|
||||
assertTrue(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns true when vignette enabled with non-zero percentage`() {
|
||||
val effects = WallpaperEffects(enableVignette = true, vignettePercentage = 75)
|
||||
assertTrue(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns true when grayscale enabled with non-zero percentage`() {
|
||||
val effects = WallpaperEffects(enableGrayscale = true, grayscalePercentage = 100)
|
||||
assertTrue(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects returns true when multiple effects are enabled`() {
|
||||
val effects = WallpaperEffects(
|
||||
enableBlur = true,
|
||||
blurPercentage = 10,
|
||||
enableDarken = true,
|
||||
darkenPercentage = 20
|
||||
)
|
||||
assertTrue(effects.hasEffects)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hasEffects ignores interactive effects`() {
|
||||
val effects = WallpaperEffects(
|
||||
enableDoubleTap = true,
|
||||
enableParallax = true,
|
||||
parallaxIntensity = 100
|
||||
)
|
||||
assertFalse(effects.hasEffects)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: validate()
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `validate coerces darkenPercentage above 100 to 100`() {
|
||||
val effects = WallpaperEffects(darkenPercentage = 150)
|
||||
val validated = effects.validate()
|
||||
assertEquals(100, validated.darkenPercentage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate coerces negative darkenPercentage to 0`() {
|
||||
val effects = WallpaperEffects(darkenPercentage = -50)
|
||||
val validated = effects.validate()
|
||||
assertEquals(0, validated.darkenPercentage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate coerces blurPercentage above 100 to 100`() {
|
||||
val effects = WallpaperEffects(blurPercentage = 200)
|
||||
val validated = effects.validate()
|
||||
assertEquals(100, validated.blurPercentage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate coerces negative blurPercentage to 0`() {
|
||||
val effects = WallpaperEffects(blurPercentage = -10)
|
||||
val validated = effects.validate()
|
||||
assertEquals(0, validated.blurPercentage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate coerces vignettePercentage to valid range`() {
|
||||
val over = WallpaperEffects(vignettePercentage = 120)
|
||||
val under = WallpaperEffects(vignettePercentage = -5)
|
||||
|
||||
assertEquals(100, over.validate().vignettePercentage)
|
||||
assertEquals(0, under.validate().vignettePercentage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate coerces grayscalePercentage to valid range`() {
|
||||
val over = WallpaperEffects(grayscalePercentage = 999)
|
||||
val under = WallpaperEffects(grayscalePercentage = -1)
|
||||
|
||||
assertEquals(100, over.validate().grayscalePercentage)
|
||||
assertEquals(0, under.validate().grayscalePercentage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate coerces parallaxIntensity to valid range`() {
|
||||
val over = WallpaperEffects(parallaxIntensity = 150)
|
||||
val under = WallpaperEffects(parallaxIntensity = -25)
|
||||
|
||||
assertEquals(100, over.validate().parallaxIntensity)
|
||||
assertEquals(0, under.validate().parallaxIntensity)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate keeps valid values unchanged`() {
|
||||
val effects = WallpaperEffects(
|
||||
darkenPercentage = 50,
|
||||
blurPercentage = 25,
|
||||
vignettePercentage = 75,
|
||||
grayscalePercentage = 100,
|
||||
parallaxIntensity = 60
|
||||
)
|
||||
|
||||
val validated = effects.validate()
|
||||
|
||||
assertEquals(50, validated.darkenPercentage)
|
||||
assertEquals(25, validated.blurPercentage)
|
||||
assertEquals(75, validated.vignettePercentage)
|
||||
assertEquals(100, validated.grayscalePercentage)
|
||||
assertEquals(60, validated.parallaxIntensity)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `validate handles boundary values correctly`() {
|
||||
val minEffects = WallpaperEffects(
|
||||
darkenPercentage = 0,
|
||||
blurPercentage = 0,
|
||||
vignettePercentage = 0,
|
||||
grayscalePercentage = 0,
|
||||
parallaxIntensity = 0
|
||||
)
|
||||
val maxEffects = WallpaperEffects(
|
||||
darkenPercentage = 100,
|
||||
blurPercentage = 100,
|
||||
vignettePercentage = 100,
|
||||
grayscalePercentage = 100,
|
||||
parallaxIntensity = 100
|
||||
)
|
||||
|
||||
val validatedMin = minEffects.validate()
|
||||
val validatedMax = maxEffects.validate()
|
||||
|
||||
assertEquals(0, validatedMin.darkenPercentage)
|
||||
assertEquals(100, validatedMax.darkenPercentage)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Companion object
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `default factory creates effects with default values`() {
|
||||
val effects = WallpaperEffects.default()
|
||||
|
||||
assertFalse(effects.enableBlur)
|
||||
assertEquals(Constants.DEFAULT_BLUR_PERCENTAGE, effects.blurPercentage)
|
||||
assertFalse(effects.enableDarken)
|
||||
assertEquals(Constants.DEFAULT_DARKEN_PERCENTAGE, effects.darkenPercentage)
|
||||
assertFalse(effects.enableVignette)
|
||||
assertFalse(effects.enableGrayscale)
|
||||
assertFalse(effects.enableDoubleTap)
|
||||
assertFalse(effects.enableParallax)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `none factory creates same as default`() {
|
||||
val none = WallpaperEffects.none()
|
||||
val default = WallpaperEffects.default()
|
||||
|
||||
assertEquals(default, none)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Unit tests for Wallpaper domain model
|
||||
*/
|
||||
class WallpaperTest {
|
||||
|
||||
// ============================================================
|
||||
// Test: displayFileName
|
||||
// ============================================================
|
||||
|
||||
// Note: displayFileName uses Uri.decode() which is an Android API
|
||||
// These tests verify behavior in JVM environment where Uri.decode() returns input unchanged
|
||||
|
||||
@Test
|
||||
fun `displayFileName returns fileName for simple names`() {
|
||||
val wallpaper = createWallpaper(fileName = "image.jpg")
|
||||
// In JVM tests, Uri.decode returns null, so fallback to fileName is used
|
||||
assertEquals("image.jpg", wallpaper.displayFileName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `displayFileName handles empty fileName gracefully`() {
|
||||
val wallpaper = createWallpaper(fileName = "")
|
||||
assertEquals("", wallpaper.displayFileName)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: isFromFolder
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `isFromFolder returns true when folderId is set and sourceType is FOLDER`() {
|
||||
val wallpaper = createWallpaper(
|
||||
folderId = "folder-123",
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
assertTrue(wallpaper.isFromFolder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isFromFolder returns false when folderId is null`() {
|
||||
val wallpaper = createWallpaper(
|
||||
folderId = null,
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
assertFalse(wallpaper.isFromFolder)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isFromFolder returns false when sourceType is DIRECT`() {
|
||||
val wallpaper = createWallpaper(
|
||||
folderId = "folder-123",
|
||||
sourceType = WallpaperSourceType.DIRECT
|
||||
)
|
||||
assertFalse(wallpaper.isFromFolder)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: extension
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `extension extracts jpg extension`() {
|
||||
val wallpaper = createWallpaper(fileName = "photo.jpg")
|
||||
assertEquals("jpg", wallpaper.extension)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extension extracts JPEG extension as lowercase`() {
|
||||
val wallpaper = createWallpaper(fileName = "photo.JPEG")
|
||||
assertEquals("jpeg", wallpaper.extension)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extension returns empty string when no extension`() {
|
||||
val wallpaper = createWallpaper(fileName = "noextension")
|
||||
assertEquals("", wallpaper.extension)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `extension handles multiple dots correctly`() {
|
||||
val wallpaper = createWallpaper(fileName = "my.photo.file.png")
|
||||
assertEquals("png", wallpaper.extension)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: isValidImage
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns true for jpg`() {
|
||||
assertTrue(createWallpaper(fileName = "image.jpg").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns true for jpeg`() {
|
||||
assertTrue(createWallpaper(fileName = "image.jpeg").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns true for png`() {
|
||||
assertTrue(createWallpaper(fileName = "image.png").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns true for webp`() {
|
||||
assertTrue(createWallpaper(fileName = "image.webp").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns true for avif`() {
|
||||
assertTrue(createWallpaper(fileName = "image.avif").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns false for gif`() {
|
||||
assertFalse(createWallpaper(fileName = "animation.gif").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns false for bmp`() {
|
||||
assertFalse(createWallpaper(fileName = "image.bmp").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage returns false for no extension`() {
|
||||
assertFalse(createWallpaper(fileName = "noext").isValidImage)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `isValidImage is case insensitive`() {
|
||||
assertTrue(createWallpaper(fileName = "image.PNG").isValidImage)
|
||||
assertTrue(createWallpaper(fileName = "image.JPG").isValidImage)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Test: Companion object
|
||||
// ============================================================
|
||||
|
||||
@Test
|
||||
fun `empty factory creates wallpaper with default values`() {
|
||||
val wallpaper = Wallpaper.empty(id = "test-id", albumId = "album-1")
|
||||
assertEquals("test-id", wallpaper.id)
|
||||
assertEquals("album-1", wallpaper.albumId)
|
||||
assertEquals("", wallpaper.uri)
|
||||
assertEquals("", wallpaper.fileName)
|
||||
assertEquals(0L, wallpaper.dateModified)
|
||||
assertNull(wallpaper.folderId)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Helper
|
||||
// ============================================================
|
||||
|
||||
private fun createWallpaper(
|
||||
fileName: String = "test.jpg",
|
||||
folderId: String? = null,
|
||||
sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
|
||||
mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE
|
||||
) = Wallpaper(
|
||||
id = "test-id",
|
||||
albumId = "album-1",
|
||||
folderId = folderId,
|
||||
uri = "content://test/$fileName",
|
||||
fileName = fileName,
|
||||
dateModified = System.currentTimeMillis(),
|
||||
displayOrder = 0,
|
||||
sourceType = sourceType,
|
||||
mediaType = mediaType
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user