fix: bug hunt
This commit is contained in:
1 parent
be482fefbc
commit
89dc845f1b
18 files changed
+311
-275
No files matched your search
@@ -87,7 +87,7 @@ object Constants {
|
||||
|
||||
// Vignette effect
|
||||
const val VIGNETTE_DIVISOR = 150f // Radius calculation divisor
|
||||
const val VIGNETTE_MIN_RADIUS = 0.1f // Minimum vignette radius
|
||||
const val VIGNETTE_MIN_RADIUS = 1f // Minimum vignette radius (guards against zero-radius RadialGradient crash)
|
||||
const val VIGNETTE_INNER_ALPHA = 0.1f // Inner alpha for vignette gradient
|
||||
const val VIGNETTE_OUTER_ALPHA = 0.8f // Outer alpha for vignette gradient
|
||||
val VIGNETTE_GRADIENT_POSITIONS = floatArrayOf(0f, 0.7f, 1f) // Vignette gradient positions
|
||||
@@ -117,6 +117,7 @@ object Constants {
|
||||
const val PERCENTAGE_DIVISOR = 100f
|
||||
const val GL_ES_VERSION = 2
|
||||
const val SURFACE_POLL_INTERVAL_MS = 50L
|
||||
const val SURFACE_WAIT_TIMEOUT_MS = 1000L // Max wait for GL surface dimensions before falling back to display metrics
|
||||
|
||||
// Wallpaper loading
|
||||
const val MAX_WALLPAPER_LOAD_RETRIES = 10
|
||||
|
||||
@@ -41,20 +41,16 @@ fun Uri.scanFolderForImages(context: Context): List<Uri> {
|
||||
if (!documentFile.isDirectory) return emptyList()
|
||||
|
||||
val imageUris = mutableListOf<Uri>()
|
||||
val supportedTypes = setOf(
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/avif"
|
||||
)
|
||||
|
||||
fun scanDirectory(directory: DocumentFile) {
|
||||
directory.listFiles().forEach { file ->
|
||||
when {
|
||||
file.isDirectory -> scanDirectory(file) // Recursively scan subdirectories
|
||||
file.isFile && file.type in supportedTypes -> {
|
||||
imageUris.add(file.uri)
|
||||
file.isFile -> {
|
||||
val ext = file.name?.substringAfterLast('.', "")?.lowercase() ?: ""
|
||||
if (ext in com.anthonyla.paperize.core.constants.Constants.SUPPORTED_IMAGE_EXTENSIONS) {
|
||||
imageUris.add(file.uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,11 @@ object WallpaperSorter {
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByName(folder.wallpapers, ascending)
|
||||
folder.copy(wallpapers = applyDisplayOrder(sortedWallpapers))
|
||||
val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
|
||||
folder.copy(
|
||||
wallpapers = orderedWallpapers,
|
||||
coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
@@ -200,7 +204,11 @@ object WallpaperSorter {
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByDateModified(folder.wallpapers, ascending)
|
||||
folder.copy(wallpapers = applyDisplayOrder(sortedWallpapers))
|
||||
val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
|
||||
folder.copy(
|
||||
wallpapers = orderedWallpapers,
|
||||
coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
|
||||
@@ -15,6 +15,8 @@ import android.graphics.ImageDecoder
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.PorterDuff
|
||||
import android.graphics.PorterDuffXfermode
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RenderEffect
|
||||
import android.graphics.RenderNode
|
||||
@@ -199,50 +201,67 @@ fun retrieveBitmap(
|
||||
calculateInSampleSize(imageSize, width, height)
|
||||
}
|
||||
|
||||
// ImageDecoder auto-applies EXIF orientation and its info.size returns post-EXIF dimensions.
|
||||
// We must NOT call applyExifOrientation on the ImageDecoder result — it would double-rotate.
|
||||
// BitmapFactory does NOT auto-apply EXIF, so applyExifOrientation is needed only for that path.
|
||||
var decodedWithImageDecoder = false
|
||||
val bitmap = try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
|
||||
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
val result = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||
// info.size is the post-EXIF (display) size — use it for correct aspect-ratio math
|
||||
val srcWidth = info.size.width
|
||||
val srcHeight = info.size.height
|
||||
val (targetWidth, targetHeight) = when (scaling) {
|
||||
ScalingType.FILL -> {
|
||||
// Calculate scale to cover target dimensions
|
||||
val widthRatio = width.toFloat() / imageSize.width
|
||||
val heightRatio = height.toFloat() / imageSize.height
|
||||
val scale = maxOf(widthRatio, heightRatio)
|
||||
Pair((imageSize.width * scale).fastRoundToInt(), (imageSize.height * scale).fastRoundToInt())
|
||||
val scale = maxOf(width.toFloat() / srcWidth, height.toFloat() / srcHeight)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
}
|
||||
ScalingType.FIT -> {
|
||||
// Calculate scale to fit inside target dimensions
|
||||
val widthRatio = width.toFloat() / imageSize.width
|
||||
val heightRatio = height.toFloat() / imageSize.height
|
||||
val scale = minOf(widthRatio, heightRatio)
|
||||
Pair((imageSize.width * scale).fastRoundToInt(), (imageSize.height * scale).fastRoundToInt())
|
||||
val scale = minOf(width.toFloat() / srcWidth, height.toFloat() / srcHeight)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
}
|
||||
ScalingType.STRETCH -> Pair(width, height)
|
||||
ScalingType.NONE -> Pair(imageSize.width, imageSize.height)
|
||||
ScalingType.NONE -> {
|
||||
// Cap at 2× screen size to prevent OOM on very large source images
|
||||
val maxWidth = width * 2
|
||||
val maxHeight = height * 2
|
||||
if (srcWidth > maxWidth || srcHeight > maxHeight) {
|
||||
val scale = minOf(maxWidth.toFloat() / srcWidth, maxHeight.toFloat() / srcHeight)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
} else {
|
||||
Pair(srcWidth, srcHeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
decoder.setTargetSize(targetWidth, targetHeight)
|
||||
decoder.isMutableRequired = true
|
||||
// Use high quality when possible
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
}
|
||||
decodedWithImageDecoder = true
|
||||
result
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "ImageDecoder failed, falling back to BitmapFactory: $e")
|
||||
context.contentResolver.openInputStream(wallpaperUri)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
try {
|
||||
context.contentResolver.openInputStream(wallpaperUri)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM during BitmapFactory fallback for $wallpaperUri: $e")
|
||||
null
|
||||
}
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM during retrieveBitmap for $wallpaperUri: $e")
|
||||
null
|
||||
}
|
||||
|
||||
// Handle EXIF orientation
|
||||
return bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
|
||||
// Only apply EXIF orientation for the BitmapFactory path — ImageDecoder already handles it
|
||||
return if (decodedWithImageDecoder) bitmap else bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,7 +300,7 @@ fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "darkenBitmap received an immutable bitmap. Creating a mutable copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle()
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return darkenBitmap(mutableCopy, darkenPercent)
|
||||
}
|
||||
|
||||
@@ -295,6 +314,7 @@ fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(targetBrightnessFactor, targetBrightnessFactor, targetBrightnessFactor, 1f)
|
||||
})
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
@@ -328,7 +348,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
renderNode.setPosition(0, 0, source.width, source.height)
|
||||
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.MIRROR)
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP)
|
||||
renderNode.setRenderEffect(blurEffect)
|
||||
|
||||
val canvas = renderNode.beginRecording()
|
||||
@@ -342,20 +362,26 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
val image = imageReader.acquireNextImage()
|
||||
?: throw IllegalStateException("Failed to acquire blurred image")
|
||||
|
||||
val hardwareBuffer = image.hardwareBuffer
|
||||
?: throw IllegalStateException("Failed to acquire hardware buffer")
|
||||
try {
|
||||
val hardwareBuffer = image.hardwareBuffer
|
||||
?: throw IllegalStateException("Failed to acquire hardware buffer")
|
||||
|
||||
val hardwareBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
|
||||
?: throw IllegalStateException("Failed to create bitmap from hardware buffer")
|
||||
try {
|
||||
val hardwareBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
|
||||
?: throw IllegalStateException("Failed to create bitmap from hardware buffer")
|
||||
|
||||
// Convert hardware bitmap to regular bitmap for further processing
|
||||
// Use mutable=true to allow subsequent effects to modify in-place
|
||||
resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, true)
|
||||
?: throw IllegalStateException("Failed to copy hardware bitmap to software bitmap")
|
||||
// Convert hardware bitmap to regular bitmap for further processing
|
||||
// Use mutable=true to allow subsequent effects to modify in-place
|
||||
resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, true)
|
||||
?: throw IllegalStateException("Failed to copy hardware bitmap to software bitmap")
|
||||
|
||||
hardwareBitmap.recycle()
|
||||
hardwareBuffer.close()
|
||||
image.close()
|
||||
hardwareBitmap.recycle()
|
||||
} finally {
|
||||
hardwareBuffer.close()
|
||||
}
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error blurring bitmap: $e")
|
||||
@@ -388,14 +414,17 @@ fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "vignetteBitmap received an immutable bitmap. Creating a mutable copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle()
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return vignetteBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
return try {
|
||||
val canvas = Canvas(source)
|
||||
val dim = if (source.width < source.height) source.height else source.width
|
||||
val rad = (dim * (1 - (percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))).coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
|
||||
// Use corner-to-center diagonal so the vignette darkens uniformly in all directions
|
||||
val halfW = source.width / 2f
|
||||
val halfH = source.height / 2f
|
||||
val diagonal = kotlin.math.sqrt(halfW * halfW + halfH * halfH)
|
||||
val rad = (diagonal * (1 - (percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))).coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
|
||||
val centerX = source.width / 2f
|
||||
val centerY = source.height / 2f
|
||||
|
||||
@@ -432,7 +461,7 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "grayscaleBitmap received an immutable bitmap. Creating a mutable copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle()
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return grayscaleBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
@@ -440,7 +469,10 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (factor <= 0f) return source
|
||||
|
||||
val colorMatrix = ColorMatrix().apply { setSaturation(1 - factor) }
|
||||
val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(colorMatrix) }
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(colorMatrix)
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
@@ -463,7 +495,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "adjustBitmapBrightness received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle() // Recycle source to prevent memory leak
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return adjustBitmapBrightness(mutableCopy, brightnessFactor)
|
||||
}
|
||||
|
||||
@@ -471,6 +503,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(brightnessFactor, brightnessFactor, brightnessFactor, 1f)
|
||||
})
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
|
||||
@@ -45,7 +45,7 @@ class PreferencesManager @Inject constructor(
|
||||
suspend fun getAppSettings(): AppSettings {
|
||||
val prefs = dataStore.data.first()
|
||||
return AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)],
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: false,
|
||||
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
|
||||
@@ -56,7 +56,7 @@ class PreferencesManager @Inject constructor(
|
||||
|
||||
fun getAppSettingsFlow(): Flow<AppSettings> = dataStore.data.map { prefs ->
|
||||
AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)],
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: false,
|
||||
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
|
||||
@@ -67,7 +67,11 @@ class PreferencesManager @Inject constructor(
|
||||
|
||||
suspend fun updateAppSettings(settings: AppSettings) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = settings.darkMode ?: false
|
||||
if (settings.darkMode != null) {
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = settings.darkMode
|
||||
} else {
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.DARK_MODE))
|
||||
}
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = settings.dynamicTheming
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = settings.animate
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = settings.firstLaunch
|
||||
|
||||
@@ -121,8 +121,6 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
val batchSize = 100 // Process in smaller batches to avoid memory spikes
|
||||
var offset = 0
|
||||
|
||||
// Use while loop to handle deletions correctly
|
||||
// When items are deleted, we don't advance offset since indices shift
|
||||
while (true) {
|
||||
val wallpapers = wallpaperDao.getWallpapersByAlbumPaged(albumId, batchSize, offset)
|
||||
if (wallpapers.isEmpty()) break
|
||||
@@ -130,13 +128,15 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
val invalidUris = wallpapers
|
||||
.filter { !it.uri.toUri().isValid(contentResolver) }
|
||||
.map { it.uri }
|
||||
.toSet()
|
||||
|
||||
if (invalidUris.isNotEmpty()) {
|
||||
wallpaperDao.deleteWallpapersByUris(invalidUris)
|
||||
wallpaperDao.deleteWallpapersByUris(invalidUris.toList())
|
||||
totalRemoved += invalidUris.size
|
||||
// Don't advance offset when deleting - remaining items shift down
|
||||
// Advance offset only by the number of valid items in this batch,
|
||||
// so valid items already checked are not re-fetched next iteration
|
||||
offset += wallpapers.size - invalidUris.size
|
||||
} else {
|
||||
// Only advance offset if no deletions (all items in batch were valid)
|
||||
offset += batchSize
|
||||
}
|
||||
}
|
||||
@@ -229,12 +229,12 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
|
||||
override suspend fun normalizeAllQueuesForAlbum(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
// Normalize all queue types for this album
|
||||
// Normalize queue positions for each active screen type
|
||||
// This fixes gaps in queue positions caused by CASCADE deletes
|
||||
// Note: BOTH queue is intentionally excluded — it is never populated or consumed
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.HOME)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LOCK)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LIVE)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.BOTH)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
|
||||
@@ -140,10 +140,14 @@ class ChangeWallpaperUseCase @Inject constructor(
|
||||
return Result.Error(NoValidWallpaperException(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
}
|
||||
|
||||
// Check if queue needs refilling
|
||||
val nextItem = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
|
||||
if (nextItem == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
// Best-effort queue refill — do not propagate failure, the bitmap is already ready
|
||||
try {
|
||||
val nextItem = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
|
||||
if (nextItem == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.w("ChangeWallpaperUseCase", "Queue refill failed, will rebuild on next change", e)
|
||||
}
|
||||
|
||||
Result.Success(finalBitmap)
|
||||
|
||||
+12
-11
@@ -82,6 +82,7 @@ class AlbumViewViewModel @Inject constructor(
|
||||
|
||||
fun addWallpapers(uris: List<String>) {
|
||||
viewModelScope.launch {
|
||||
val existingCount = wallpapers.value.size
|
||||
val wallpapers = uris.mapIndexed { index, uri ->
|
||||
val parsedUri = uri.toUri()
|
||||
val mediaType = parsedUri.detectMediaType(context) ?: WallpaperMediaType.IMAGE
|
||||
@@ -93,7 +94,7 @@ class AlbumViewViewModel @Inject constructor(
|
||||
uri = uri,
|
||||
fileName = parsedUri.getFileName(context) ?: uri.substringAfterLast('/'),
|
||||
dateModified = System.currentTimeMillis(),
|
||||
displayOrder = index,
|
||||
displayOrder = existingCount + index,
|
||||
mediaType = mediaType
|
||||
)
|
||||
}
|
||||
@@ -138,7 +139,7 @@ class AlbumViewViewModel @Inject constructor(
|
||||
name = uri.toUri().getFileName(context) ?: uri.substringAfterLast('/'),
|
||||
coverUri = wallpapers.firstOrNull()?.uri, // Use first image as cover
|
||||
dateModified = System.currentTimeMillis(),
|
||||
displayOrder = 0,
|
||||
displayOrder = folders.value.size,
|
||||
wallpapers = wallpapers
|
||||
)
|
||||
|
||||
@@ -199,13 +200,14 @@ class AlbumViewViewModel @Inject constructor(
|
||||
viewModelScope.launch {
|
||||
val wallpaperIds = _selectedWallpapers.value.toList()
|
||||
val folderIds = _selectedFolders.value.toList()
|
||||
var hasError = false
|
||||
|
||||
// Batch delete wallpapers from album (includes timestamp update and cover refresh)
|
||||
if (wallpaperIds.isNotEmpty()) {
|
||||
when (albumRepository.removeWallpapersFromAlbum(albumId, wallpaperIds)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> hasError = true
|
||||
is com.anthonyla.paperize.core.Result.Success -> {
|
||||
_selectedWallpapers.value = _selectedWallpapers.value - wallpaperIds.toSet()
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Leave failed items selected */ }
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
@@ -214,17 +216,16 @@ class AlbumViewViewModel @Inject constructor(
|
||||
if (folderIds.isNotEmpty()) {
|
||||
folderIds.forEach { folderId ->
|
||||
when (albumRepository.removeFolderFromAlbum(albumId, folderId)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> hasError = true
|
||||
is com.anthonyla.paperize.core.Result.Success -> {
|
||||
_selectedFolders.value = _selectedFolders.value - folderId
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Leave failed item selected */ }
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only clear selection if all operations succeeded
|
||||
if (!hasError) {
|
||||
clearSelection()
|
||||
}
|
||||
updateSelectionMode()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+24
-18
@@ -48,9 +48,9 @@ class SortViewModel @Inject constructor(
|
||||
private fun loadAlbumData() {
|
||||
viewModelScope.launch {
|
||||
val album = albumRepository.getAlbumById(albumId).first()
|
||||
val wallpapers = wallpaperRepository.getWallpapersByAlbum(albumId).first()
|
||||
val wallpapers = wallpaperRepository.getDirectWallpapersByAlbum(albumId).first()
|
||||
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = album?.folders ?: emptyList(),
|
||||
wallpapers = wallpapers
|
||||
)
|
||||
@@ -62,7 +62,7 @@ class SortViewModel @Inject constructor(
|
||||
var hasError = false
|
||||
|
||||
// Update folders with new display orders
|
||||
state.value.folders.forEach { folder ->
|
||||
_state.value.folders.forEach { folder ->
|
||||
when (val result = albumRepository.updateFolder(folder)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
@@ -74,7 +74,7 @@ class SortViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
// Update wallpapers with new display orders
|
||||
state.value.wallpapers.forEach { wallpaper ->
|
||||
_state.value.wallpapers.forEach { wallpaper ->
|
||||
when (val result = wallpaperRepository.updateWallpaper(wallpaper)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
@@ -96,38 +96,44 @@ class SortViewModel @Inject constructor(
|
||||
fun onEvent(event: SortEvent) {
|
||||
when (event) {
|
||||
is SortEvent.LoadSortView -> {
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = event.folders,
|
||||
wallpapers = event.wallpapers
|
||||
)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftFolder -> {
|
||||
val fromUri = event.from.key as? String ?: return
|
||||
val toUri = event.to.key as? String ?: return
|
||||
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
|
||||
fromUri = fromUri,
|
||||
toUri = toUri
|
||||
)
|
||||
_state.value = state.value.copy(folders = updatedFolders)
|
||||
_state.value = _state.value.copy(folders = updatedFolders)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftFolderWallpaper -> {
|
||||
val fromUri = event.from.key as? String ?: return
|
||||
val toUri = event.to.key as? String ?: return
|
||||
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
|
||||
fromUri = fromUri,
|
||||
toUri = toUri
|
||||
)
|
||||
_state.value = state.value.copy(folders = updatedFolders)
|
||||
_state.value = _state.value.copy(folders = updatedFolders)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftWallpaper -> {
|
||||
val fromUri = event.from.key as? String ?: return
|
||||
val toUri = event.to.key as? String ?: return
|
||||
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
|
||||
fromUri = fromUri,
|
||||
toUri = toUri
|
||||
)
|
||||
_state.value = state.value.copy(wallpapers = updatedWallpapers)
|
||||
_state.value = _state.value.copy(wallpapers = updatedWallpapers)
|
||||
}
|
||||
|
||||
is SortEvent.Reset -> {
|
||||
@@ -140,7 +146,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = true
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
@@ -152,7 +158,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = false
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
@@ -164,7 +170,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = true
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
@@ -176,7 +182,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = false
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
|
||||
+1
-1
@@ -221,7 +221,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
|
||||
try {
|
||||
val uri = wallpaper.uri.toUri()
|
||||
ContentUriImageLoader(contentResolver, uri)
|
||||
ContentUriImageLoader(contentResolver, uri, settings.liveScalingType)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error creating image loader", e)
|
||||
EmptyImageLoader
|
||||
|
||||
@@ -139,7 +139,8 @@ class GLPicture(
|
||||
|
||||
// Draw each tile using pre-allocated buffers (no per-frame allocation)
|
||||
for (tile in tiles) {
|
||||
// Bind texture
|
||||
// Bind texture to unit 0 (must set active unit explicitly to avoid relying on GL state)
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tile.textureId)
|
||||
|
||||
// Use pre-allocated buffers - no allocation here!
|
||||
|
||||
+12
-10
@@ -4,6 +4,7 @@ import android.opengl.GLSurfaceView
|
||||
import android.service.wallpaper.WallpaperService
|
||||
import android.util.Log
|
||||
import android.view.SurfaceHolder
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import javax.microedition.khronos.egl.EGL10
|
||||
import javax.microedition.khronos.egl.EGLConfig
|
||||
import javax.microedition.khronos.egl.EGLContext
|
||||
@@ -149,7 +150,11 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
|
||||
@Volatile var renderMode = RENDERMODE_WHEN_DIRTY
|
||||
|
||||
private val eventQueue = mutableListOf<Runnable>()
|
||||
// LinkedBlockingQueue is thread-safe — no explicit synchronization needed.
|
||||
// Using a single lock for render signalling eliminates the previous AB-BA deadlock
|
||||
// where the GL thread held `lock` while acquiring `eventQueue`, and callers held
|
||||
// `eventQueue` while trying to acquire `lock` in requestRender().
|
||||
private val eventQueue = LinkedBlockingQueue<Runnable>()
|
||||
@Suppress("UseKotlinAny")
|
||||
private val lock = Object()
|
||||
|
||||
@@ -175,9 +180,7 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
}
|
||||
|
||||
fun queueEvent(runnable: Runnable) {
|
||||
synchronized(eventQueue) {
|
||||
eventQueue.add(runnable)
|
||||
}
|
||||
eventQueue.add(runnable)
|
||||
requestRender()
|
||||
}
|
||||
|
||||
@@ -232,12 +235,11 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
return
|
||||
}
|
||||
|
||||
// Process events
|
||||
synchronized(eventQueue) {
|
||||
if (eventQueue.isNotEmpty()) {
|
||||
event = eventQueue.removeAt(0)
|
||||
break
|
||||
}
|
||||
// Process events — LinkedBlockingQueue.poll() is non-blocking and thread-safe
|
||||
val polled = eventQueue.poll()
|
||||
if (polled != null) {
|
||||
event = polled
|
||||
break
|
||||
}
|
||||
|
||||
// Check if we should render
|
||||
|
||||
+55
-42
@@ -40,8 +40,9 @@ object GLShaders {
|
||||
|
||||
/**
|
||||
* Fragment shader for horizontal Gaussian blur pass.
|
||||
* Uses 9-tap kernel with branchless design for optimal GPU performance.
|
||||
* Weights are pre-computed for sigma ~= 2.0.
|
||||
* Uses 17-tap kernel (half-integer steps) to eliminate banding/ghosting at high blur radii.
|
||||
* Weights are pre-computed for sigma ~= 1.815 sampled at {0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4} steps.
|
||||
* Branchless: when blurRadius is 0, all offsets are 0 so all samples collapse to center.
|
||||
*/
|
||||
const val BLUR_HORIZONTAL_FRAGMENT_SHADER = """
|
||||
precision mediump float;
|
||||
@@ -52,23 +53,28 @@ object GLShaders {
|
||||
|
||||
void main() {
|
||||
vec2 pixelSize = 1.0 / u_resolution;
|
||||
|
||||
// Sample center pixel
|
||||
vec4 center = texture2D(u_texture, v_texCoord);
|
||||
|
||||
// 9-tap Gaussian blur (branchless - when radius is 0, offsets are 0)
|
||||
vec4 color = center * 0.2210;
|
||||
|
||||
// Symmetric pairs for efficiency
|
||||
float r = u_blurRadius;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-4.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 4.0 * pixelSize.x * r, 0.0))) * 0.0204;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-3.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 3.0 * pixelSize.x * r, 0.0))) * 0.0577;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-2.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 2.0 * pixelSize.x * r, 0.0))) * 0.1215;
|
||||
|
||||
// 17-tap Gaussian (half-integer steps: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0)
|
||||
// Doubles sampling density vs 9-tap to eliminate aliasing at high blur radii
|
||||
vec4 color = texture2D(u_texture, v_texCoord) * 0.1120;
|
||||
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-0.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 0.5 * pixelSize.x * r, 0.0))) * 0.1078;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-1.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 1.0 * pixelSize.x * r, 0.0))) * 0.1899;
|
||||
texture2D(u_texture, v_texCoord + vec2( 1.0 * pixelSize.x * r, 0.0))) * 0.0962;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-1.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 1.5 * pixelSize.x * r, 0.0))) * 0.0796;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-2.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 2.0 * pixelSize.x * r, 0.0))) * 0.0610;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-2.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 2.5 * pixelSize.x * r, 0.0))) * 0.0434;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-3.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 3.0 * pixelSize.x * r, 0.0))) * 0.0286;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-3.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 3.5 * pixelSize.x * r, 0.0))) * 0.0175;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-4.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 4.0 * pixelSize.x * r, 0.0))) * 0.0099;
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -76,7 +82,7 @@ object GLShaders {
|
||||
|
||||
/**
|
||||
* Fragment shader for vertical Gaussian blur pass.
|
||||
* Uses 9-tap kernel with branchless design matching horizontal pass.
|
||||
* Uses 17-tap kernel matching the horizontal pass.
|
||||
*/
|
||||
const val BLUR_VERTICAL_FRAGMENT_SHADER = """
|
||||
precision mediump float;
|
||||
@@ -87,23 +93,27 @@ object GLShaders {
|
||||
|
||||
void main() {
|
||||
vec2 pixelSize = 1.0 / u_resolution;
|
||||
|
||||
// Sample center pixel
|
||||
vec4 center = texture2D(u_texture, v_texCoord);
|
||||
|
||||
// 9-tap Gaussian blur (branchless - when radius is 0, offsets are 0)
|
||||
vec4 color = center * 0.2210;
|
||||
|
||||
// Symmetric pairs for efficiency
|
||||
float r = u_blurRadius;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -4.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 4.0 * pixelSize.y * r))) * 0.0204;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 3.0 * pixelSize.y * r))) * 0.0577;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 2.0 * pixelSize.y * r))) * 0.1215;
|
||||
|
||||
// 17-tap Gaussian (half-integer steps: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0)
|
||||
vec4 color = texture2D(u_texture, v_texCoord) * 0.1120;
|
||||
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -0.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 0.5 * pixelSize.y * r))) * 0.1078;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 1.0 * pixelSize.y * r))) * 0.1899;
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 1.0 * pixelSize.y * r))) * 0.0962;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 1.5 * pixelSize.y * r))) * 0.0796;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 2.0 * pixelSize.y * r))) * 0.0610;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 2.5 * pixelSize.y * r))) * 0.0434;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 3.0 * pixelSize.y * r))) * 0.0286;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 3.5 * pixelSize.y * r))) * 0.0175;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -4.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 4.0 * pixelSize.y * r))) * 0.0099;
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -129,15 +139,18 @@ object GLShaders {
|
||||
// 1. Apply darken (branchless - when factor is 0, multiplier is 1.0)
|
||||
color.rgb *= (1.0 - u_darkenFactor);
|
||||
|
||||
// 2. Apply vignette (branchless using mix)
|
||||
// When vignetteFactor is 0, the vignette calculation still runs but
|
||||
// the smoothstep result approaches 1.0 everywhere, so color is unchanged
|
||||
vec2 center = v_texCoord - 0.5;
|
||||
float dist = length(center);
|
||||
float vignette = 1.0 - smoothstep(0.3, 0.9, dist * (1.0 + u_vignetteFactor * 2.0));
|
||||
// Mix between original (1.0) and vignette based on factor
|
||||
float vignetteMultiplier = mix(1.0, vignette, u_vignetteFactor);
|
||||
color.rgb *= vignetteMultiplier;
|
||||
// 2. Apply vignette — matches CPU vignetteBitmap gradient stops:
|
||||
// [0% dark at center] → [10% dark at 70% of radius] → [80% dark at edge]
|
||||
// radius is normalized to 0.5 UV (image edge along shorter axis)
|
||||
vec2 vignetteCenter = v_texCoord - 0.5;
|
||||
float dist = length(vignetteCenter);
|
||||
float t = clamp(dist / 0.5, 0.0, 1.0);
|
||||
// Inner segment: 0% → 10% over [0, 0.7]
|
||||
float innerDark = smoothstep(0.0, 0.7, t) * 0.1;
|
||||
// Outer segment: 10% → 80% over [0.7, 1.0]
|
||||
float outerDark = smoothstep(0.7, 1.0, t) * 0.7;
|
||||
float darkAmount = innerDark + outerDark;
|
||||
color.rgb *= (1.0 - darkAmount * u_vignetteFactor);
|
||||
|
||||
// 3. Apply grayscale (branchless - mix handles factor 0 correctly)
|
||||
// ITU-R BT.709 standard luminance calculation
|
||||
|
||||
+45
-101
@@ -5,9 +5,10 @@ import android.graphics.Bitmap
|
||||
import android.graphics.ImageDecoder
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Sealed interface for loading images from different sources.
|
||||
@@ -41,10 +42,12 @@ object EmptyImageLoader : ImageLoader {
|
||||
*
|
||||
* @property contentResolver Content resolver for URI access
|
||||
* @property uri Content URI to load
|
||||
* @property scalingType How the image will be scaled for display
|
||||
*/
|
||||
class ContentUriImageLoader(
|
||||
private val contentResolver: ContentResolver,
|
||||
private val uri: Uri
|
||||
private val uri: Uri,
|
||||
private val scalingType: ScalingType = ScalingType.FILL
|
||||
) : ImageLoader {
|
||||
|
||||
companion object {
|
||||
@@ -54,38 +57,47 @@ class ContentUriImageLoader(
|
||||
override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
// First verify the URI is accessible
|
||||
val isAccessible = try {
|
||||
contentResolver.openInputStream(uri)?.use { true } ?: false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "URI not accessible: $uri", e)
|
||||
false
|
||||
}
|
||||
|
||||
if (!isAccessible) {
|
||||
Log.w(TAG, "Image not accessible or doesn't exist: $uri")
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
// Get image dimensions without loading pixel data
|
||||
val dimensions = getImageDimensions() ?: return@withContext null
|
||||
|
||||
// Calculate optimal sample size
|
||||
val sampleSize = calculateSampleSize(
|
||||
dimensions.first,
|
||||
dimensions.second,
|
||||
targetWidth,
|
||||
targetHeight
|
||||
)
|
||||
|
||||
Log.d(TAG, "Loading image: ${dimensions.first}x${dimensions.second} -> " +
|
||||
"${dimensions.first / sampleSize}x${dimensions.second / sampleSize} " +
|
||||
"(sample size: $sampleSize)")
|
||||
|
||||
// Load bitmap with sampling
|
||||
// ImageDecoder auto-applies EXIF orientation; info.size returns post-EXIF (display)
|
||||
// dimensions. Computing decodeWidth/decodeHeight inside the lambda from info.size
|
||||
// ensures correct aspect-ratio math regardless of EXIF rotation metadata.
|
||||
val source = ImageDecoder.createSource(contentResolver, uri)
|
||||
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
decoder.setTargetSampleSize(sampleSize)
|
||||
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||
val srcWidth = info.size.width
|
||||
val srcHeight = info.size.height
|
||||
|
||||
val (decodeWidth, decodeHeight) = when (scalingType) {
|
||||
ScalingType.FILL -> {
|
||||
val scale = maxOf(
|
||||
targetWidth.toFloat() / srcWidth,
|
||||
targetHeight.toFloat() / srcHeight
|
||||
)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
}
|
||||
ScalingType.FIT -> {
|
||||
val scale = minOf(
|
||||
targetWidth.toFloat() / srcWidth,
|
||||
targetHeight.toFloat() / srcHeight
|
||||
)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
}
|
||||
ScalingType.STRETCH -> Pair(targetWidth, targetHeight)
|
||||
ScalingType.NONE -> {
|
||||
// Cap at 2× screen size to prevent OOM on very large source images
|
||||
val maxW = targetWidth * 2
|
||||
val maxH = targetHeight * 2
|
||||
if (srcWidth > maxW || srcHeight > maxH) {
|
||||
val scale = minOf(maxW.toFloat() / srcWidth, maxH.toFloat() / srcHeight)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
} else {
|
||||
Pair(srcWidth, srcHeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "Loading image: ${srcWidth}x${srcHeight} -> ${decodeWidth}x${decodeHeight} " +
|
||||
"(scaling: $scalingType, target: ${targetWidth}x${targetHeight})")
|
||||
|
||||
decoder.setTargetSize(decodeWidth, decodeHeight)
|
||||
decoder.isMutableRequired = false // Immutable for GPU upload
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
}
|
||||
@@ -108,72 +120,4 @@ class ContentUriImageLoader(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get image dimensions without loading the full bitmap.
|
||||
* Uses BitmapFactory with inJustDecodeBounds to avoid allocating pixel data.
|
||||
*/
|
||||
private fun getImageDimensions(): Pair<Int, Int>? {
|
||||
return try {
|
||||
contentResolver.openInputStream(uri)?.use { inputStream ->
|
||||
val options = android.graphics.BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
android.graphics.BitmapFactory.decodeStream(inputStream, null, options)
|
||||
val width = options.outWidth
|
||||
val height = options.outHeight
|
||||
if (width > 0 && height > 0) Pair(width, height) else null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to get image dimensions for $uri", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the optimal sample size for downsampling.
|
||||
* Returns the largest power-of-2 sample size that still maintains
|
||||
* image dimensions larger than or equal to target dimensions.
|
||||
*
|
||||
* @param width Source image width
|
||||
* @param height Source image height
|
||||
* @param targetWidth Target width
|
||||
* @param targetHeight Target height
|
||||
* @return Sample size (power of 2)
|
||||
*/
|
||||
private fun calculateSampleSize(
|
||||
width: Int,
|
||||
height: Int,
|
||||
targetWidth: Int,
|
||||
targetHeight: Int
|
||||
): Int {
|
||||
// Guard against invalid target dimensions
|
||||
if (targetWidth <= 0 || targetHeight <= 0) {
|
||||
Log.w(TAG, "Invalid target dimensions: ${targetWidth}x${targetHeight}, using original size")
|
||||
return 1
|
||||
}
|
||||
|
||||
// Guard against invalid source dimensions
|
||||
if (width <= 0 || height <= 0) {
|
||||
Log.w(TAG, "Invalid source dimensions: ${width}x${height}")
|
||||
return 1
|
||||
}
|
||||
|
||||
var sampleSize = 1
|
||||
|
||||
if (width > targetWidth || height > targetHeight) {
|
||||
val halfWidth = width / 2
|
||||
val halfHeight = height / 2
|
||||
|
||||
// Calculate the largest sample size that is a power of 2 and keeps both
|
||||
// dimensions larger than the target dimensions
|
||||
while ((halfWidth / sampleSize) >= targetWidth &&
|
||||
(halfHeight / sampleSize) >= targetHeight) {
|
||||
sampleSize *= 2
|
||||
}
|
||||
}
|
||||
|
||||
// Return the calculated sample size (it is already the largest power-of-2
|
||||
// that keeps dimensions larger than or equal to target)
|
||||
return max(1, sampleSize)
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -634,7 +634,7 @@ class PaperizeWallpaperRenderer(
|
||||
* @return Pair of (width, height)
|
||||
*/
|
||||
private suspend fun waitForSurfaceDimensions(): Pair<Int, Int> {
|
||||
val maxWaitMs = Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS
|
||||
val maxWaitMs = Constants.SURFACE_WAIT_TIMEOUT_MS
|
||||
val pollIntervalMs = Constants.SURFACE_POLL_INTERVAL_MS
|
||||
var waitedMs = 0L
|
||||
|
||||
@@ -683,6 +683,7 @@ class PaperizeWallpaperRenderer(
|
||||
if (skipCrossfade) {
|
||||
// Instant swap - no animation (used for screen-off changes)
|
||||
currentPicture?.recycle()
|
||||
nextPicture?.recycle() // Recycle any in-flight crossfade target
|
||||
currentPicture = picture
|
||||
nextPicture = null
|
||||
crossfadeProgress = 0f
|
||||
@@ -690,6 +691,7 @@ class PaperizeWallpaperRenderer(
|
||||
Log.d(TAG, "Wallpaper instantly swapped (no crossfade): $picture")
|
||||
} else {
|
||||
// Start crossfade with time-based animation
|
||||
nextPicture?.recycle() // Recycle interrupted crossfade target if any
|
||||
nextPicture = picture
|
||||
crossfadeProgress = 0f
|
||||
crossfadeStartTimeNanos = System.nanoTime()
|
||||
|
||||
+34
-11
@@ -166,7 +166,7 @@ class WallpaperChangeService : Service() {
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
handleEmptyAlbumError()
|
||||
handleEmptyAlbumError(ScreenType.BOTH)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting wallpaper bitmap", error)
|
||||
}
|
||||
@@ -224,7 +224,7 @@ class WallpaperChangeService : Service() {
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
handleEmptyAlbumError()
|
||||
handleEmptyAlbumError(ScreenType.HOME)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting home wallpaper bitmap", error)
|
||||
}
|
||||
@@ -258,7 +258,7 @@ class WallpaperChangeService : Service() {
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
handleEmptyAlbumError()
|
||||
handleEmptyAlbumError(ScreenType.LOCK)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
|
||||
}
|
||||
@@ -277,7 +277,7 @@ class WallpaperChangeService : Service() {
|
||||
return NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(getString(R.string.changing_wallpaper))
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setSmallIcon(R.drawable.ic_launcher_monochrome)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
@@ -298,7 +298,7 @@ class WallpaperChangeService : Service() {
|
||||
val notification = NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(title)
|
||||
.setContentText(message)
|
||||
.setSmallIcon(R.mipmap.ic_launcher)
|
||||
.setSmallIcon(R.drawable.ic_launcher_monochrome)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
@@ -308,16 +308,39 @@ class WallpaperChangeService : Service() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle empty album error by showing notification and disabling wallpaper changer
|
||||
* Handle empty album error scoped to the specific screen that failed.
|
||||
* Only disables the changer globally if all active screens have empty albums.
|
||||
*/
|
||||
private suspend fun handleEmptyAlbumError() {
|
||||
Log.w(TAG, "Album is empty, disabling wallpaper changer")
|
||||
private suspend fun handleEmptyAlbumError(screenType: ScreenType) {
|
||||
Log.w(TAG, "Album is empty for $screenType")
|
||||
|
||||
// Disable wallpaper changer
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
settingsRepository.updateScheduleSettings(settings.copy(enableChanger = false))
|
||||
|
||||
// Show notification to user
|
||||
val updatedSettings = when (screenType) {
|
||||
ScreenType.HOME -> {
|
||||
// Disable home screen; only disable changer globally if lock is also inactive
|
||||
val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
enableChanger = if (lockStillActive) settings.enableChanger else false
|
||||
)
|
||||
}
|
||||
ScreenType.LOCK -> {
|
||||
// Disable lock screen; only disable changer globally if home is also inactive
|
||||
val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
settings.copy(
|
||||
lockAlbumId = null,
|
||||
enableChanger = if (homeStillActive) settings.enableChanger else false
|
||||
)
|
||||
}
|
||||
ScreenType.BOTH, ScreenType.LIVE -> {
|
||||
// Both screens or live — disable entirely
|
||||
settings.copy(enableChanger = false)
|
||||
}
|
||||
}
|
||||
|
||||
settingsRepository.updateScheduleSettings(updatedSettings)
|
||||
|
||||
showErrorNotification(
|
||||
getString(R.string.no_wallpapers_in_album),
|
||||
getString(R.string.wallpaper_changer_disabled_empty_album)
|
||||
|
||||
@@ -112,10 +112,10 @@ class AlbumRefreshWorker @AssistedInject constructor(
|
||||
}.forEach { it.await() }
|
||||
}
|
||||
|
||||
// Step 3: Normalize queues and refresh covers if new wallpapers were added
|
||||
// Step 3: Clear and rebuild queues and refresh covers if new wallpapers were added
|
||||
if (albumHasNewWallpapers.get()) {
|
||||
// Normalize queues so new wallpapers appear in rotation
|
||||
wallpaperRepository.normalizeAllQueuesForAlbum(album.id)
|
||||
// Clear queues so they are rebuilt on next change, including new wallpapers
|
||||
wallpaperRepository.clearQueuesForAlbum(album.id)
|
||||
when (albumRepository.refreshFolderCovers(album.id)) {
|
||||
is CoreResult.Success -> {
|
||||
Log.d(TAG, "Album '${album.name}': folder covers refreshed")
|
||||
|
||||
@@ -95,8 +95,8 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
ScreenType.BOTH -> {
|
||||
// Synchronized mode: set both screens to the same wallpaper
|
||||
// This ensures both HOME and LOCK show identical wallpapers
|
||||
// Use home album, fallback to lock album (they should be the same when synced)
|
||||
val albumId = settings.homeAlbumId ?: settings.lockAlbumId
|
||||
// Both screens must use the same album in sync mode
|
||||
val albumId = settings.homeAlbumId
|
||||
|
||||
if (albumId != null) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
|
||||
@@ -126,12 +126,12 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Both screens wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting wallpaper for both screens", e)
|
||||
throw e
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.e(TAG, "Error getting wallpaper bitmap for both screens", error)
|
||||
@@ -165,13 +165,12 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
|
||||
// Recycle bitmap after setting to free memory
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Home wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting home wallpaper", e)
|
||||
throw e
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.e(TAG, "Error getting home wallpaper bitmap", error)
|
||||
@@ -200,13 +199,12 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
|
||||
// Recycle bitmap after setting to free memory
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Lock wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper", e)
|
||||
throw e
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
|
||||
|
||||
Reference in new issue
Block a user