Skip to content

Commit 1fb33ba

Browse files
Merge pull request #74 from codenameakshay/fix/android-rotation-start
Fix double apply, cache loss, and hidden failures on rotation start
2 parents 62cd180 + 0048457 commit 1fb33ba

5 files changed

Lines changed: 110 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
- The video scale mode is persisted with the active asset instead of being held in a process-global field, so `fitCenter` survives process death and cannot be applied to a different video.
99
- Static wallpapers and rotation now draw onto the display size instead of the launcher's desired size. That size is a wide virtual canvas (for example 4800x2400 on a 1080x2400 phone), and Android shows its left edge, so `fitCenter` and `center` produced an all-black screen and the other modes showed only a zoomed-in left strip of the image.
1010
- Charging rotation now applies at most once per configured interval while the device is charging instead of once per plug-in event. Overnight active-hour windows (for example `22` to `6`) are supported, equal start/end hours mean a full-day window, and alarm scheduling no longer drifts by the window length.
11+
- Starting a rotation no longer applies twice. WorkManager ran the new periodic request at once, right after start had applied the first wallpaper, so the playlist skipped ahead. The first scheduled run now waits one interval.
12+
- A rejected rotation start (for example every source failing to load) no longer deletes the cache of the rotation that is still running. Before, that rotation kept reporting "running" but every later rotation failed.
13+
- `WallpaperRotationStatus.totalCount` now counts the requested sources and `cachedCount` the ones that loaded, so a source that failed to load is visible instead of both numbers matching.
1114
- `startWallpaperRotation`, `stopWallpaperRotation`, `rotateWallpaperNow`, and `getWallpaperRotationStatus` now return an `unsupported` result / a not-running status off Android instead of falling through to a platform call.
1215
- `getWallpaperRotationStatus()` no longer throws when the platform call fails; it returns a not-running status with `lastError` set instead.
1316
- Results decided in Dart (unsupported platform, invalid input, transport exception) now fill `home`/`lock` for each requested target, the same way Android does, instead of leaving them null.

‎android/src/main/kotlin/com/codenameakshay/async_wallpaper/WallpaperRotationEngine.kt‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,34 @@ internal enum class RotationStartResult {
2424
FAILED_AFTER_SAVE,
2525
}
2626

