Compare commits

...
5 Commits
Author SHA1 Message Date
YaqiongWu 073df232f2 fix(import): skip files trashed under their old display name
HyperOS renames a deleted file to .trashed-… but keeps reporting its old display name, so only the document id shows it.
2026-11-18 08:27:33 -08:00
Anthonyy232 16f5a1682b docs: say that a rescan drops deleted folder images 2026-11-17 18:22:36 -08:00
YaqiongWu e7c6c5b850 fix(import): drop deleted and trashed images on folder refresh
Some galleries delete a photo by renaming it to .trashed-… in place. A rescan imported those as new wallpapers and kept the deleted originals.
2026-11-17 18:18:24 -08:00
Pbg4444 548bc9b32a fix: skip screen-off change if the screen comes back on 2026-11-17 11:41:30 -08:00
Anthonyy232 cb6e7b83be fix: retry the live wallpaper until its images can be read
Waiting for the provider to announce a change did not recover on a Galaxy Tab: nothing was announced, so the home screen stayed black. Retry on a timer instead, and test readability by opening the file.

Refs #646
2026-11-17 08:55:17 -08:00
14 changed files with 190 additions and 78 deletions

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ Paperize is an Android app that changes your home and lock screen wallpaper on a
<img src=".github/readme/feature-albums-light.png" alt="01. Albums, on rotation. The library with two albums, and an album open showing its wallpapers.">
</picture>
An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and once a day while a schedule is running, so new files join the rotation by themselves; **Refresh folder** rescans one straight away. Removing something from an album never touches the file on your device.
An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and once a day while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. Removing something from an album never touches the file on your device.
Supported formats: JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF and TIFF.
@@ -98,6 +98,27 @@ class DocumentAccessInstrumentedTest {
assertEquals(2, provider.queries)
}
@Test fun scanSkipsTrashedFilesButKeepsImagesInHiddenFolders() = runBlocking {
provider.answer = { uri ->
when (DocumentsContract.getDocumentId(uri)) {
"root" -> directoryCursor().apply {
addRow(arrayOf<Any>("trashed", ".trashed54970.jpg", "image/jpeg", 1L))
addRow(arrayOf<Any>("trash", ".Trash-123.png", "image/png", 2L))
addRow(arrayOf<Any>("primary:Pictures/.trashed-1797497267-old.jpg", "old.jpg", "image/jpeg", 5L))
addRow(arrayOf<Any>("primary:.trashed-1797497267-top.jpg", "top.jpg", "image/jpeg", 6L))
addRow(arrayOf<Any>("primary:Pictures/.walls", ".walls", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
addRow(arrayOf<Any>("plain", "photo.jpg", "image/jpeg", 3L))
}
"primary:Pictures/.walls" -> directoryCursor().apply {
addRow(arrayOf<Any>("primary:Pictures/.walls/wall.png", "wall.png", "image/png", 4L))
}
else -> directoryCursor()
}
}
val found = treeUri.scanFolderImages(context)
assertEquals(setOf("photo.jpg", "wall.png"), found.map { it.name }.toSet())
}
@Test fun failureInChildFolderDoesNotReturnPartialImport() = runBlocking {
provider.answer = { uri ->
if (DocumentsContract.getDocumentId(uri) == "root") directoryCursor().apply {
@@ -140,4 +140,32 @@ class AlbumRepositoryInstrumentedTest {
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true)
assertEquals(expected.drop(1), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
}
@Test fun syncFolderWallpapersRemovesOnlyThatFoldersMissingFilesAndAddsNewOnes() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(
wallpapers = (1..5).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
))
albums.addWallpapersToAlbum("album", listOf(testWallpaper("direct", "album").copy(uri = "content://photo-3")))
val scanned = listOf(1, 2, 4, 5, 6).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
val added = albums.syncFolderWallpapers("album", "folder", scanned)
assertEquals(1, added)
assertEquals(
listOf(1, 2, 4, 5, 6).map { "content://photo-$it" }.toSet(),
db.wallpaperDao().getUrisInCollection("album", "folder").toSet()
)
assertEquals(listOf("content://photo-3"), db.wallpaperDao().getUrisInCollection("album", null))
}
@Test fun syncFolderWallpapersKeepsRowsWhenScanIsEmpty() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(
wallpapers = listOf(testWallpaper("image-1", "album").copy(folderId = "folder", uri = "content://photo-1"))
))
assertEquals(0, albums.syncFolderWallpapers("album", "folder", emptyList()))
assertEquals(1, db.wallpaperDao().getUrisInCollection("album", "folder").size)
}
}
@@ -2,23 +2,14 @@ package com.anthonyla.paperize.core.util
import android.content.ContentResolver
import android.net.Uri
import android.provider.OpenableColumns
import java.util.UUID
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
fun Uri.isReadable(contentResolver: ContentResolver): Boolean {
if (scheme != ContentResolver.SCHEME_CONTENT) return false
return try {
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
cursor.moveToFirst()
} ?: false
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (_: Exception) {
// Fallback to opening the stream if the provider doesn't support the specific query
try {
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (_: Exception) {
false
}
false
}
}
@@ -14,6 +14,9 @@ interface WallpaperDao {
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId AND folderId IS :folderId")
suspend fun getUrisInCollection(albumId: String, folderId: String?): List<String>
@Query("DELETE FROM wallpapers WHERE albumId = :albumId AND folderId = :folderId AND uri IN (:uris)")
suspend fun deleteFolderWallpapersByUris(albumId: String, folderId: String, uris: List<String>): Int
@Query("SELECT COALESCE(MAX(displayOrder), -1) FROM wallpapers WHERE albumId = :albumId")
suspend fun getMaxOrder(albumId: String): Int
@@ -73,6 +73,30 @@ class AlbumRepositoryImpl @Inject constructor(
true
}
override suspend fun syncFolderWallpapers(
albumId: String,
folderId: String,
wallpapers: List<Wallpaper>,
onProgress: (Int, Int) -> Unit
): Int = database.withTransaction {
checkNotNull(albumDao.getAlbumById(albumId))
val scanned = wallpapers.mapTo(HashSet()) { it.uri }
// An empty scan can be an unavailable provider, so it removes nothing.
val stale = if (scanned.isEmpty()) emptyList()
else wallpaperDao.getUrisInCollection(albumId, folderId).filterNot { it in scanned }
var removed = 0
stale.chunked(WALLPAPER_BATCH_SIZE).forEach {
removed += wallpaperDao.deleteFolderWallpapersByUris(albumId, folderId, it)
}
val added = insertNewWallpapers(albumId, wallpapers, onProgress)
if (removed > 0) {
folderDao.updateFolderCover(folderId, wallpaperDao.getFolderCoverUri(folderId))
updateAlbumCoverIfNeeded(albumId)
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
}
added
}
private suspend fun insertNewWallpapers(
albumId: String,
wallpapers: List<Wallpaper>,
@@ -122,10 +122,14 @@ internal suspend fun Uri.scanFolderImages(context: Context, onProgress: (found:
currentCoroutineContext().ensureActive()
val documentId = cursor.getString(idColumn) ?: continue
if (!visitedDocuments.add(documentId)) continue
val name = cursor.getString(nameColumn) ?: continue
// Galleries rename deleted files in place: .trashed-…, .Trash-…
// HyperOS keeps reporting the old display name, so the id is checked too.
val fileName = documentId.substringAfterLast('/').substringAfterLast(':')
if (listOf(name, fileName).any { it.startsWith(".trash", ignoreCase = true) }) continue
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
pendingDirs.addLast(documentId)
} else {
val name = cursor.getString(nameColumn) ?: continue
val extension = name.substringAfterLast('.', "").lowercase()
if (extension in Constants.SUPPORTED_IMAGE_EXTENSIONS) {
results.add(
@@ -31,6 +31,14 @@ interface AlbumRepository {
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Boolean
/** Makes a folder match a complete scan of it. Returns the number of new images. */
suspend fun syncFolderWallpapers(
albumId: String,
folderId: String,
wallpapers: List<Wallpaper>,
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
): Int
suspend fun removeWallpapersFromAlbum(albumId: String, wallpaperIds: List<String>)
suspend fun removeFolderFromAlbum(albumId: String, folderId: String)
@@ -13,8 +13,8 @@ class RefreshFolderUseCase @Inject constructor(
suspend operator fun invoke(folderId: String): Int {
val folder = albumRepository.getFolderById(folderId).first() ?: return 0
val source = documents.readFolder(folder.uri)
return albumRepository.addWallpapersToAlbum(
folder.albumId, source.images.map { it.toWallpaper(folder.albumId, folderId) }
return albumRepository.syncFolderWallpapers(
folder.albumId, folderId, source.images.map { it.toWallpaper(folder.albumId, folderId) }
)
}
}
@@ -7,11 +7,8 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Configuration
import android.database.ContentObserver
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
@@ -24,7 +21,7 @@ import com.anthonyla.paperize.core.EmptyAlbumException
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.util.isValid
import com.anthonyla.paperize.core.util.isReadable
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.model.usesVisibleLiveTimer
@@ -129,14 +126,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
}
}
// Registered only while no wallpaper is readable, e.g. storage still mounting after boot.
private var watchingSource = false
private val sourceObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean) {
renderController.reloadCurrentArtwork()
}
}
override fun onCreate(surfaceHolder: SurfaceHolder) {
super.onCreate(surfaceHolder)
Log.d(TAG, "Engine created")
@@ -178,32 +167,19 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
val settings = settingsRepository.getScheduleSettings()
val albumId = settings.liveAlbumId ?: return EmptyImageLoader
var unreadable: Uri? = null
suspend fun nextReadable() = withContext(Dispatchers.IO) {
changeWallpaperUseCase.dequeueReadable(albumId, ScreenType.LIVE, settings.shuffleEnabled) { candidate ->
val uri = candidate.uri.toUri()
if (uri.isValid(contentResolver)) {
currentWallpaper = candidate
ContentUriImageLoader(contentResolver, uri, settings.liveScalingType)
} else {
unreadable = uri
null
return try {
val loader = withContext(Dispatchers.IO) {
changeWallpaperUseCase.dequeueReadable(albumId, ScreenType.LIVE, settings.shuffleEnabled) { candidate ->
val uri = candidate.uri.toUri()
if (uri.isReadable(contentResolver)) {
currentWallpaper = candidate
ContentUriImageLoader(contentResolver, uri, settings.liveScalingType)
} else {
null
}
}
}
}
return try {
var loader = nextReadable()
if (loader == null && !watchingSource) {
unreadable?.let(::watchSource)
// The source may have come back before the observer was registered.
loader = nextReadable()
}
if (loader == null) {
Log.w(TAG, "No readable wallpaper in album $albumId")
} else {
stopWatchingSource()
}
if (loader == null) Log.w(TAG, "No readable wallpaper in album $albumId")
loader
} catch (_: EmptyAlbumException) {
Log.w(TAG, "No wallpapers in album $albumId")
@@ -211,22 +187,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
}
}
/** A provider notifies its documents when their root changes, e.g. a volume is mounted. */
private fun watchSource(uri: Uri) {
try {
contentResolver.registerContentObserver(uri, false, sourceObserver)
watchingSource = true
} catch (e: SecurityException) {
Log.w(TAG, "Cannot watch $uri", e)
}
}
private fun stopWatchingSource() {
if (!watchingSource) return
contentResolver.unregisterContentObserver(sourceObserver)
watchingSource = false
}
private fun observeSettings() {
engineScope.launch {
combine(
@@ -328,7 +288,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
override fun onDestroy() {
engines -= this
applicationContext.unregisterReceiver(screenOffReceiver)
stopWatchingSource()
renderer.cancelLoading()
@@ -357,7 +316,11 @@ class PaperizeLiveWallpaperService : GLWallpaperService() {
val settings = settingsRepository.getScheduleSettings()
if (settings.liveEffects.enableChangeOnScreenOff) {
// Some skins still draw the wallpaper through their screen-off animation; an always-on display never hides it.
withTimeoutOrNull(2.seconds) { engineVisible.first { !it } }
val hidden = withTimeoutOrNull(2.seconds) { engineVisible.first { !it } } != null
if (!hidden && getSystemService(PowerManager::class.java).isInteractive) {
Log.d(TAG, "Screen turned back on before wallpaper hid - skipping change")
return@launch
}
Log.d(TAG, "Screen off - changing wallpaper")
renderController.forceReloadCurrentArtwork()
}
@@ -2,12 +2,17 @@ package com.anthonyla.paperize.service.livewallpaper.renderer
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
/**
* All calls run on the engine's main dispatcher; its scope owns cancellation.
* [openCurrentArtwork] returns null while no wallpaper is readable, which keeps what is shown.
* [openCurrentArtwork] returns null while no wallpaper is readable (e.g. storage still mounting
* after boot), which keeps what is shown. A failed selection is retried with a growing delay.
*/
class PaperizeRenderController(
private val queueWallpaper: (ImageLoader, Boolean) -> Unit,
@@ -22,6 +27,8 @@ class PaperizeRenderController(
private var isLoading = false
private var hasPendingReload = false
private var retryJob: Job? = null
private var retryDelay = FIRST_RETRY_DELAY
/** Deferred until the wallpaper is visible and any running selection has finished. */
fun reloadCurrentArtwork() {
@@ -41,15 +48,22 @@ class PaperizeRenderController(
}
private fun executeReload(skipCrossfade: Boolean = false) {
retryJob?.cancel()
isLoading = true
controllerScope.launch {
try {
val loader = openCurrentArtwork()
if (loader != null && isActive && !hasPendingReload) {
queueWallpaper(loader, skipCrossfade)
if (loader == null) {
retryLater()
} else {
retryDelay = FIRST_RETRY_DELAY
if (isActive && !hasPendingReload) queueWallpaper(loader, skipCrossfade)
}
} catch (e: Exception) {
if (isActive) Log.e("PaperizeRenderController", "Error reloading wallpaper", e)
if (isActive) {
Log.e("PaperizeRenderController", "Error reloading wallpaper", e)
retryLater()
}
} finally {
isLoading = false
if (isActive && hasPendingReload && visible) {
@@ -58,4 +72,17 @@ class PaperizeRenderController(
}
}
}
private fun retryLater() {
retryJob = controllerScope.launch {
delay(retryDelay)
retryDelay = (retryDelay * 2).coerceAtMost(MAX_RETRY_DELAY)
reloadCurrentArtwork()
}
}
private companion object {
val FIRST_RETRY_DELAY = 1.seconds
val MAX_RETRY_DELAY = 1.minutes
}
}
@@ -22,9 +22,9 @@ class RefreshFolderUseCaseTest {
coEvery { documents.readFolder("tree", any()) } returns SourceFolder("Photos", listOf(
SourceImage("existing", "old.png", 1L), SourceImage("new", "new.png", 2L)
))
coEvery { albums.addWallpapersToAlbum("album", any(), any()) } returns 1
coEvery { albums.syncFolderWallpapers("album", "folder", any(), any()) } returns 1
assertEquals(1, refresh("folder"))
coVerify { albums.addWallpapersToAlbum("album", match {
coVerify { albums.syncFolderWallpapers("album", "folder", match {
it.size == 2 && it.all { image -> image.albumId == "album" && image.folderId == "folder" }
}, any()) }
}
@@ -5,6 +5,7 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Test
@@ -48,4 +49,46 @@ class PaperizeRenderControllerTest {
assertEquals(listOf(loader to false), uploads)
assertEquals(1, selections)
}
@Test fun `selection with nothing readable is retried until it succeeds`() = runTest {
val uploads = mutableListOf<Pair<ImageLoader, Boolean>>()
val loader = mockk<ContentUriImageLoader>()
var selections = 0
val controller = PaperizeRenderController({ loader, skip -> uploads.add(loader to skip) }, backgroundScope) {
if (selections++ < 2) null else loader
}
controller.visible = true
controller.reloadCurrentArtwork()
runCurrent()
assertEquals(1, selections)
advanceTimeBy(1_001)
assertEquals(2, selections)
advanceTimeBy(1_001)
assertEquals(2, selections)
advanceTimeBy(1_000)
assertEquals(listOf(loader to false), uploads)
advanceTimeBy(120_000)
assertEquals(3, selections)
}
@Test fun `retry while hidden waits until visible`() = runTest {
val uploads = mutableListOf<Pair<ImageLoader, Boolean>>()
val loader = mockk<ContentUriImageLoader>()
var selections = 0
val controller = PaperizeRenderController({ loader, skip -> uploads.add(loader to skip) }, backgroundScope) {
if (selections++ == 0) null else loader
}
controller.visible = true
controller.reloadCurrentArtwork()
runCurrent()
controller.visible = false
advanceTimeBy(60_000)
assertEquals(1, selections)
controller.visible = true
runCurrent()
assertEquals(listOf(loader to false), uploads)
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
Paperize changes your home and lock screen wallpaper on a schedule, from albums you build out of your own images and folders. It works offline and has no internet permission.
Albums: an album holds single images, whole folders, or both. Folders are rescanned when you open the app, and daily while a schedule is running, so new files join the rotation by themselves.
Albums: an album holds single images, whole folders, or both. Folders are rescanned when you open the app, and daily while a schedule is running, so new files join the rotation and deleted ones leave it by themselves.
Schedule: turn on the lock screen, the home screen or both, and pick an album for each. One interval covers both screens, from 15 minutes to 30 days, or each screen can have its own. Wallpapers go in order or shuffled.