fix: harden wallpaper updates for v4.0.1 (#566)
This commit is contained in:
1 parent
145899d9a6
commit
797a407f3c
25 files changed
+1532
-940
No files matched your search
@@ -32,8 +32,8 @@ android {
|
||||
applicationId = "com.anthonyla.paperize"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 51
|
||||
versionName = "4.0.0"
|
||||
versionCode = 52
|
||||
versionName = "4.0.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
@@ -84,6 +84,7 @@ kotlin {
|
||||
dependencies {
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.process)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.ui)
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import java.io.File
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class WallpaperUtilInstrumentedTest {
|
||||
|
||||
private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
private val files = mutableListOf<File>()
|
||||
|
||||
@After
|
||||
fun cleanUp() {
|
||||
files.forEach(File::delete)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun imageDecoderAppliesExifRotation() {
|
||||
val image = createJpeg(width = 40, height = 20)
|
||||
ExifInterface(image).apply {
|
||||
setAttribute(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_ROTATE_90.toString()
|
||||
)
|
||||
saveAttributes()
|
||||
}
|
||||
|
||||
val result = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 20,
|
||||
height = 40,
|
||||
scaling = ScalingType.STRETCH
|
||||
)
|
||||
|
||||
assertNotNull(result)
|
||||
assertEquals(20, result?.width)
|
||||
assertEquals(40, result?.height)
|
||||
result?.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticFillRetainsWideSourceOverflow() {
|
||||
val image = createJpeg(width = 400, height = 200)
|
||||
|
||||
val scrolling = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 100,
|
||||
height = 200,
|
||||
scaling = ScalingType.FILL,
|
||||
preserveSourceOverflow = true
|
||||
)
|
||||
val exactCanvas = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 100,
|
||||
height = 200,
|
||||
scaling = ScalingType.FILL,
|
||||
preserveSourceOverflow = false
|
||||
)
|
||||
|
||||
assertEquals(400, scrolling?.width)
|
||||
assertEquals(200, scrolling?.height)
|
||||
assertEquals(100, exactCanvas?.width)
|
||||
assertEquals(200, exactCanvas?.height)
|
||||
scrolling?.recycle()
|
||||
exactCanvas?.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun android17FoldableSizingIncludesInactiveBuiltInPanel() {
|
||||
assumeTrue(Build.VERSION.SDK_INT >= 37)
|
||||
val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
val builtInDisplays = displayManager.getDisplays(
|
||||
"android.hardware.display.category.BUILT_IN_DISPLAYS"
|
||||
)
|
||||
assertTrue("Expected both foldable panels", builtInDisplays.size >= 2)
|
||||
|
||||
val expected = selectLargestDisplayDimensions(
|
||||
builtInDisplays.flatMap { display ->
|
||||
display.supportedModes.map { mode ->
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
}
|
||||
)
|
||||
val actual = ScreenMetricsCompat.getScreenSize(context)
|
||||
|
||||
assertNotNull(expected)
|
||||
assertEquals(expected?.first, actual.width)
|
||||
assertEquals(expected?.second, actual.height)
|
||||
}
|
||||
|
||||
private fun createJpeg(width: Int, height: Int): File {
|
||||
val file = File.createTempFile("paperize-test-", ".jpg", context.cacheDir)
|
||||
files += file
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
bitmap.eraseColor(Color.MAGENTA)
|
||||
file.outputStream().use { output ->
|
||||
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 95, output))
|
||||
}
|
||||
bitmap.recycle()
|
||||
return file
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,13 @@ import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import androidx.hilt.work.HiltWorkerFactory
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
import androidx.work.Configuration
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.service.worker.AlbumRefreshWorker
|
||||
import com.anthonyla.paperize.core.util.DataResetManager
|
||||
import com.anthonyla.paperize.service.worker.AlbumRefreshScheduler
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -23,13 +21,13 @@ import javax.inject.Inject
|
||||
* Implements Configuration.Provider for WorkManager with Hilt support
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class PaperizeApplication : Application(), Configuration.Provider {
|
||||
class PaperizeApplication : Application(), Configuration.Provider, DefaultLifecycleObserver {
|
||||
|
||||
@Inject
|
||||
lateinit var workerFactory: HiltWorkerFactory
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
super<Application>.onCreate()
|
||||
|
||||
// Perform one-time data reset for major version upgrades (e.g., v3 -> v4)
|
||||
// Must run before any other initialization that accesses DB/preferences
|
||||
@@ -38,8 +36,9 @@ class PaperizeApplication : Application(), Configuration.Provider {
|
||||
// Create notification channel (minSdk is 31, so always supported)
|
||||
createNotificationChannel()
|
||||
|
||||
// Trigger album refresh on app cold start to validate and update all albums
|
||||
refreshAlbumsOnStartup()
|
||||
// Process lifecycle distinguishes real background/foreground transitions from activity
|
||||
// recreation, so folder-backed albums are refreshed whenever the user returns to the app.
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||
}
|
||||
|
||||
override val workManagerConfiguration: Configuration
|
||||
@@ -61,31 +60,7 @@ class PaperizeApplication : Application(), Configuration.Provider {
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh all albums on app startup to validate and update wallpapers/folders
|
||||
*
|
||||
* This runs in the background without blocking app startup and ensures:
|
||||
* - Invalid wallpapers/folders are removed
|
||||
* - New wallpapers are discovered in existing folders
|
||||
* - Album covers are up-to-date
|
||||
*/
|
||||
private fun refreshAlbumsOnStartup() {
|
||||
val workManager = WorkManager.getInstance(this)
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
|
||||
.build()
|
||||
|
||||
val refreshWorkRequest = OneTimeWorkRequestBuilder<AlbumRefreshWorker>()
|
||||
.setConstraints(constraints)
|
||||
.addTag("startup_refresh")
|
||||
.build()
|
||||
|
||||
// Use KEEP policy to avoid duplicate refreshes if app is quickly reopened
|
||||
workManager.enqueueUniqueWork(
|
||||
"album_refresh_on_startup",
|
||||
ExistingWorkPolicy.KEEP,
|
||||
refreshWorkRequest
|
||||
)
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
AlbumRefreshScheduler.enqueue(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.graphics.Bitmap
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Apply a bitmap and treat WallpaperManager's documented zero return value as a failure.
|
||||
*/
|
||||
fun WallpaperManager.setBitmapChecked(bitmap: Bitmap, which: Int): Int {
|
||||
check(bitmap.width > 0 && bitmap.height > 0) {
|
||||
"Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}"
|
||||
}
|
||||
check(!bitmap.isRecycled) { "Bitmap has been recycled" }
|
||||
|
||||
val wallpaperId = setBitmap(bitmap, null, true, which)
|
||||
requireWallpaperSetSucceeded(wallpaperId)
|
||||
return wallpaperId
|
||||
}
|
||||
|
||||
internal fun requireWallpaperSetSucceeded(wallpaperId: Int) {
|
||||
if (wallpaperId == 0) {
|
||||
throw IOException("WallpaperManager rejected the wallpaper")
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.graphics.scale
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
@@ -47,6 +48,8 @@ import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
*/
|
||||
|
||||
private const val TAG = "WallpaperUtil"
|
||||
private const val BUILT_IN_DISPLAY_CATEGORY =
|
||||
"android.hardware.display.category.BUILT_IN_DISPLAYS"
|
||||
|
||||
/**
|
||||
* Get EXIF orientation from URI
|
||||
@@ -136,18 +139,30 @@ object ScreenMetricsCompat {
|
||||
// is still rendered sharply enough for the larger unfolded panel. External displays
|
||||
// are deliberately excluded so a connected monitor cannot inflate wallpaper memory.
|
||||
val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
displayManager?.displays
|
||||
?.asSequence()
|
||||
?.filter { display ->
|
||||
display.flags and Display.FLAG_PRESENTATION == 0 &&
|
||||
display.flags and Display.FLAG_PRIVATE == 0
|
||||
}
|
||||
?.flatMap { display ->
|
||||
val builtInDisplays = displayManager
|
||||
?.getDisplays(BUILT_IN_DISPLAY_CATEGORY)
|
||||
.orEmpty()
|
||||
val candidateDisplays = if (builtInDisplays.isNotEmpty()) {
|
||||
// Android 17+ returns all built-in panels, including currently inactive panels.
|
||||
builtInDisplays.asSequence()
|
||||
} else {
|
||||
// Compatibility fallback for releases where the built-in category is unknown.
|
||||
// Exclude presentation and app-owned virtual displays.
|
||||
displayManager?.displays
|
||||
?.asSequence()
|
||||
?.filter { display ->
|
||||
display.flags and Display.FLAG_PRESENTATION == 0 &&
|
||||
display.flags and Display.FLAG_PRIVATE == 0
|
||||
}
|
||||
.orEmpty()
|
||||
}
|
||||
candidateDisplays
|
||||
.flatMap { display ->
|
||||
display.supportedModes.asSequence().map { mode ->
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
}
|
||||
?.forEach(::add)
|
||||
.forEach(::add)
|
||||
}
|
||||
val largest = selectLargestDisplayDimensions(candidates)
|
||||
return largest?.let { Size(it.first, it.second) }
|
||||
@@ -188,25 +203,29 @@ fun getDeviceScreenSize(context: Context): Size {
|
||||
/**
|
||||
* Get the target render size for a wallpaper bitmap.
|
||||
*
|
||||
* For the HOME screen (and BOTH), the launcher may request a wider canvas than the physical
|
||||
* screen to support horizontal parallax scrolling across multiple home-screen pages (e.g.
|
||||
* Pixel Launcher with 3 pages requests ~3× screen width). If we render at physical-screen
|
||||
* width and pass a null visibleCropHint to WallpaperManager.setBitmap(), Android scales the
|
||||
* bitmap up to fill the launcher's desired width, which also enlarges the height and crops
|
||||
* the top/bottom — making "FIT" behave identically to "FILL" from the user's perspective.
|
||||
* For FIT/STRETCH/NONE on HOME (and BOTH), the launcher may request a wider canvas than the
|
||||
* physical screen to support horizontal scrolling across multiple pages. Rendering those modes
|
||||
* to the exact desired canvas prevents WallpaperManager from rescaling them into FILL.
|
||||
*
|
||||
* Fix: use WallpaperManager.getDesiredMinimumWidth/Height as the render target for HOME/BOTH
|
||||
* so the bitmap already fills the full parallax canvas. The launcher then has nothing to scale,
|
||||
* and the chosen scaling mode (FIT, FILL, STRETCH, NONE) is preserved correctly.
|
||||
* FILL deliberately uses one physical screen as its minimum viewport and keeps source overflow.
|
||||
* That restores Android's native static-wallpaper behavior: the launcher can traverse a wide
|
||||
* image, but cannot manufacture scroll area beyond the image's real edge.
|
||||
*
|
||||
* LOCK screen wallpapers are not parallax-scrolled, so the physical screen size is correct.
|
||||
* LIVE wallpapers are rendered by GLRenderer directly; they do not go through this path.
|
||||
*/
|
||||
fun getWallpaperRenderSize(context: Context, screenType: com.anthonyla.paperize.core.ScreenType): Size {
|
||||
fun getWallpaperRenderSize(
|
||||
context: Context,
|
||||
screenType: com.anthonyla.paperize.core.ScreenType,
|
||||
scaling: ScalingType = ScalingType.FIT
|
||||
): Size {
|
||||
val screen = getDeviceScreenSize(context)
|
||||
return when (screenType) {
|
||||
com.anthonyla.paperize.core.ScreenType.HOME,
|
||||
com.anthonyla.paperize.core.ScreenType.BOTH -> {
|
||||
if (usesLauncherManagedScrolling(screenType, scaling)) {
|
||||
return screen
|
||||
}
|
||||
val wm = WallpaperManager.getInstance(context)
|
||||
val desiredW = wm.desiredMinimumWidth
|
||||
val desiredH = wm.desiredMinimumHeight
|
||||
@@ -222,6 +241,19 @@ fun getWallpaperRenderSize(context: Context, screenType: com.anthonyla.paperize.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a static wallpaper should retain source overflow for launcher-managed scrolling.
|
||||
*
|
||||
* FIT/STRETCH/NONE use an exact launcher canvas so Android cannot rescale them into FILL.
|
||||
*/
|
||||
internal fun usesLauncherManagedScrolling(
|
||||
screenType: com.anthonyla.paperize.core.ScreenType,
|
||||
scaling: ScalingType
|
||||
): Boolean =
|
||||
(screenType == com.anthonyla.paperize.core.ScreenType.HOME ||
|
||||
screenType == com.anthonyla.paperize.core.ScreenType.BOTH) &&
|
||||
scaling == ScalingType.FILL
|
||||
|
||||
/**
|
||||
* Retrieve a bitmap from a URI that is scaled down to the device's screen size.
|
||||
*
|
||||
@@ -235,7 +267,8 @@ fun retrieveBitmap(
|
||||
wallpaperUri: Uri,
|
||||
width: Int,
|
||||
height: Int,
|
||||
scaling: ScalingType = ScalingType.FIT
|
||||
scaling: ScalingType = ScalingType.FIT,
|
||||
preserveSourceOverflow: Boolean = false
|
||||
): Bitmap? {
|
||||
// ImageDecoder auto-applies EXIF orientation; info.size is the post-EXIF display size.
|
||||
// No separate getImageDimensions() call needed — saves 1-2 stream opens per wallpaper.
|
||||
@@ -255,7 +288,7 @@ fun retrieveBitmap(
|
||||
val targetW = (srcWidth * scale).fastRoundToInt()
|
||||
val targetH = (srcHeight * scale).fastRoundToInt()
|
||||
decoder.setTargetSize(targetW, targetH)
|
||||
if (targetW > width || targetH > height) {
|
||||
if (!preserveSourceOverflow && (targetW > width || targetH > height)) {
|
||||
val cropX = ((targetW - width) / 2).coerceAtLeast(0)
|
||||
val cropY = ((targetH - height) / 2).coerceAtLeast(0)
|
||||
decoder.setCrop(android.graphics.Rect(
|
||||
@@ -327,7 +360,37 @@ fun retrieveBitmap(
|
||||
// FIT → decoded bitmap may be narrower/shorter than canvas; center on black canvas.
|
||||
// NONE → original-size image may be smaller than canvas; center on black canvas.
|
||||
// STRETCH → decoder was told the exact canvas size; no-op.
|
||||
return oriented?.let { finalizeToCanvas(it, width, height, scaling) }
|
||||
return oriented?.let {
|
||||
if (preserveSourceOverflow && scaling == ScalingType.FILL) {
|
||||
scaleToFillPreservingOverflow(it, width, height)
|
||||
} else {
|
||||
finalizeToCanvas(it, width, height, scaling)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale [source] just enough to cover one screen while retaining any overflow.
|
||||
*
|
||||
* The returned bitmap may be wider than [width] or taller than [height]. That overflow is what a
|
||||
* launcher uses to scroll a static wallpaper without moving past the source image's real edge.
|
||||
*/
|
||||
private fun scaleToFillPreservingOverflow(
|
||||
source: Bitmap,
|
||||
width: Int,
|
||||
height: Int
|
||||
): Bitmap {
|
||||
val scale = maxOf(
|
||||
width.toFloat() / source.width,
|
||||
height.toFloat() / source.height
|
||||
)
|
||||
val targetW = (source.width * scale).fastRoundToInt()
|
||||
val targetH = (source.height * scale).fastRoundToInt()
|
||||
if (targetW == source.width && targetH == source.height) return source
|
||||
|
||||
val scaled = source.scale(targetW, targetH)
|
||||
if (scaled !== source) source.recycle()
|
||||
return scaled
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -68,6 +68,35 @@ interface WallpaperQueueDao {
|
||||
""")
|
||||
suspend fun deleteQueueItem(albumId: String, screenType: ScreenType, wallpaperId: String)
|
||||
|
||||
@Query("""
|
||||
SELECT MIN(queuePosition) FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
""")
|
||||
suspend fun getFirstQueuePosition(albumId: String, screenType: ScreenType): Int?
|
||||
|
||||
/**
|
||||
* Restore a dequeued wallpaper to the front after the platform rejected the change.
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun restoreQueueItem(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
deleteQueueItem(albumId, screenType, wallpaperId)
|
||||
val firstPosition = getFirstQueuePosition(albumId, screenType) ?: 0
|
||||
insertQueueItems(
|
||||
listOf(
|
||||
WallpaperQueueEntity(
|
||||
albumId = albumId,
|
||||
wallpaperId = wallpaperId,
|
||||
screenType = screenType,
|
||||
queuePosition = firstPosition - 1
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear queue for album and screen type
|
||||
*/
|
||||
|
||||
@@ -154,6 +154,22 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
override suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getAndDequeueWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun removeWallpaperFromQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
wallpaperQueueDao.deleteQueueItem(albumId, screenType, wallpaperId)
|
||||
}
|
||||
|
||||
override suspend fun restoreWallpaperToQueueFront(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
wallpaperQueueDao.restoreQueueItem(albumId, screenType, wallpaperId)
|
||||
}
|
||||
|
||||
override suspend fun buildWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/**
|
||||
* A decoded and processed wallpaper that has not yet been committed as current.
|
||||
*
|
||||
* The queue item is only committed after WallpaperManager confirms that the platform accepted
|
||||
* the bitmap. If applying fails, callers restore this item to the front of its queue.
|
||||
*/
|
||||
data class PreparedWallpaper(
|
||||
val bitmap: Bitmap,
|
||||
val albumId: String,
|
||||
val screenType: ScreenType,
|
||||
val wallpaperId: String,
|
||||
val shuffle: Boolean
|
||||
)
|
||||
@@ -76,6 +76,24 @@ interface WallpaperRepository {
|
||||
*/
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
/**
|
||||
* Remove a specific wallpaper from a screen queue.
|
||||
*/
|
||||
suspend fun removeWallpaperFromQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Restore a prepared wallpaper to the front when applying it did not succeed.
|
||||
*/
|
||||
suspend fun restoreWallpaperToQueueFront(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Build wallpaper queue for album
|
||||
*/
|
||||
|
||||
+158
-97
@@ -2,62 +2,57 @@ package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.NoValidWallpaperException
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
|
||||
import com.anthonyla.paperize.core.util.getWallpaperRenderSize
|
||||
import com.anthonyla.paperize.core.util.processBitmap
|
||||
import com.anthonyla.paperize.core.util.retrieveBitmap
|
||||
import com.anthonyla.paperize.core.util.usesLauncherManagedScrolling
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Use case to change wallpaper
|
||||
* Prepares the next wallpaper without marking it as current.
|
||||
*
|
||||
* Handles the complete wallpaper changing flow:
|
||||
* 1. Atomically get and dequeue next wallpaper from queue
|
||||
* 2. Validate URI
|
||||
* 3. Load and process bitmap
|
||||
* 4. Apply effects
|
||||
* 5. Refill queue if needed
|
||||
* The queue item is dequeued while it is decoded, but callers must invoke [complete] only after
|
||||
* WallpaperManager confirms the bitmap was applied. If the platform rejects it, [restore] puts
|
||||
* the item back at the front of the queue.
|
||||
*/
|
||||
class ChangeWallpaperUseCase @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val settingsRepository: SettingsRepository
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String, screenType: ScreenType): Result<Bitmap> {
|
||||
suspend operator fun invoke(
|
||||
albumId: String,
|
||||
screenType: ScreenType
|
||||
): Result<PreparedWallpaper> {
|
||||
return try {
|
||||
// Get settings first - needed for queue building
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
|
||||
// Check if queue exists, build it if empty
|
||||
val queueCheck = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
|
||||
if (queueCheck == null) {
|
||||
// Queue is empty, build it first
|
||||
val buildResult = wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
if (wallpaperRepository.getNextWallpaperInQueue(albumId, screenType) == null) {
|
||||
val buildResult = wallpaperRepository.buildWallpaperQueue(
|
||||
albumId,
|
||||
screenType,
|
||||
settings.shuffleEnabled
|
||||
)
|
||||
if (buildResult is Result.Error) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_failed_to_build_queue)))
|
||||
return Result.Error(
|
||||
Exception(context.getString(R.string.error_failed_to_build_queue))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Atomically get and dequeue wallpaper, skipping invalid or corrupted ones
|
||||
var finalBitmap: Bitmap? = null
|
||||
var maxRetries = Constants.MAX_WALLPAPER_LOAD_RETRIES
|
||||
var queueRebuildAttempts = 0
|
||||
|
||||
// Get render dimensions once for the retry loop.
|
||||
// HOME/BOTH use the launcher's desired parallax canvas; LOCK uses physical screen.
|
||||
val screenSize = getWallpaperRenderSize(context, screenType)
|
||||
val effects = when (screenType) {
|
||||
ScreenType.LIVE -> settings.liveEffects
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
|
||||
@@ -68,101 +63,167 @@ class ChangeWallpaperUseCase @Inject constructor(
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
|
||||
ScreenType.LOCK -> settings.lockScalingType
|
||||
}
|
||||
val preserveSourceOverflow = usesLauncherManagedScrolling(screenType, scaling)
|
||||
val screenSize = getWallpaperRenderSize(context, screenType, scaling)
|
||||
|
||||
while (finalBitmap == null && maxRetries > 0) {
|
||||
var finalBitmap: Bitmap? = null
|
||||
var preparedWallpaperId: String? = null
|
||||
var remainingRetries = Constants.MAX_WALLPAPER_LOAD_RETRIES
|
||||
var queueRebuildAttempts = 0
|
||||
|
||||
while (finalBitmap == null && remainingRetries > 0) {
|
||||
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
|
||||
|
||||
if (candidate == null) {
|
||||
queueRebuildAttempts++
|
||||
if (queueRebuildAttempts > 2) {
|
||||
return Result.Error(EmptyAlbumException(context.getString(R.string.no_wallpapers_in_album)))
|
||||
if (queueRebuildAttempts > Constants.MAX_QUEUE_REBUILD_ATTEMPTS) {
|
||||
return Result.Error(
|
||||
EmptyAlbumException(context.getString(R.string.no_wallpapers_in_album))
|
||||
)
|
||||
}
|
||||
val rebuildResult = wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
val rebuildResult = wallpaperRepository.buildWallpaperQueue(
|
||||
albumId,
|
||||
screenType,
|
||||
settings.shuffleEnabled
|
||||
)
|
||||
if (rebuildResult is Result.Error) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_failed_to_build_queue)))
|
||||
return Result.Error(
|
||||
Exception(context.getString(R.string.error_failed_to_build_queue))
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
val uri = candidate.uri.toUri()
|
||||
// Skip the isValid() pre-check — retrieveBitmap returns null on failure,
|
||||
// which is handled below. Avoiding the extra contentResolver.query() saves
|
||||
// one round-trip per wallpaper on the hot path.
|
||||
try {
|
||||
val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling)
|
||||
if (bitmap != null) {
|
||||
var processedBitmap: Bitmap? = null
|
||||
try {
|
||||
processedBitmap = processBitmap(
|
||||
source = bitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
enableBlur = effects.enableBlur,
|
||||
blurPercent = effects.blurPercentage,
|
||||
enableVignette = effects.enableVignette,
|
||||
vignettePercent = effects.vignettePercentage,
|
||||
enableGrayscale = effects.enableGrayscale,
|
||||
grayscalePercent = effects.grayscalePercentage
|
||||
)
|
||||
val bitmap = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = candidate.uri.toUri(),
|
||||
width = screenSize.width,
|
||||
height = screenSize.height,
|
||||
scaling = scaling,
|
||||
preserveSourceOverflow = preserveSourceOverflow
|
||||
)
|
||||
if (bitmap == null) {
|
||||
// A temporarily inaccessible/corrupt item is skipped for this cycle.
|
||||
// AlbumRefreshWorker owns permanent pruning.
|
||||
remainingRetries--
|
||||
continue
|
||||
}
|
||||
|
||||
if (processedBitmap !== bitmap) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
var processedBitmap: Bitmap? = null
|
||||
try {
|
||||
processedBitmap = processBitmap(
|
||||
source = bitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
enableBlur = effects.enableBlur,
|
||||
blurPercent = effects.blurPercentage,
|
||||
enableVignette = effects.enableVignette,
|
||||
vignettePercent = effects.vignettePercentage,
|
||||
enableGrayscale = effects.enableGrayscale,
|
||||
grayscalePercent = effects.grayscalePercentage
|
||||
)
|
||||
|
||||
if (settings.adaptiveBrightness) {
|
||||
val previousBitmap = processedBitmap
|
||||
processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
|
||||
if (processedBitmap !== previousBitmap) {
|
||||
previousBitmap.recycle()
|
||||
}
|
||||
}
|
||||
if (processedBitmap !== bitmap) bitmap.recycle()
|
||||
|
||||
finalBitmap = processedBitmap
|
||||
|
||||
try {
|
||||
wallpaperRepository.setCurrentWallpaper(albumId, screenType, candidate.id)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.w("ChangeWallpaperUseCase", "Failed to record current wallpaper", e)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Recycle any bitmaps that were allocated before the exception
|
||||
if (processedBitmap != null && !processedBitmap.isRecycled) {
|
||||
processedBitmap.recycle()
|
||||
} else if (!bitmap.isRecycled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
throw e
|
||||
if (settings.adaptiveBrightness) {
|
||||
val previousBitmap = processedBitmap
|
||||
processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
|
||||
if (processedBitmap !== previousBitmap) previousBitmap.recycle()
|
||||
}
|
||||
} else {
|
||||
// null bitmap — file temporarily inaccessible; skip this cycle.
|
||||
// Do NOT delete the wallpaper permanently — a transient storage or
|
||||
// permission issue should not remove it from the user's album.
|
||||
// RefreshAlbumUseCase is responsible for pruning truly invalid URIs.
|
||||
maxRetries--
|
||||
|
||||
finalBitmap = processedBitmap
|
||||
preparedWallpaperId = candidate.id
|
||||
} catch (e: Exception) {
|
||||
if (processedBitmap != null && !processedBitmap.isRecycled) {
|
||||
processedBitmap.recycle()
|
||||
} else if (!bitmap.isRecycled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
throw e
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Error during bitmap processing; skip this wallpaper this cycle.
|
||||
maxRetries--
|
||||
remainingRetries--
|
||||
}
|
||||
}
|
||||
|
||||
if (finalBitmap == null) {
|
||||
return Result.Error(NoValidWallpaperException(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
}
|
||||
val preparedBitmap = finalBitmap
|
||||
?: return Result.Error(
|
||||
NoValidWallpaperException(
|
||||
context.getString(R.string.error_no_valid_wallpaper_after_retries)
|
||||
)
|
||||
)
|
||||
|
||||
// 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)
|
||||
Result.Success(
|
||||
PreparedWallpaper(
|
||||
bitmap = preparedBitmap,
|
||||
albumId = albumId,
|
||||
screenType = screenType,
|
||||
wallpaperId = checkNotNull(preparedWallpaperId),
|
||||
shuffle = settings.shuffleEnabled
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a successfully applied wallpaper and keep the target screen queue in sync.
|
||||
*
|
||||
* [screenType] can differ from the prepared queue when one HOME item was atomically applied to
|
||||
* both screens. The exact item is removed from LOCK rather than blindly dequeuing its head.
|
||||
*/
|
||||
suspend fun complete(
|
||||
prepared: PreparedWallpaper,
|
||||
screenType: ScreenType = prepared.screenType
|
||||
) {
|
||||
try {
|
||||
wallpaperRepository.setCurrentWallpaper(
|
||||
prepared.albumId,
|
||||
screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Applied wallpaper could not be recorded as current", e)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
if (wallpaperRepository.getNextWallpaperInQueue(prepared.albumId, screenType) == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(
|
||||
prepared.albumId,
|
||||
screenType,
|
||||
prepared.shuffle
|
||||
)
|
||||
}
|
||||
// Build first when this is the first synchronized use of a screen queue, then remove
|
||||
// the exact applied item. This prevents the just-applied wallpaper from being
|
||||
// reintroduced at the head of a freshly built queue.
|
||||
wallpaperRepository.removeWallpaperFromQueue(
|
||||
prepared.albumId,
|
||||
screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Queue sync failed; it will rebuild on the next change", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Restore a prepared item after WallpaperManager rejected it. */
|
||||
suspend fun restore(prepared: PreparedWallpaper) {
|
||||
try {
|
||||
wallpaperRepository.restoreWallpaperToQueueFront(
|
||||
prepared.albumId,
|
||||
prepared.screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to restore rejected wallpaper to its queue", e)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ChangeWallpaperUseCase"
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import com.anthonyla.paperize.core.util.getWallpaperRenderSize
|
||||
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.core.util.usesLauncherManagedScrolling
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
@@ -30,13 +31,18 @@ class ReapplyEffectsUseCase @Inject constructor(
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val settingsRepository: SettingsRepository
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String, screenType: ScreenType): Result<Bitmap> {
|
||||
suspend operator fun invoke(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String? = null
|
||||
): Result<Bitmap> {
|
||||
return try {
|
||||
val current = wallpaperRepository.getCurrentWallpaper(albumId, screenType)
|
||||
val current = wallpaperId
|
||||
?.let { wallpaperRepository.getWallpaperById(it) }
|
||||
?: wallpaperRepository.getCurrentWallpaper(albumId, screenType)
|
||||
?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
val screenSize = getWallpaperRenderSize(context, screenType)
|
||||
|
||||
val effects = when (screenType) {
|
||||
ScreenType.LIVE -> settings.liveEffects
|
||||
@@ -48,13 +54,22 @@ class ReapplyEffectsUseCase @Inject constructor(
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
|
||||
ScreenType.LOCK -> settings.lockScalingType
|
||||
}
|
||||
val preserveSourceOverflow = usesLauncherManagedScrolling(screenType, scaling)
|
||||
val screenSize = getWallpaperRenderSize(context, screenType, scaling)
|
||||
|
||||
val uri = current.uri.toUri()
|
||||
if (!uri.isValid(context.contentResolver)) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
}
|
||||
|
||||
val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling)
|
||||
val bitmap = retrieveBitmap(
|
||||
context,
|
||||
uri,
|
||||
screenSize.width,
|
||||
screenSize.height,
|
||||
scaling,
|
||||
preserveSourceOverflow
|
||||
)
|
||||
?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
|
||||
var processed: Bitmap? = null
|
||||
|
||||
+104
-12
@@ -727,9 +727,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.darkenPercentage else scheduleSettings.liveEffects.darkenPercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableDarken,
|
||||
lockChecked = scheduleSettings.lockEffects.enableDarken,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableDarken = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableDarken = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.darkenPercentage
|
||||
else scheduleSettings.lockEffects.darkenPercentage
|
||||
} else scheduleSettings.liveEffects.darkenPercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.darkenPercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -778,9 +801,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.blurPercentage else scheduleSettings.liveEffects.blurPercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableBlur,
|
||||
lockChecked = scheduleSettings.lockEffects.enableBlur,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableBlur = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableBlur = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.blurPercentage
|
||||
else scheduleSettings.lockEffects.blurPercentage
|
||||
} else scheduleSettings.liveEffects.blurPercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.blurPercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -829,9 +875,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.vignettePercentage else scheduleSettings.liveEffects.vignettePercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableVignette,
|
||||
lockChecked = scheduleSettings.lockEffects.enableVignette,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableVignette = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableVignette = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.vignettePercentage
|
||||
else scheduleSettings.lockEffects.vignettePercentage
|
||||
} else scheduleSettings.liveEffects.vignettePercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.vignettePercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -880,9 +949,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.grayscalePercentage else scheduleSettings.liveEffects.grayscalePercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableGrayscale,
|
||||
lockChecked = scheduleSettings.lockEffects.enableGrayscale,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableGrayscale = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableGrayscale = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.grayscalePercentage
|
||||
else scheduleSettings.lockEffects.grayscalePercentage
|
||||
} else scheduleSettings.liveEffects.grayscalePercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.grayscalePercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
|
||||
+157
-131
@@ -1,5 +1,4 @@
|
||||
package com.anthonyla.paperize.presentation.screens.wallpaper.components
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.animation.animateContentSize
|
||||
@@ -9,6 +8,8 @@ import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Switch
|
||||
@@ -25,12 +26,12 @@ import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Setting switch with percentage sliders for home and lock screens
|
||||
* Enhanced with Material 3 Expressive design
|
||||
* Effect control with either one switch/slider or independent HOME and LOCK controls.
|
||||
*/
|
||||
@Composable
|
||||
fun SettingSwitchWithSlider(
|
||||
@@ -42,17 +43,25 @@ fun SettingSwitchWithSlider(
|
||||
homePercentage: Int,
|
||||
lockPercentage: Int,
|
||||
onPercentageChange: (Int, Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
modifier: Modifier = Modifier,
|
||||
homeChecked: Boolean = checked,
|
||||
lockChecked: Boolean = checked,
|
||||
onHomeCheckedChange: (Boolean) -> Unit = onCheckedChange,
|
||||
onLockCheckedChange: (Boolean) -> Unit = onCheckedChange
|
||||
) {
|
||||
var homeValue by remember(homePercentage) { mutableFloatStateOf(homePercentage.toFloat()) }
|
||||
var lockValue by remember(lockPercentage) { mutableFloatStateOf(lockPercentage.toFloat()) }
|
||||
var homeValue by remember(homePercentage) {
|
||||
mutableFloatStateOf(homePercentage.toFloat())
|
||||
}
|
||||
var lockValue by remember(lockPercentage) {
|
||||
mutableFloatStateOf(lockPercentage.toFloat())
|
||||
}
|
||||
|
||||
androidx.compose.material3.Card(
|
||||
Card(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
colors = androidx.compose.material3.CardDefaults.cardColors(
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
|
||||
)
|
||||
) {
|
||||
@@ -62,145 +71,162 @@ fun SettingSwitchWithSlider(
|
||||
.padding(AppSpacing.large),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.large)
|
||||
) {
|
||||
// Header with title and switch
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.semantics(mergeDescendants = true) {},
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)
|
||||
) {
|
||||
if (bothEnabled) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)) {
|
||||
Text(
|
||||
text = stringResource(title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
if (!checked) {
|
||||
Text(
|
||||
text = stringResource(description),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
ScreenEffectControl(
|
||||
label = R.string.home,
|
||||
checked = homeChecked,
|
||||
onCheckedChange = onHomeCheckedChange,
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), lockValue.roundToInt())
|
||||
}
|
||||
)
|
||||
ScreenEffectControl(
|
||||
label = R.string.lock,
|
||||
checked = lockChecked,
|
||||
onCheckedChange = onLockCheckedChange,
|
||||
value = lockValue,
|
||||
onValueChange = {
|
||||
lockValue = it
|
||||
onPercentageChange(homeValue.roundToInt(), it.roundToInt())
|
||||
}
|
||||
)
|
||||
} else {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.semantics(mergeDescendants = true) {},
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(description),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
text = stringResource(title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
|
||||
// Sliders (shown when enabled)
|
||||
if (checked) {
|
||||
if (bothEnabled) {
|
||||
// Lock screen slider
|
||||
Column(modifier = Modifier.padding(horizontal = AppSpacing.small)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.lock),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${lockValue.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = lockValue,
|
||||
onValueChange = {
|
||||
lockValue = it
|
||||
onPercentageChange(homeValue.roundToInt(), it.roundToInt())
|
||||
},
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
|
||||
// Home screen slider
|
||||
Column(modifier = Modifier.padding(horizontal = AppSpacing.small)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.home),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${homeValue.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), lockValue.roundToInt())
|
||||
},
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Single slider (for whichever screen is enabled)
|
||||
Column(modifier = Modifier.padding(horizontal = AppSpacing.small)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
if (!checked) {
|
||||
Text(
|
||||
text = stringResource(description),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 2,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${homeValue.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = AppSpacing.medium)
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), it.roundToInt())
|
||||
},
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
|
||||
if (checked) {
|
||||
PercentageSlider(
|
||||
label = description,
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), it.roundToInt())
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenEffectControl(
|
||||
@StringRes label: Int,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = AppSpacing.small),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.small)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(label),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
if (checked) {
|
||||
PercentageSlider(
|
||||
label = label,
|
||||
value = value,
|
||||
onValueChange = onValueChange
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PercentageSlider(
|
||||
@StringRes label: Int,
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(label),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${value.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = AppSpacing.medium)
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..
|
||||
Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.renderer
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.FloatBuffer
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* Geometry utilities for OpenGL rendering including vertex positions,
|
||||
@@ -10,6 +13,66 @@ import java.nio.FloatBuffer
|
||||
*/
|
||||
object GLGeometry {
|
||||
|
||||
data class WallpaperTransform(
|
||||
val scaledWidth: Float,
|
||||
val scaledHeight: Float,
|
||||
val horizontalOffset: Float
|
||||
)
|
||||
|
||||
/**
|
||||
* Calculate live-wallpaper scale and launcher-scroll offset without OpenGL dependencies.
|
||||
*/
|
||||
fun calculateWallpaperTransform(
|
||||
viewWidth: Float,
|
||||
viewHeight: Float,
|
||||
imageWidth: Float,
|
||||
imageHeight: Float,
|
||||
scalingType: ScalingType,
|
||||
parallaxEnabled: Boolean,
|
||||
parallaxIntensity: Int,
|
||||
normalizedOffsetX: Float
|
||||
): WallpaperTransform {
|
||||
require(viewWidth > 0f && viewHeight > 0f)
|
||||
require(imageWidth > 0f && imageHeight > 0f)
|
||||
|
||||
val scaleX = viewWidth / imageWidth
|
||||
val scaleY = viewHeight / imageHeight
|
||||
val (baseScaleX, baseScaleY) = when (scalingType) {
|
||||
ScalingType.FILL -> max(scaleX, scaleY).let { it to it }
|
||||
ScalingType.FIT -> min(scaleX, scaleY).let { it to it }
|
||||
ScalingType.STRETCH -> scaleX to scaleY
|
||||
ScalingType.NONE -> 1f to 1f
|
||||
}
|
||||
|
||||
var effectiveScaleX = baseScaleX
|
||||
var effectiveScaleY = baseScaleY
|
||||
val intensity = if (parallaxEnabled) {
|
||||
parallaxIntensity.coerceIn(0, 100) / 100f
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
|
||||
if (intensity > 0f) {
|
||||
val currentWidth = imageWidth * effectiveScaleX
|
||||
val minimumExtraWidth = viewWidth * intensity * 0.2f
|
||||
if (currentWidth - viewWidth < minimumExtraWidth) {
|
||||
val zoom = (viewWidth + minimumExtraWidth) / currentWidth
|
||||
effectiveScaleX *= zoom
|
||||
effectiveScaleY *= zoom
|
||||
}
|
||||
}
|
||||
|
||||
val scaledWidth = imageWidth * effectiveScaleX
|
||||
val scaledHeight = imageHeight * effectiveScaleY
|
||||
val extraWidth = max(0f, scaledWidth - viewWidth)
|
||||
val offset = normalizedOffsetX.coerceIn(0f, 1f)
|
||||
return WallpaperTransform(
|
||||
scaledWidth = scaledWidth,
|
||||
scaledHeight = scaledHeight,
|
||||
horizontalOffset = extraWidth * intensity * (0.5f - offset)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-screen quad vertices in normalized device coordinates (-1 to 1).
|
||||
* Layout: x, y for each vertex (2 floats per vertex, 4 vertices).
|
||||
|
||||
+21
-65
@@ -347,67 +347,16 @@ class PaperizeWallpaperRenderer(
|
||||
return
|
||||
}
|
||||
|
||||
// 1. Calculate scale based on ScalingType
|
||||
val scaleX = viewWidth / imageWidth
|
||||
val scaleY = viewHeight / imageHeight
|
||||
|
||||
val (finalScaleX, finalScaleY) = when (currentScalingType) {
|
||||
ScalingType.FILL -> {
|
||||
val scale = kotlin.math.max(scaleX, scaleY)
|
||||
Pair(scale, scale)
|
||||
}
|
||||
ScalingType.FIT -> {
|
||||
val scale = kotlin.math.min(scaleX, scaleY)
|
||||
Pair(scale, scale)
|
||||
}
|
||||
ScalingType.STRETCH -> {
|
||||
Pair(scaleX, scaleY)
|
||||
}
|
||||
ScalingType.NONE -> {
|
||||
Pair(1f, 1f)
|
||||
}
|
||||
}
|
||||
|
||||
var effectiveScaleX = finalScaleX
|
||||
var effectiveScaleY = finalScaleY
|
||||
|
||||
val parallaxEnabled = currentEffects.enableParallax && currentEffects.parallaxIntensity > 0
|
||||
val parallaxIntensity = if (parallaxEnabled) currentEffects.parallaxIntensity / 100f else 0f
|
||||
|
||||
// If parallax is enabled, ensure we have enough width to scroll (overscan).
|
||||
// If image fits perfectly, apply artificial zoom based on intensity.
|
||||
if (parallaxEnabled) {
|
||||
val currentWidth = imageWidth * effectiveScaleX
|
||||
// Target at least 20% overscan at max intensity
|
||||
val minExtraWidth = viewWidth * parallaxIntensity * 0.2f
|
||||
|
||||
if ((currentWidth - viewWidth) < minExtraWidth) {
|
||||
// Zoom in to create scrollable area
|
||||
val targetWidth = viewWidth + minExtraWidth
|
||||
// Prevent division by zero
|
||||
if (currentWidth > 0) {
|
||||
val zoomFactor = targetWidth / currentWidth
|
||||
effectiveScaleX *= zoomFactor
|
||||
effectiveScaleY *= zoomFactor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val scaledWidth = imageWidth * effectiveScaleX
|
||||
val scaledHeight = imageHeight * effectiveScaleY
|
||||
|
||||
// 2. Calculate parallax offset
|
||||
// Available scroll range is the difference between scaled image width and screen width
|
||||
val extraWidth = kotlin.math.max(0f, scaledWidth - viewWidth)
|
||||
|
||||
// Calculate offset based on scroll position (0.0 = left, 1.0 = right)
|
||||
// Center (0.5) is 0 offset
|
||||
// Reverting to: `maxParallaxOffset = extraWidth`.
|
||||
// And relying on the "Zoom" logic to create that width if needed.
|
||||
val maxParallaxOffset = extraWidth
|
||||
val parallaxOffset = maxParallaxOffset * (0.5f - normalOffsetX)
|
||||
|
||||
// Verbose logging removed to avoid per-frame log spam
|
||||
val transform = GLGeometry.calculateWallpaperTransform(
|
||||
viewWidth = viewWidth,
|
||||
viewHeight = viewHeight,
|
||||
imageWidth = imageWidth,
|
||||
imageHeight = imageHeight,
|
||||
scalingType = currentScalingType,
|
||||
parallaxEnabled = currentEffects.enableParallax,
|
||||
parallaxIntensity = currentEffects.parallaxIntensity,
|
||||
normalizedOffsetX = normalOffsetX
|
||||
)
|
||||
|
||||
// 3. Construct Matrix
|
||||
// We use an orthographic projection matching the screen dimensions
|
||||
@@ -423,12 +372,18 @@ class PaperizeWallpaperRenderer(
|
||||
|
||||
// Apply Model transformations
|
||||
// Translate for parallax
|
||||
Matrix.translateM(matrix, 0, parallaxOffset, 0f, 0f)
|
||||
Matrix.translateM(matrix, 0, transform.horizontalOffset, 0f, 0f)
|
||||
|
||||
// Scale to match image size * crop scale
|
||||
// The quad is -1 to 1 (size 2), so we need to scale it to match image dimensions
|
||||
// Actually, we want to map the quad (-1..1) to the image size (-w/2..w/2)
|
||||
Matrix.scaleM(matrix, 0, scaledWidth / 2f, scaledHeight / 2f, 1f)
|
||||
Matrix.scaleM(
|
||||
matrix,
|
||||
0,
|
||||
transform.scaledWidth / 2f,
|
||||
transform.scaledHeight / 2f,
|
||||
1f
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -734,8 +689,9 @@ class PaperizeWallpaperRenderer(
|
||||
* @param offset Normalized offset (0.0 = left, 1.0 = right)
|
||||
*/
|
||||
fun setNormalOffsetX(offset: Float) {
|
||||
if (normalOffsetX != offset) {
|
||||
normalOffsetX = offset
|
||||
val clampedOffset = offset.coerceIn(0f, 1f)
|
||||
if (normalOffsetX != clampedOffset) {
|
||||
normalOffsetX = clampedOffset
|
||||
callbacks.requestRender()
|
||||
}
|
||||
}
|
||||
|
||||
+250
-351
@@ -13,69 +13,49 @@ import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.Result as PaperizeResult
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.setBitmapChecked
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
|
||||
import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase
|
||||
import com.anthonyla.paperize.presentation.MainActivity
|
||||
import com.anthonyla.paperize.service.WallpaperChangeLock
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import javax.inject.Inject
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Foreground service for changing wallpapers
|
||||
*
|
||||
* Actions:
|
||||
* - CHANGE_WALLPAPER: Change wallpaper immediately
|
||||
* Foreground service for immediate wallpaper changes and effect reapplication.
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class WallpaperChangeService : Service() {
|
||||
|
||||
@Inject
|
||||
lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase
|
||||
|
||||
@Inject
|
||||
lateinit var reapplyEffectsUseCase: ReapplyEffectsUseCase
|
||||
|
||||
@Inject
|
||||
lateinit var wallpaperRepository: WallpaperRepository
|
||||
|
||||
@Inject
|
||||
lateinit var settingsRepository: SettingsRepository
|
||||
|
||||
@Inject
|
||||
lateinit var wallpaperChangeLock: WallpaperChangeLock
|
||||
@Inject lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase
|
||||
@Inject lateinit var reapplyEffectsUseCase: ReapplyEffectsUseCase
|
||||
@Inject lateinit var settingsRepository: SettingsRepository
|
||||
@Inject lateinit var wallpaperChangeLock: WallpaperChangeLock
|
||||
|
||||
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
private lateinit var wallpaperManager: WallpaperManager
|
||||
private lateinit var notificationManager: NotificationManager
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WallpaperChangeService"
|
||||
const val ACTION_CHANGE_WALLPAPER = Constants.ACTION_CHANGE_WALLPAPER
|
||||
const val ACTION_REAPPLY_EFFECTS = Constants.ACTION_REAPPLY_EFFECTS
|
||||
const val EXTRA_SCREEN_TYPE = Constants.EXTRA_SCREEN_TYPE
|
||||
private const val ERROR_NOTIFICATION_ID = Constants.NOTIFICATION_ID + 1
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
wallpaperManager = WallpaperManager.getInstance(this)
|
||||
notificationManager = getSystemService(NotificationManager::class.java)
|
||||
?: throw IllegalStateException("NotificationManager not available")
|
||||
?: error("NotificationManager not available")
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
// Start foreground service. Android 14+ requires specifying the service type.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
startForeground(
|
||||
Constants.NOTIFICATION_ID,
|
||||
@@ -86,347 +66,301 @@ class WallpaperChangeService : Service() {
|
||||
startForeground(Constants.NOTIFICATION_ID, createNotification())
|
||||
}
|
||||
|
||||
val screenType = intent?.getStringExtra(EXTRA_SCREEN_TYPE)
|
||||
?.let(ScreenType::fromString)
|
||||
?: ScreenType.BOTH
|
||||
when (intent?.action) {
|
||||
ACTION_CHANGE_WALLPAPER -> {
|
||||
val screenType = intent.getStringExtra(EXTRA_SCREEN_TYPE)?.let {
|
||||
ScreenType.fromString(it)
|
||||
} ?: ScreenType.BOTH
|
||||
handleChangeWallpaper(screenType, startId)
|
||||
}
|
||||
ACTION_REAPPLY_EFFECTS -> {
|
||||
val screenType = intent.getStringExtra(EXTRA_SCREEN_TYPE)?.let {
|
||||
ScreenType.fromString(it)
|
||||
} ?: ScreenType.BOTH
|
||||
handleReapplyEffects(screenType, startId)
|
||||
}
|
||||
ACTION_CHANGE_WALLPAPER -> handleChangeWallpaper(screenType, startId)
|
||||
ACTION_REAPPLY_EFFECTS -> handleReapplyEffects(screenType, startId)
|
||||
else -> {
|
||||
// Unknown or null action — stop immediately to avoid a stuck foreground service
|
||||
Log.w(TAG, "Unknown action: ${intent?.action}")
|
||||
stopSelf(startId)
|
||||
}
|
||||
}
|
||||
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun handleChangeWallpaper(screenType: ScreenType, startId: Int) {
|
||||
serviceScope.launch {
|
||||
// Use mutex to prevent concurrent wallpaper changes
|
||||
wallpaperChangeLock.mutex.withLock {
|
||||
try {
|
||||
// Get schedule settings to determine which albums to use
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
|
||||
when (screenType) {
|
||||
ScreenType.LIVE -> {
|
||||
val reloadIntent = Intent(Constants.ACTION_RELOAD_WALLPAPER).apply {
|
||||
setPackage(packageName)
|
||||
}
|
||||
sendBroadcast(reloadIntent)
|
||||
Log.d(TAG, "Requested immediate live wallpaper reload")
|
||||
}
|
||||
ScreenType.HOME -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected")
|
||||
}
|
||||
}
|
||||
ScreenType.LOCK -> {
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
}
|
||||
ScreenType.BOTH -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
|
||||
// If same album and not separately scheduled, use same wallpaper
|
||||
if (homeAlbumId != null && lockAlbumId != null &&
|
||||
homeAlbumId == lockAlbumId && !settings.separateSchedules) {
|
||||
// Get one wallpaper and set for both screens
|
||||
val result = changeWallpaperUseCase(homeAlbumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
val canSetAtomically =
|
||||
settings.homeEffects == settings.lockEffects &&
|
||||
settings.homeScalingType == settings.lockScalingType
|
||||
|
||||
if (canSetAtomically) {
|
||||
// A single platform transaction prevents home and lock
|
||||
// from diverging (or one side reverting to the stock
|
||||
// wallpaper) if a second setBitmap call fails.
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
Log.d(TAG, "Home and lock wallpaper set atomically")
|
||||
} else {
|
||||
// Different effects/scaling require distinct render sizes.
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper set in BOTH mode")
|
||||
}
|
||||
|
||||
// Keep LOCK queue in sync with HOME so that if the user later
|
||||
// switches to separate schedules, both screens continue from
|
||||
// the same queue position rather than LOCK restarting at 0.
|
||||
try {
|
||||
val homeCurrentId = wallpaperRepository
|
||||
.getCurrentWallpaper(homeAlbumId, ScreenType.HOME)?.id
|
||||
if (homeCurrentId != null) {
|
||||
// Ensure LOCK queue exists (first run in synced mode)
|
||||
if (wallpaperRepository.getNextWallpaperInQueue(
|
||||
homeAlbumId, ScreenType.LOCK) == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(
|
||||
homeAlbumId, ScreenType.LOCK, settings.shuffleEnabled)
|
||||
}
|
||||
wallpaperRepository.getAndDequeueWallpaper(
|
||||
homeAlbumId, ScreenType.LOCK)
|
||||
wallpaperRepository.setCurrentWallpaper(
|
||||
homeAlbumId, ScreenType.LOCK, homeCurrentId)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to sync LOCK queue in BOTH mode", e)
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting wallpaper for both screens", e)
|
||||
} finally {
|
||||
// Recycle HOME bitmap BEFORE rendering LOCK to avoid
|
||||
// holding both in memory (~48MB + ~16MB).
|
||||
bitmap.recycle()
|
||||
}
|
||||
|
||||
if (settings.homeEffects != settings.lockEffects ||
|
||||
settings.homeScalingType != settings.lockScalingType) {
|
||||
// Render a separate bitmap only when the user deliberately
|
||||
// configured different lock-screen presentation settings.
|
||||
val lockResult = reapplyEffectsUseCase(homeAlbumId, ScreenType.LOCK)
|
||||
lockResult.onSuccess { lockBitmap ->
|
||||
try {
|
||||
wallpaperManager.setBitmap(
|
||||
lockBitmap, null, true, WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
Log.d(TAG, "Lock wallpaper set separately in BOTH mode")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper in BOTH mode", e)
|
||||
} finally {
|
||||
lockBitmap.recycle()
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.w(TAG, "Lock rerender failed in BOTH mode: ${error.message}")
|
||||
}
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(ScreenType.BOTH)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting wallpaper bitmap", error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Different albums or separately scheduled - change independently
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected")
|
||||
}
|
||||
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stopSelf(startId)
|
||||
changeWallpaper(screenType, settingsRepository.getScheduleSettings())
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error changing wallpaper", e)
|
||||
showErrorNotification(
|
||||
getString(R.string.app_name),
|
||||
e.localizedMessage
|
||||
?: getString(R.string.error_no_valid_wallpaper_after_retries)
|
||||
)
|
||||
} finally {
|
||||
stopSelf(startId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeHomeWallpaper(albumId: String) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
private suspend fun changeWallpaper(
|
||||
screenType: ScreenType,
|
||||
settings: ScheduleSettings
|
||||
) {
|
||||
when (screenType) {
|
||||
ScreenType.LIVE -> {
|
||||
sendBroadcast(
|
||||
Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(packageName)
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting home wallpaper", e)
|
||||
} finally {
|
||||
// Always recycle bitmap to prevent memory leaks
|
||||
bitmap.recycle()
|
||||
Log.d(TAG, "Requested immediate live wallpaper reload")
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(ScreenType.HOME)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting home wallpaper bitmap", error)
|
||||
|
||||
ScreenType.HOME -> settings.homeAlbumId?.let {
|
||||
changeSingle(it, ScreenType.HOME)
|
||||
} ?: Log.w(TAG, "No home album selected")
|
||||
|
||||
ScreenType.LOCK -> settings.lockAlbumId?.let {
|
||||
changeSingle(it, ScreenType.LOCK)
|
||||
} ?: Log.w(TAG, "No lock album selected")
|
||||
|
||||
ScreenType.BOTH -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (
|
||||
homeAlbumId != null &&
|
||||
homeAlbumId == lockAlbumId &&
|
||||
!settings.separateSchedules
|
||||
) {
|
||||
changeSynchronized(homeAlbumId, settings)
|
||||
} else {
|
||||
homeAlbumId?.let { changeSingle(it, ScreenType.HOME) }
|
||||
?: Log.w(TAG, "No home album selected")
|
||||
lockAlbumId?.let { changeSingle(it, ScreenType.LOCK) }
|
||||
?: Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeLockWallpaper(albumId: String) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.LOCK)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
private suspend fun changeSynchronized(
|
||||
albumId: String,
|
||||
settings: ScheduleSettings
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, ScreenType.HOME)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val prepared = result.data
|
||||
val samePresentation =
|
||||
settings.homeEffects == settings.lockEffects &&
|
||||
settings.homeScalingType == settings.lockScalingType
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
Log.d(TAG, "Lock wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper", e)
|
||||
} finally {
|
||||
// Always recycle bitmap to prevent memory leaks
|
||||
bitmap.recycle()
|
||||
if (samePresentation) {
|
||||
applyPrepared(
|
||||
prepared,
|
||||
WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK,
|
||||
listOf(ScreenType.HOME, ScreenType.LOCK)
|
||||
)
|
||||
Log.d(TAG, "Home and lock wallpaper set atomically")
|
||||
} else {
|
||||
applyPrepared(
|
||||
prepared,
|
||||
WallpaperManager.FLAG_SYSTEM,
|
||||
listOf(ScreenType.HOME)
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper set in BOTH mode")
|
||||
|
||||
when (
|
||||
val lockResult = reapplyEffectsUseCase(
|
||||
albumId,
|
||||
ScreenType.LOCK,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
) {
|
||||
is PaperizeResult.Success -> {
|
||||
val lockBitmap = lockResult.data
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(
|
||||
lockBitmap,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
changeWallpaperUseCase.complete(prepared, ScreenType.LOCK)
|
||||
Log.d(TAG, "Lock wallpaper set separately in BOTH mode")
|
||||
} finally {
|
||||
lockBitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> throw asException(lockResult.exception)
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(ScreenType.LOCK)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(ScreenType.BOTH)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeSingle(
|
||||
albumId: String,
|
||||
screenType: ScreenType
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, screenType)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val which = when (screenType) {
|
||||
ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM
|
||||
ScreenType.LOCK -> WallpaperManager.FLAG_LOCK
|
||||
else -> error("Unsupported static screen: $screenType")
|
||||
}
|
||||
applyPrepared(result.data, which, listOf(screenType))
|
||||
Log.d(TAG, "$screenType wallpaper changed successfully")
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(screenType)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyPrepared(
|
||||
prepared: PreparedWallpaper,
|
||||
which: Int,
|
||||
completedScreens: List<ScreenType>
|
||||
) {
|
||||
var platformAccepted = false
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(prepared.bitmap, which)
|
||||
platformAccepted = true
|
||||
completedScreens.forEach { screen ->
|
||||
changeWallpaperUseCase.complete(prepared, screen)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (!platformAccepted) {
|
||||
changeWallpaperUseCase.restore(prepared)
|
||||
}
|
||||
throw e
|
||||
} finally {
|
||||
prepared.bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reapply current effects to the last-applied wallpaper without advancing the queue.
|
||||
* Falls back to a normal queue advance if no current wallpaper is recorded.
|
||||
*/
|
||||
private fun handleReapplyEffects(screenType: ScreenType, startId: Int) {
|
||||
serviceScope.launch {
|
||||
wallpaperChangeLock.mutex.withLock {
|
||||
try {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
when (screenType) {
|
||||
ScreenType.HOME -> {
|
||||
val albumId = settings.homeAlbumId ?: run {
|
||||
Log.w(TAG, "No home album selected for reapply"); return@withLock
|
||||
}
|
||||
reapplyHome(albumId)
|
||||
ScreenType.HOME -> settings.homeAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.HOME)
|
||||
}
|
||||
ScreenType.LOCK -> {
|
||||
val albumId = settings.lockAlbumId ?: run {
|
||||
Log.w(TAG, "No lock album selected for reapply"); return@withLock
|
||||
}
|
||||
reapplyLock(albumId)
|
||||
|
||||
ScreenType.LOCK -> settings.lockAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.LOCK)
|
||||
}
|
||||
|
||||
ScreenType.BOTH -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (homeAlbumId != null) reapplyHome(homeAlbumId)
|
||||
if (lockAlbumId != null) reapplyLock(lockAlbumId)
|
||||
settings.homeAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.HOME)
|
||||
}
|
||||
settings.lockAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.LOCK)
|
||||
}
|
||||
}
|
||||
ScreenType.LIVE -> Unit // handled by live wallpaper service
|
||||
|
||||
ScreenType.LIVE -> Unit
|
||||
}
|
||||
stopSelf(startId)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error reapplying effects", e)
|
||||
showErrorNotification(
|
||||
getString(R.string.app_name),
|
||||
e.localizedMessage
|
||||
?: getString(R.string.error_no_valid_wallpaper_after_retries)
|
||||
)
|
||||
} finally {
|
||||
stopSelf(startId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun reapplyHome(albumId: String) {
|
||||
val result = reapplyEffectsUseCase(albumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.isRecycled) {
|
||||
throw IllegalStateException("Invalid bitmap for reapply")
|
||||
private suspend fun reapplySingle(
|
||||
albumId: String,
|
||||
screenType: ScreenType
|
||||
) {
|
||||
when (val result = reapplyEffectsUseCase(albumId, screenType)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val bitmap = result.data
|
||||
try {
|
||||
val which = if (screenType == ScreenType.HOME) {
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
} else {
|
||||
WallpaperManager.FLAG_LOCK
|
||||
}
|
||||
wallpaperManager.setBitmapChecked(bitmap, which)
|
||||
Log.d(TAG, "$screenType effects reapplied successfully")
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_SYSTEM)
|
||||
Log.d(TAG, "Home effects reapplied successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting home wallpaper during reapply", e)
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}.onError { error ->
|
||||
// Current wallpaper not recorded yet — fall back to normal queue advance
|
||||
Log.w(TAG, "Reapply failed for home, falling back to change: ${error.message}")
|
||||
changeHomeWallpaper(albumId)
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
Log.w(TAG, "Reapply failed for $screenType; advancing queue", result.exception)
|
||||
changeSingle(albumId, screenType)
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun reapplyLock(albumId: String) {
|
||||
val result = reapplyEffectsUseCase(albumId, ScreenType.LOCK)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.isRecycled) {
|
||||
throw IllegalStateException("Invalid bitmap for reapply")
|
||||
}
|
||||
wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK)
|
||||
Log.d(TAG, "Lock effects reapplied successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper during reapply", e)
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
private suspend fun handleEmptyAlbumError(screenType: ScreenType) {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
val updated = when (screenType) {
|
||||
ScreenType.HOME -> {
|
||||
val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
enableChanger = lockStillActive && settings.enableChanger
|
||||
)
|
||||
}
|
||||
}.onError { error ->
|
||||
// Current wallpaper not recorded yet — fall back to normal queue advance
|
||||
Log.w(TAG, "Reapply failed for lock, falling back to change: ${error.message}")
|
||||
changeLockWallpaper(albumId)
|
||||
|
||||
ScreenType.LOCK -> {
|
||||
val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
settings.copy(
|
||||
lockAlbumId = null,
|
||||
enableChanger = homeStillActive && settings.enableChanger
|
||||
)
|
||||
}
|
||||
|
||||
ScreenType.BOTH -> settings.copy(
|
||||
homeAlbumId = null,
|
||||
lockAlbumId = null,
|
||||
enableChanger = false
|
||||
)
|
||||
|
||||
ScreenType.LIVE -> settings.copy(enableChanger = false)
|
||||
}
|
||||
settingsRepository.updateScheduleSettings(updated)
|
||||
showErrorNotification(
|
||||
getString(R.string.no_wallpapers_in_album),
|
||||
getString(R.string.wallpaper_changer_disabled_empty_album)
|
||||
)
|
||||
}
|
||||
|
||||
private fun createNotification(): Notification {
|
||||
val intent = Intent(this, MainActivity::class.java)
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
intent,
|
||||
Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
return NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(getString(R.string.changing_wallpaper))
|
||||
@@ -436,18 +370,13 @@ class WallpaperChangeService : Service() {
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Show an error notification to the user
|
||||
*/
|
||||
private fun showErrorNotification(title: String, message: String) {
|
||||
val intent = Intent(this, MainActivity::class.java)
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
intent,
|
||||
Intent(this, MainActivity::class.java),
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(title)
|
||||
.setContentText(message)
|
||||
@@ -456,49 +385,11 @@ class WallpaperChangeService : Service() {
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(ERROR_NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(screenType: ScreenType) {
|
||||
Log.w(TAG, "Album is empty for $screenType")
|
||||
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
|
||||
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)
|
||||
)
|
||||
}
|
||||
private fun asException(throwable: Throwable): Exception =
|
||||
throwable as? Exception ?: RuntimeException(throwable)
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
@@ -506,4 +397,12 @@ class WallpaperChangeService : Service() {
|
||||
serviceScope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WallpaperChangeService"
|
||||
const val ACTION_CHANGE_WALLPAPER = Constants.ACTION_CHANGE_WALLPAPER
|
||||
const val ACTION_REAPPLY_EFFECTS = Constants.ACTION_REAPPLY_EFFECTS
|
||||
const val EXTRA_SCREEN_TYPE = Constants.EXTRA_SCREEN_TYPE
|
||||
private const val ERROR_NOTIFICATION_ID = Constants.NOTIFICATION_ID + 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.anthonyla.paperize.service.worker
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
|
||||
/**
|
||||
* Schedules a folder rescan whenever Paperize enters the foreground.
|
||||
*
|
||||
* Unique work with [ExistingWorkPolicy.KEEP] coalesces rapid foreground transitions and avoids
|
||||
* running a second scan while an existing one is still active.
|
||||
*/
|
||||
object AlbumRefreshScheduler {
|
||||
internal const val UNIQUE_WORK_NAME = "album_refresh_on_foreground"
|
||||
internal const val WORK_TAG = "foreground_album_refresh"
|
||||
|
||||
fun enqueue(context: Context) {
|
||||
val request = OneTimeWorkRequestBuilder<AlbumRefreshWorker>()
|
||||
.addTag(WORK_TAG)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
UNIQUE_WORK_NAME,
|
||||
ExistingWorkPolicy.KEEP,
|
||||
request
|
||||
)
|
||||
}
|
||||
}
|
||||
+188
-220
@@ -2,15 +2,19 @@ package com.anthonyla.paperize.service.worker
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.hilt.work.HiltWorker
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.Result as PaperizeResult
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.setBitmapChecked
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
|
||||
import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase
|
||||
import com.anthonyla.paperize.service.WallpaperChangeLock
|
||||
@@ -19,10 +23,7 @@ import dagger.assisted.AssistedInject
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/**
|
||||
* WorkManager worker for changing wallpapers
|
||||
*
|
||||
* Handles periodic wallpaper changes for home screen, lock screen, or both.
|
||||
* Uses CoroutineWorker for suspend function support and Hilt for dependency injection.
|
||||
* WorkManager worker for scheduled wallpaper changes.
|
||||
*/
|
||||
@HiltWorker
|
||||
class WallpaperChangeWorker @AssistedInject constructor(
|
||||
@@ -31,31 +32,23 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
private val changeWallpaperUseCase: ChangeWallpaperUseCase,
|
||||
private val reapplyEffectsUseCase: ReapplyEffectsUseCase,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val wallpaperChangeLock: WallpaperChangeLock
|
||||
) : CoroutineWorker(context, workerParams) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WallpaperChangeWorker"
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
return try {
|
||||
val screenTypeString = inputData.getString(Constants.EXTRA_SCREEN_TYPE)
|
||||
val screenType = screenTypeString?.let { ScreenType.fromString(it) } ?: ScreenType.HOME
|
||||
val screenType = inputData.getString(Constants.EXTRA_SCREEN_TYPE)
|
||||
?.let(ScreenType::fromString)
|
||||
?: ScreenType.HOME
|
||||
|
||||
Log.d(TAG, "Starting wallpaper change for $screenType")
|
||||
|
||||
// Use shared lock to prevent concurrent wallpaper changes across service and worker
|
||||
wallpaperChangeLock.mutex.withLock {
|
||||
changeWallpaper(screenType)
|
||||
}
|
||||
|
||||
Log.d(TAG, "Wallpaper change completed successfully for $screenType")
|
||||
Result.success()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error changing wallpaper", e)
|
||||
// Retry on failure (WorkManager will handle backoff)
|
||||
if (runAttemptCount < Constants.MAX_WORK_RETRY_ATTEMPTS) {
|
||||
Result.retry()
|
||||
} else {
|
||||
@@ -70,232 +63,207 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
|
||||
when (screenType) {
|
||||
ScreenType.LIVE -> {
|
||||
// Send broadcast to trigger live wallpaper reload
|
||||
val intent = android.content.Intent(Constants.ACTION_RELOAD_WALLPAPER)
|
||||
intent.setPackage(context.packageName)
|
||||
context.sendBroadcast(intent)
|
||||
context.sendBroadcast(
|
||||
Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(context.packageName)
|
||||
)
|
||||
Log.d(TAG, "Sent reload broadcast to live wallpaper service")
|
||||
}
|
||||
|
||||
ScreenType.HOME -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId, settings, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected")
|
||||
}
|
||||
settings.homeAlbumId?.let {
|
||||
changeSingle(it, ScreenType.HOME, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No home album selected")
|
||||
}
|
||||
|
||||
ScreenType.LOCK -> {
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId, settings, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
settings.lockAlbumId?.let {
|
||||
changeSingle(it, ScreenType.LOCK, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
|
||||
ScreenType.BOTH -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
|
||||
// Only treat as synchronized when both screens point to the same album.
|
||||
// If they diverge (transient state during album selection), fall back to
|
||||
// independent changes — mirrors the guard in WallpaperChangeService.
|
||||
if (homeAlbumId != null && lockAlbumId != null && homeAlbumId == lockAlbumId) {
|
||||
val result = changeWallpaperUseCase(homeAlbumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
Log.d(TAG, "Setting both screens - size: ${bitmap.width}x${bitmap.height}, config: ${bitmap.config}")
|
||||
|
||||
val canSetAtomically =
|
||||
settings.homeEffects == settings.lockEffects &&
|
||||
settings.homeScalingType == settings.lockScalingType
|
||||
|
||||
if (canSetAtomically) {
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
Log.d(TAG, "Home and lock wallpaper set atomically")
|
||||
} else {
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper set in BOTH mode")
|
||||
}
|
||||
|
||||
// Keep LOCK queue in sync with HOME so that if the user later
|
||||
// switches to separate schedules, both screens continue from
|
||||
// the same queue position rather than LOCK restarting at 0.
|
||||
try {
|
||||
val homeCurrentId = wallpaperRepository
|
||||
.getCurrentWallpaper(homeAlbumId, ScreenType.HOME)?.id
|
||||
if (homeCurrentId != null) {
|
||||
if (wallpaperRepository.getNextWallpaperInQueue(
|
||||
homeAlbumId, ScreenType.LOCK) == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(
|
||||
homeAlbumId, ScreenType.LOCK, settings.shuffleEnabled)
|
||||
}
|
||||
wallpaperRepository.getAndDequeueWallpaper(
|
||||
homeAlbumId, ScreenType.LOCK)
|
||||
wallpaperRepository.setCurrentWallpaper(
|
||||
homeAlbumId, ScreenType.LOCK, homeCurrentId)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to sync LOCK queue in BOTH mode", e)
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting wallpaper for both screens", e)
|
||||
} finally {
|
||||
// Recycle HOME bitmap BEFORE rendering LOCK to avoid
|
||||
// holding both in memory simultaneously.
|
||||
bitmap.recycle()
|
||||
}
|
||||
|
||||
if (settings.homeEffects != settings.lockEffects ||
|
||||
settings.homeScalingType != settings.lockScalingType) {
|
||||
val lockResult = reapplyEffectsUseCase(homeAlbumId, ScreenType.LOCK)
|
||||
lockResult.onSuccess { lockBitmap ->
|
||||
try {
|
||||
wallpaperManager.setBitmap(
|
||||
lockBitmap, null, true, WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
Log.d(TAG, "Lock wallpaper set separately in BOTH mode")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper in BOTH mode", e)
|
||||
} finally {
|
||||
lockBitmap.recycle()
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.w(TAG, "Lock rerender failed in BOTH mode: ${error.message}")
|
||||
}
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error is EmptyAlbumException) {
|
||||
Log.w(TAG, "Album is empty for BOTH screens — disabling changer")
|
||||
val updatedSettings = settings.copy(
|
||||
homeAlbumId = null,
|
||||
lockAlbumId = null,
|
||||
enableChanger = false
|
||||
)
|
||||
settingsRepository.updateScheduleSettings(updatedSettings)
|
||||
} else {
|
||||
Log.e(TAG, "Error getting wallpaper bitmap for both screens", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
if (
|
||||
homeAlbumId != null &&
|
||||
homeAlbumId == lockAlbumId &&
|
||||
!settings.separateSchedules
|
||||
) {
|
||||
changeSynchronized(homeAlbumId, settings, wallpaperManager)
|
||||
} else {
|
||||
// Albums diverged — change screens independently
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId, settings, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected for BOTH mode")
|
||||
}
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId, settings, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected for BOTH mode")
|
||||
}
|
||||
homeAlbumId?.let {
|
||||
changeSingle(it, ScreenType.HOME, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No home album selected for BOTH mode")
|
||||
lockAlbumId?.let {
|
||||
changeSingle(it, ScreenType.LOCK, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No lock album selected for BOTH mode")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeHomeWallpaper(albumId: String, settings: com.anthonyla.paperize.domain.model.ScheduleSettings, wallpaperManager: WallpaperManager) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
private suspend fun changeSynchronized(
|
||||
albumId: String,
|
||||
settings: ScheduleSettings,
|
||||
wallpaperManager: WallpaperManager
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, ScreenType.HOME)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val prepared = result.data
|
||||
val samePresentation =
|
||||
settings.homeEffects == settings.lockEffects &&
|
||||
settings.homeScalingType == settings.lockScalingType
|
||||
|
||||
if (samePresentation) {
|
||||
applyPrepared(
|
||||
prepared = prepared,
|
||||
wallpaperManager = wallpaperManager,
|
||||
which = WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK,
|
||||
completedScreens = listOf(ScreenType.HOME, ScreenType.LOCK)
|
||||
)
|
||||
Log.d(TAG, "Home and lock wallpaper set atomically")
|
||||
} else {
|
||||
// Distinct effects require two platform writes. Each screen is committed only
|
||||
// after its own write succeeds.
|
||||
applyPrepared(
|
||||
prepared = prepared,
|
||||
wallpaperManager = wallpaperManager,
|
||||
which = WallpaperManager.FLAG_SYSTEM,
|
||||
completedScreens = listOf(ScreenType.HOME)
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper set in BOTH mode")
|
||||
|
||||
when (
|
||||
val lockResult = reapplyEffectsUseCase(
|
||||
albumId,
|
||||
ScreenType.LOCK,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
) {
|
||||
is PaperizeResult.Success -> {
|
||||
val lockBitmap = lockResult.data
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(
|
||||
lockBitmap,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
changeWallpaperUseCase.complete(prepared, ScreenType.LOCK)
|
||||
Log.d(TAG, "Lock wallpaper set separately in BOTH mode")
|
||||
} finally {
|
||||
lockBitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> throw asException(lockResult.exception)
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
Log.d(TAG, "Setting home wallpaper - size: ${bitmap.width}x${bitmap.height}, config: ${bitmap.config}")
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
|
||||
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 ->
|
||||
if (error is EmptyAlbumException) {
|
||||
Log.w(TAG, "Home album is empty — disabling home screen")
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
Log.w(TAG, "Album is empty for BOTH screens; disabling changer")
|
||||
settingsRepository.updateScheduleSettings(
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
lockAlbumId = null,
|
||||
enableChanger = false
|
||||
)
|
||||
)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeSingle(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
settings: ScheduleSettings,
|
||||
wallpaperManager: WallpaperManager
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, screenType)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val flag = when (screenType) {
|
||||
ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM
|
||||
ScreenType.LOCK -> WallpaperManager.FLAG_LOCK
|
||||
else -> error("Unsupported static screen: $screenType")
|
||||
}
|
||||
applyPrepared(result.data, wallpaperManager, flag, listOf(screenType))
|
||||
Log.d(TAG, "$screenType wallpaper changed successfully")
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
disableEmptyScreen(screenType, settings)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyPrepared(
|
||||
prepared: PreparedWallpaper,
|
||||
wallpaperManager: WallpaperManager,
|
||||
which: Int,
|
||||
completedScreens: List<ScreenType>
|
||||
) {
|
||||
var platformAccepted = false
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(prepared.bitmap, which)
|
||||
platformAccepted = true
|
||||
completedScreens.forEach { screen ->
|
||||
changeWallpaperUseCase.complete(prepared, screen)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (!platformAccepted) {
|
||||
changeWallpaperUseCase.restore(prepared)
|
||||
}
|
||||
throw e
|
||||
} finally {
|
||||
prepared.bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun disableEmptyScreen(
|
||||
screenType: ScreenType,
|
||||
settings: ScheduleSettings
|
||||
) {
|
||||
when (screenType) {
|
||||
ScreenType.HOME -> {
|
||||
val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null
|
||||
settingsRepository.updateScheduleSettings(settings.copy(
|
||||
homeAlbumId = null,
|
||||
enableChanger = if (lockStillActive) settings.enableChanger else false
|
||||
))
|
||||
} else {
|
||||
Log.e(TAG, "Error getting home wallpaper bitmap", error)
|
||||
throw error
|
||||
settingsRepository.updateScheduleSettings(
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
enableChanger = lockStillActive && settings.enableChanger
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
ScreenType.LOCK -> {
|
||||
val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
settingsRepository.updateScheduleSettings(
|
||||
settings.copy(
|
||||
lockAlbumId = null,
|
||||
enableChanger = homeStillActive && settings.enableChanger
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeLockWallpaper(albumId: String, settings: com.anthonyla.paperize.domain.model.ScheduleSettings, wallpaperManager: WallpaperManager) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.LOCK)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
private fun asException(throwable: Throwable): Exception =
|
||||
throwable as? Exception ?: RuntimeException(throwable)
|
||||
|
||||
Log.d(TAG, "Setting lock wallpaper - size: ${bitmap.width}x${bitmap.height}, config: ${bitmap.config}")
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
|
||||
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 ->
|
||||
if (error is EmptyAlbumException) {
|
||||
Log.w(TAG, "Lock album is empty — disabling lock screen")
|
||||
val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
settingsRepository.updateScheduleSettings(settings.copy(
|
||||
lockAlbumId = null,
|
||||
enableChanger = if (homeStillActive) settings.enableChanger else false
|
||||
))
|
||||
} else {
|
||||
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private companion object {
|
||||
const val TAG = "WallpaperChangeWorker"
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@
|
||||
<string name="change_on_screen_off">Change on Screen Off</string>
|
||||
<string name="change_wallpaper_when_screen_turns_off">Change wallpaper when screen turns off</string>
|
||||
<string name="parallax_effect">Parallax Effect</string>
|
||||
<string name="wallpaper_moves_with_screen_scroll">Wallpaper moves with screen scroll</string>
|
||||
<string name="wallpaper_moves_with_screen_scroll">Swipe between home-screen pages to move the wallpaper (launcher support required)</string>
|
||||
<string name="live_wallpaper_name">Paperize Live Wallpaper</string>
|
||||
<string name="live_wallpaper_description">Dynamic wallpapers with effects and interactive features</string>
|
||||
<string name="adaptive_brightness">Adaptive Brightness</string>
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ScreenMetricsCompatTest {
|
||||
@@ -42,4 +46,18 @@ class ScreenMetricsCompatTest {
|
||||
|
||||
assertNull(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `home fill preserves overflow for launcher scrolling`() {
|
||||
assertTrue(usesLauncherManagedScrolling(ScreenType.HOME, ScalingType.FILL))
|
||||
assertTrue(usesLauncherManagedScrolling(ScreenType.BOTH, ScalingType.FILL))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `non-fill and lock rendering use exact canvas`() {
|
||||
assertFalse(usesLauncherManagedScrolling(ScreenType.HOME, ScalingType.FIT))
|
||||
assertFalse(usesLauncherManagedScrolling(ScreenType.HOME, ScalingType.STRETCH))
|
||||
assertFalse(usesLauncherManagedScrolling(ScreenType.HOME, ScalingType.NONE))
|
||||
assertFalse(usesLauncherManagedScrolling(ScreenType.LOCK, ScalingType.FILL))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import java.io.IOException
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class WallpaperManagerExtTest {
|
||||
|
||||
@Test
|
||||
fun `zero wallpaper id is treated as failure`() {
|
||||
assertThrows(IOException::class.java) {
|
||||
requireWallpaperSetSucceeded(0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `positive wallpaper id is accepted`() {
|
||||
requireWallpaperSetSucceeded(42)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.coVerifyOrder
|
||||
import io.mockk.mockk
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Test
|
||||
|
||||
class ChangeWallpaperUseCaseTest {
|
||||
|
||||
private val repository = mockk<WallpaperRepository>(relaxed = true)
|
||||
private val useCase = ChangeWallpaperUseCase(
|
||||
context = mockk<Context>(relaxed = true),
|
||||
wallpaperRepository = repository,
|
||||
settingsRepository = mockk<SettingsRepository>(relaxed = true)
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `complete records current then synchronizes exact queue item`() = runTest {
|
||||
val prepared = preparedWallpaper()
|
||||
coEvery {
|
||||
repository.getNextWallpaperInQueue(prepared.albumId, ScreenType.LOCK)
|
||||
} returns null
|
||||
coEvery {
|
||||
repository.buildWallpaperQueue(prepared.albumId, ScreenType.LOCK, false)
|
||||
} returns Result.Success(Unit)
|
||||
|
||||
useCase.complete(prepared, ScreenType.LOCK)
|
||||
|
||||
coVerifyOrder {
|
||||
repository.setCurrentWallpaper(
|
||||
prepared.albumId,
|
||||
ScreenType.LOCK,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
repository.getNextWallpaperInQueue(prepared.albumId, ScreenType.LOCK)
|
||||
repository.buildWallpaperQueue(prepared.albumId, ScreenType.LOCK, false)
|
||||
repository.removeWallpaperFromQueue(
|
||||
prepared.albumId,
|
||||
ScreenType.LOCK,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `restore returns rejected item to its original queue`() = runTest {
|
||||
val prepared = preparedWallpaper()
|
||||
|
||||
useCase.restore(prepared)
|
||||
|
||||
coVerify(exactly = 1) {
|
||||
repository.restoreWallpaperToQueueFront(
|
||||
prepared.albumId,
|
||||
prepared.screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
}
|
||||
coVerify(exactly = 0) {
|
||||
repository.setCurrentWallpaper(any(), any(), any())
|
||||
}
|
||||
}
|
||||
|
||||
private fun preparedWallpaper() = PreparedWallpaper(
|
||||
bitmap = mockk<Bitmap>(relaxed = true),
|
||||
albumId = "album",
|
||||
screenType = ScreenType.HOME,
|
||||
wallpaperId = "wallpaper",
|
||||
shuffle = false
|
||||
)
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.renderer
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class GLGeometryTest {
|
||||
|
||||
@Test
|
||||
fun `fill parallax reaches both real image edges`() {
|
||||
val left = transform(ScalingType.FILL, offset = 0f)
|
||||
val center = transform(ScalingType.FILL, offset = 0.5f)
|
||||
val right = transform(ScalingType.FILL, offset = 1f)
|
||||
|
||||
assertEquals(400f, left.scaledWidth, 0.001f)
|
||||
assertEquals(150f, left.horizontalOffset, 0.001f)
|
||||
assertEquals(0f, center.horizontalOffset, 0.001f)
|
||||
assertEquals(-150f, right.horizontalOffset, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `fit adds bounded overscan when parallax is enabled`() {
|
||||
val left = transform(ScalingType.FIT, offset = 0f)
|
||||
val right = transform(ScalingType.FIT, offset = 1f)
|
||||
|
||||
assertEquals(120f, left.scaledWidth, 0.001f)
|
||||
assertEquals(10f, left.horizontalOffset, 0.001f)
|
||||
assertEquals(-10f, right.horizontalOffset, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `launcher offsets are clamped to documented range`() {
|
||||
assertEquals(
|
||||
transform(ScalingType.FILL, offset = 0f),
|
||||
transform(ScalingType.FILL, offset = -5f)
|
||||
)
|
||||
assertEquals(
|
||||
transform(ScalingType.FILL, offset = 1f),
|
||||
transform(ScalingType.FILL, offset = 5f)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `disabled parallax keeps a wide image centered`() {
|
||||
val result = transform(
|
||||
scalingType = ScalingType.FILL,
|
||||
offset = 0f,
|
||||
enabled = false
|
||||
)
|
||||
|
||||
assertEquals(0f, result.horizontalOffset, 0.001f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parallax intensity scales travel across existing overflow`() {
|
||||
val result = transform(
|
||||
scalingType = ScalingType.FILL,
|
||||
offset = 0f,
|
||||
intensity = 50
|
||||
)
|
||||
|
||||
assertEquals(75f, result.horizontalOffset, 0.001f)
|
||||
}
|
||||
|
||||
private fun transform(
|
||||
scalingType: ScalingType,
|
||||
offset: Float,
|
||||
enabled: Boolean = true,
|
||||
intensity: Int = 100
|
||||
): GLGeometry.WallpaperTransform =
|
||||
GLGeometry.calculateWallpaperTransform(
|
||||
viewWidth = 100f,
|
||||
viewHeight = 200f,
|
||||
imageWidth = 400f,
|
||||
imageHeight = 200f,
|
||||
scalingType = scalingType,
|
||||
parallaxEnabled = enabled,
|
||||
parallaxIntensity = intensity,
|
||||
normalizedOffsetX = offset
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user