27+
/**
28+
* Fills a sibling staging directory and swaps it in only when [fill] produced at least one file, so
29+
* a rejected playlist never deletes the cache a running rotation still reads. Returns the absolute
30+
* paths inside [target], or an empty list when nothing was produced or the swap failed; in both
31+
* cases [target] keeps its previous contents.
32+
*/
33+
internal fun replaceDirectoryContents(target: File, fill: (File) -> List<String>): List<String> {
34+
val parent = target.absoluteFile.parentFile
35+
val staging = File(parent, "${target.name}.staging").apply { deleteRecursively(); mkdirs() }
36+
val names = fill(staging)
37+
if (names.isEmpty()) {
38+
staging.deleteRecursively()
39+
return emptyList()
40+
}
41+
val previous = File(parent, "${target.name}.previous").apply { deleteRecursively() }
42+
if (target.exists() && !target.renameTo(previous)) {
43+
staging.deleteRecursively()
44+
return emptyList()
45+
}
46+
if (!staging.renameTo(target)) {
47+
previous.renameTo(target)
48+
staging.deleteRecursively()
49+
return emptyList()
50+
}
51+
previous.deleteRecursively()
52+
return names.map { File(target, it).absolutePath }
53+
}
54+
2755
internal class WallpaperRotationEngine(
2856
context: Context,
2957
private val store: WallpaperRotationStore,
@@ -45,14 +73,16 @@ internal class WallpaperRotationEngine(
4573
return@withLock RotationStartResult.REJECTED
4674
}
4775

48-
val preparedFiles = prepareLocalFiles(config.sources.orEmpty())
76+
val sources = config.sources.orEmpty()
77+
val preparedFiles = prepareLocalFiles(sources)
4978
if (preparedFiles.isEmpty()) {
5079
store.setLastError("No valid wallpapers available for rotation.")
5180
return@withLock RotationStartResult.REJECTED
5281
}
5382

5483
val storedConfig = StoredWallpaperRotationConfig(
5584
localSources = preparedFiles,
85+
requestedSourceCount = sources.size,
5686
target = targetToStored(config.target),
5787
intervalMinutes = intervalMinutes,
5888
enableIntervalTrigger = config.enableIntervalTrigger == true,
@@ -148,13 +178,11 @@ internal class WallpaperRotationEngine(
148178
return list
149179
}
150180

151-
private fun prepareLocalFiles(sources: List<RotationSourceData?>): List<String> {
152-
val cacheDir = getRotationCacheDirectory()
153-
if (cacheDir.exists()) {
154-
cacheDir.deleteRecursively()
155-
}
156-
cacheDir.mkdirs()
181+
private fun prepareLocalFiles(sources: List<RotationSourceData?>): List<String> =
182+
replaceDirectoryContents(getRotationCacheDirectory()) { stagingDir -> cacheSources(sources, stagingDir) }
157183

184+
/** Caches every loadable source into [cacheDir] and returns the cached file names. */
185+
private fun cacheSources(sources: List<RotationSourceData?>, cacheDir: File): List<String> {
158186
val prepared = mutableListOf<String>()
159187
sources.forEachIndexed { index, sourceData ->
160188
val source = sourceData?.source?.trim().orEmpty()
@@ -174,7 +202,7 @@ internal class WallpaperRotationEngine(
174202
null -> false
175203
}
176204
if (success) {
177-
prepared.add(targetFile.absolutePath)
205+
prepared.add(targetFile.name)
178206
}
179207
}
180208
return prepared

‎android/src/main/kotlin/com/codenameakshay/async_wallpaper/WallpaperRotationScheduler.kt‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import androidx.work.Constraints
88
import androidx.work.ExistingPeriodicWorkPolicy
99
import androidx.work.ExistingWorkPolicy
1010
import androidx.work.OneTimeWorkRequestBuilder
11+
import androidx.work.PeriodicWorkRequest
1112
import androidx.work.PeriodicWorkRequestBuilder
1213
import androidx.work.WorkManager
1314
import java.util.concurrent.TimeUnit
@@ -28,15 +29,10 @@ internal object WallpaperRotationScheduler {
2829
private const val TIME_OF_DAY_REQUEST_CODE = 42043
2930

3031
fun schedulePeriodic(context: Context, intervalMinutes: Int) {
31-
val workManager = WorkManager.getInstance(context)
32-
val request = PeriodicWorkRequestBuilder<WallpaperRotationWorker>(
33-
intervalMinutes.toLong(),
34-
TimeUnit.MINUTES,
35-
).build()
36-
workManager.enqueueUniquePeriodicWork(
32+
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
3733
PERIODIC_WORK_NAME,
3834
ExistingPeriodicWorkPolicy.UPDATE,
39-
request,
35+
rotationRequest(intervalMinutes, requiresCharging = false),
4036
)
4137
}
4238

@@ -49,19 +45,24 @@ internal object WallpaperRotationScheduler {
4945
* `ACTION_POWER_CONNECTED` receiver, which required a persistent foreground service.
5046
*/
5147
fun scheduleCharging(context: Context, intervalMinutes: Int) {
52-
val request = PeriodicWorkRequestBuilder<WallpaperRotationWorker>(
53-
intervalMinutes.toLong(),
54-
TimeUnit.MINUTES,
55-
).setConstraints(
56-
Constraints.Builder().setRequiresCharging(true).build(),
57-
).build()
5848
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
5949
CHARGING_WORK_NAME,
6050
ExistingPeriodicWorkPolicy.UPDATE,
61-
request,
51+
rotationRequest(intervalMinutes, requiresCharging = true),
6252
)
6353
}
6454

55+
/**
56+
* Starting a rotation already applies the first wallpaper, so the first scheduled run waits one
57+
* interval. Without the delay WorkManager runs a new periodic request at once and skips ahead.
58+
*/
59+
internal fun rotationRequest(intervalMinutes: Int, requiresCharging: Boolean): PeriodicWorkRequest {
60+
return PeriodicWorkRequestBuilder<WallpaperRotationWorker>(intervalMinutes.toLong(), TimeUnit.MINUTES)
61+
.setInitialDelay(intervalMinutes.toLong(), TimeUnit.MINUTES)
62+
.setConstraints(Constraints.Builder().setRequiresCharging(requiresCharging).build())
63+
.build()
64+
}
65+
6566
fun cancelCharging(context: Context) {
6667
WorkManager.getInstance(context).cancelUniqueWork(CHARGING_WORK_NAME)
6768
}

‎android/src/main/kotlin/com/codenameakshay/async_wallpaper/WallpaperRotationStore.kt‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import org.json.JSONArray
66

77
internal data class StoredWallpaperRotationConfig(
88
val localSources: List<String>,
9+
/** Sources the caller asked for; [localSources] holds only the ones that could be cached. */
10+
val requestedSourceCount: Int,
911
val target: Int,
1012
val intervalMinutes: Int,
1113
val enableIntervalTrigger: Boolean,
@@ -24,6 +26,7 @@ internal class WallpaperRotationStore(context: Context) {
2426
prefs.edit {
2527
putBoolean(KEY_IS_RUNNING, true)
2628
putString(KEY_LOCAL_SOURCES, JSONArray(config.localSources).toString())
29+
putInt(KEY_REQUESTED_SOURCE_COUNT, config.requestedSourceCount)
2730
putInt(KEY_TARGET, config.target)
2831
putInt(KEY_INTERVAL_MINUTES, config.intervalMinutes)
2932
putBoolean(KEY_ENABLE_INTERVAL_TRIGGER, config.enableIntervalTrigger)
@@ -49,6 +52,7 @@ internal class WallpaperRotationStore(context: Context) {
4952
}
5053
return StoredWallpaperRotationConfig(
5154
localSources = localSources,
55+
requestedSourceCount = prefs.getInt(KEY_REQUESTED_SOURCE_COUNT, localSources.size),
5256
target = prefs.getInt(KEY_TARGET, 2),
5357
intervalMinutes = prefs.getInt(KEY_INTERVAL_MINUTES, DEFAULT_INTERVAL_MINUTES),
5458
enableIntervalTrigger = prefs.getBoolean(KEY_ENABLE_INTERVAL_TRIGGER, true),
@@ -114,7 +118,7 @@ internal class WallpaperRotationStore(context: Context) {
114118
nextRunEpochMs = getNextRunEpochMs(),
115119
currentIndex = getCurrentIndex().toLong(),
116120
cachedCount = config?.localSources?.size?.toLong() ?: 0L,
117-
totalCount = config?.localSources?.size?.toLong() ?: 0L,
121+
totalCount = config?.requestedSourceCount?.toLong() ?: 0L,
118122
lastError = prefs.getString(KEY_LAST_ERROR, null),
119123
effectiveIntervalMinutes = config?.intervalMinutes?.toLong() ?: 0L,
120124
)
@@ -153,6 +157,7 @@ internal class WallpaperRotationStore(context: Context) {
153157
private const val PREFS_NAME = "async_wallpaper_rotation"
154158
private const val KEY_IS_RUNNING = "is_running"
155159
private const val KEY_LOCAL_SOURCES = "local_sources"
160+
private const val KEY_REQUESTED_SOURCE_COUNT = "requested_source_count"
156161
private const val KEY_TARGET = "target"
157162
private const val KEY_INTERVAL_MINUTES = "interval_minutes"
158163
private const val KEY_ENABLE_INTERVAL_TRIGGER = "enable_interval_trigger"
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.codenameakshay.async_wallpaper
2+
3+
import java.io.File
4+
import java.nio.file.Files
5+
import java.util.concurrent.TimeUnit
6+
import org.junit.Assert.assertEquals
7+
import org.junit.Assert.assertFalse
8+
import org.junit.Assert.assertTrue
9+
import org.junit.Test
10+
11+
class RotationStartTest {
12+
@Test
13+
fun `a rejected playlist keeps the cache a running rotation reads`() {
14+
val root = Files.createTempDirectory("rotation").toFile()
15+
val cache = File(root, "wallpaper_rotation").apply { mkdirs() }
16+
File(cache, "wallpaper_0.jpg").writeText("running")
17+
18+
val paths = replaceDirectoryContents(cache) { emptyList() }
19+
20+
assertTrue(paths.isEmpty())
21+
assertEquals("running", File(cache, "wallpaper_0.jpg").readText())
22+
assertEquals(listOf("wallpaper_rotation"), root.list()!!.toList())
23+
}
24+
25+
@Test
26+
fun `an accepted playlist replaces the cache and returns paths inside it`() {
27+
val root = Files.createTempDirectory("rotation").toFile()
28+
val cache = File(root, "wallpaper_rotation").apply { mkdirs() }
29+
File(cache, "wallpaper_0.jpg").writeText("old")
30+
31+
val paths = replaceDirectoryContents(cache) { staging ->
32+
File(staging, "wallpaper_1.jpg").writeText("new")
33+
listOf("wallpaper_1.jpg")
34+
}
35+
36+
assertEquals(listOf(File(cache, "wallpaper_1.jpg").absolutePath), paths)
37+
assertFalse(File(cache, "wallpaper_0.jpg").exists())
38+
assertEquals("new", File(cache, "wallpaper_1.jpg").readText())
39+
assertEquals(listOf("wallpaper_rotation"), root.list()!!.toList())
40+
}
41+
42+
@Test
43+
fun `scheduled rotation waits one interval because start already applied a wallpaper`() {
44+
val request = WallpaperRotationScheduler.rotationRequest(intervalMinutes = 30, requiresCharging = true)
45+
46+
assertEquals(TimeUnit.MINUTES.toMillis(30), request.workSpec.initialDelay)
47+
assertEquals(TimeUnit.MINUTES.toMillis(30), request.workSpec.intervalDuration)
48+
assertTrue(request.workSpec.constraints.requiresCharging())
49+
}
50+
}

0 commit comments

Comments
 (0)