diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
index c2fa9f7..e69da87 100644
--- a/.github/FUNDING.yml
+++ b/.github/FUNDING.yml
@@ -1,14 +1 @@
-# These are supported funding model platforms
-
github: Anthonyy232
-patreon: # Replace with a single Patreon username
-open_collective: # Replace with a single Open Collective username
-ko_fi: # Replace with a single Ko-fi username
-tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
-community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
-liberapay: # Replace with a single Liberapay username
-issuehunt: # Replace with a single IssueHunt username
-lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
-polar: # Replace with a single Polar username
-buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
-custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
diff --git a/.github/workflows/android-release.yml b/.github/workflows/android-release.yml
index 610aaa0..995690e 100644
--- a/.github/workflows/android-release.yml
+++ b/.github/workflows/android-release.yml
@@ -1,23 +1,3 @@
-# ===================================================================
-# Paperize CI/CD Pipeline
-#
-# Automates the testing, building and release process for the Paperize Android application.
-#
-# Workflow Architecture:
-# 1. Test: Runs unit tests and Android lint to ensure code quality.
-# 2. Build: Compiles and signs the release APK (depends on test passing).
-# 3. Release: Publishes the APK to a draft GitHub Release, but only for version tags.
-#
-# Triggering Conditions:
-# - On push to `master`:
-# - Executes the `test` and `build` jobs.
-# - Produces a versioned build artifact for testing and internal distribution.
-# - On push of a tag (e.g., `v1.2.3`):
-# - Executes all jobs: `test`, `build` and `release`.
-# - Creates a formal, versioned draft release on GitHub with the signed APK attached.
-# - On pull requests to `master`:
-# - Executes only the `test` job to validate changes before merge.
-# ===================================================================
name: Paperize CI/CD Pipeline
on:
@@ -31,11 +11,6 @@ permissions:
contents: read
jobs:
- # ===================================================================
- # JOB: test
- #
- # Runs unit tests and Android lint to ensure code quality before building.
- # ===================================================================
test:
name: Run Unit Tests
runs-on: ubuntu-latest
@@ -59,13 +34,6 @@ jobs:
- name: Run Android lint
run: ./gradlew :app:lintDebug
- # ===================================================================
- # JOB: build
- #
- # Compiles, signs, and packages the release APK. This job produces a
- # versioned artifact that is used for both internal testing and the final release.
- # Only runs after tests pass.
- # ===================================================================
build:
name: Build Signed APK
runs-on: ubuntu-latest
@@ -83,11 +51,9 @@ jobs:
cache: gradle
- name: Grant execute permission for gradlew
- # The gradlew wrapper requires execute permissions to run on the Linux-based runner.
run: chmod +x gradlew
- name: Decode Base64 Keystore
- # Reconstructs the binary .jks keystore file from the Base64 encoded secret.
env:
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
run: |
@@ -102,9 +68,6 @@ jobs:
run: ./gradlew assembleRelease
- name: Get Version Name
- # Determines the application version for artifact naming.
- # - For tag pushes (e.g., 'v1.2.3'), it uses the tag name directly.
- # - For master branch pushes, it parses the `versionName` from the app's build.gradle.kts file.
id: get_version
shell: bash
run: |
@@ -123,20 +86,12 @@ jobs:
"app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk"
- name: Upload APK as a build artifact
- # Archives the generated APK with a dynamic, versioned name. This artifact is essential
- # for passing the APK file to the subsequent `release` job.
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: paperize-${{ steps.get_version.outputs.VERSION_NAME }}
path: app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk
if-no-files-found: error
- # ===================================================================
- # JOB: release
- #
- # Creates a draft GitHub Release and attaches the signed APK. This job is
- # conditional and will only execute for pushes that include a version tag.
- # ===================================================================
release:
name: Create GitHub Release
runs-on: ubuntu-latest
@@ -146,8 +101,6 @@ jobs:
contents: write
steps:
- name: Download signed APK artifact
- # Downloads the versioned artifact produced by the `build` job. The pattern ensures
- # it finds the correct artifact regardless of the specific version number.
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
pattern: paperize-v*
@@ -155,8 +108,6 @@ jobs:
merge-multiple: true
- name: Create Draft Release
- # Publishes a new release to GitHub. `draft: true` ensures the release is not made
- # public until it has been manually reviewed and published.
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3
with:
files: ./apk-artifact/paperize-v*.apk
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0737ce9..0ffe2bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,18 +1,22 @@
-## Unreleased
+## v4.2.0
-- Made imports cancellable, moved file-provider queries off the UI thread, and
- added visible errors for inaccessible selections and incomplete folder scans.
-- Prevented duplicate imports and fixed folder wallpaper source metadata.
-- Preserved albums during temporary storage-provider failures and scoped missing
- wallpaper cleanup to the album being refreshed.
-- Made album deletion wait for completion and clear saved album selections;
- added confirmation and failure feedback when removing selected items.
-- Added import actions to empty albums, enabled folder sorting, and made the
- active sort order visible and accessible. Wallpaper thumbnails now expose file names and selection state to screen readers.
-- Added manual folder refresh with progress and error feedback, sharing batch
- imports and duplicate detection with the daily background refresh.
-- Updated folder covers atomically during imports and consistently selected
- covers by display order.
+### Library and albums
+- Make image imports and folder refreshes cancellable and transactional, with accurate progress and useful failure feedback.
+- Preserve library entries when a document provider is temporarily unavailable, avoid duplicate imports, and refresh folder metadata and covers consistently.
+- Preserve library data when upgrading older database versions.
+- Improve album deletion, selection cleanup, sorting, and empty-album actions.
+
+### Wallpaper reliability
+- Keep home and lock schedules consistent across restarts, manual changes, and settings edits.
+- Prevent rapid settings edits from overwriting newer album selections or pause/resume actions.
+- Share wallpaper application and rendering between manual changes and scheduled jobs, with consistent failure recovery.
+- Correct static image sizing, thin-image decoding, and FIT/STRETCH fallback rendering.
+
+### Live wallpaper and interface
+- Fix crossfade completion and preserve pending wallpaper changes when folding, resizing, or recreating the rendering surface.
+- Improve OpenGL resource cleanup, blur rendering, and memory use.
+- Respect animation settings in previews and improve sorting accessibility and settings feedback.
+- Remove redundant UI, unused dependencies, obsolete compatibility code, and low-value tests and comments.
## v4.1.1
diff --git a/README.md b/README.md
index 6ba4282..54c7793 100644
--- a/README.md
+++ b/README.md
@@ -51,20 +51,32 @@ Help translate Paperize into your language! Currently, most translations are pro
| **Dependency Injection** | [Dagger Hilt](https://dagger.dev/hilt/) |
| **Database** | [Room](https://developer.android.com/training/data-storage/room) |
| **Image Loading** | [Coil](https://coil-kt.github.io/coil/) |
-| **Animations** | [Lottie](https://github.com/airbnb/lottie) |
View all dependencies
- [Zoomable](https://github.com/usuiat/Zoomable) — Zoomable and pannable views
-- [DocumentFileCompat](https://github.com/ItzNotABug/DocumentFileCompat) — Efficient DocumentFile wrapper
-- [LazyColumnScrollbar](https://github.com/nanihadesuka/LazyColumnScrollbar) — Compose scrollbar library
-- [compose-collapsing-toolbar](https://github.com/onebone/compose-collapsing-toolbar) — Collapsing toolbar for Compose
---
+## Architecture
+
+- `AlbumRepository` owns library mutations. Imports, reordering, removal, covers,
+ and queue invalidation use Room transactions; provider scans run outside them.
+- `DocumentSource` isolates Android permissions and document-provider queries.
+ Import and refresh use cases consume metadata without accessing Android providers.
+- `WallpaperRepository` owns rotation queues and current-wallpaper records.
+ Queue creation checks and writes in one transaction, including synchronized screens.
+- `WallpaperController` shares static wallpaper application between the service
+ and worker. Callers hold `WallpaperChangeLock` through application and schedule
+ updates. `WallpaperRenderer` owns image processing; the controller recycles applied bitmaps.
+- Operation `Result` values contain success or failure. Progress belongs to UI state,
+ and coroutine cancellation propagates instead of becoming a failure result.
+- Room migrations preserve versions 1–3 when upgrading to version 4. New schema
+ changes must include a migration; destructive fallback is disabled.
+
## Building from Source
### Prerequisites
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 9e6b026..ce0eabb 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -28,12 +28,14 @@ android {
}
}
+ sourceSets.getByName("androidTest").assets.directories.add("$projectDir/schemas")
+
defaultConfig {
applicationId = "com.anthonyla.paperize"
minSdk = 31
targetSdk = 36
- versionCode = 56
- versionName = "4.1.1"
+ versionCode = 57
+ versionName = "4.2.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
@@ -60,7 +62,6 @@ android {
buildFeatures {
compose = true
- viewBinding = true
buildConfig = true
}
@@ -93,11 +94,9 @@ dependencies {
implementation(libs.androidx.material3)
implementation(libs.google.material)
implementation(libs.androidx.navigation.compose)
- implementation(libs.androidx.material)
implementation(libs.coil.compose)
implementation(libs.coil.gif)
implementation(libs.coil.svg)
- implementation(libs.androidx.datastore)
implementation(libs.androidx.datastore.preferences)
implementation(libs.androidx.material.icons.extended)
implementation(libs.androidx.hilt.navigation.compose)
@@ -109,10 +108,7 @@ dependencies {
implementation(libs.zoomable)
implementation(libs.androidx.work.runtime.ktx)
implementation(libs.androidx.hilt.work)
- implementation(libs.lottie.compose)
- implementation(libs.accompanist.permissions)
implementation(libs.androidx.foundation)
- implementation(libs.lazycolumnscrollbar)
implementation(libs.androidx.profileinstaller)
implementation(libs.reorderable)
testImplementation(libs.junit)
@@ -132,5 +128,4 @@ dependencies {
ksp(libs.androidx.room.compiler)
implementation(libs.androidx.room.ktx)
implementation (libs.kotlinx.serialization.json)
- implementation(libs.toolbar.compose)
}
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
index 72e7fa2..2cc9c2f 100644
--- a/app/proguard-rules.pro
+++ b/app/proguard-rules.pro
@@ -1,62 +1,2 @@
-# Add project specific ProGuard rules here.
-# You can control the set of applied configuration files using the
-# proguardFiles setting in build.gradle.
-#
-# For more details, see
-# http://developer.android.com/guide/developing/tools/proguard.html
-
-# If your project uses WebView with JS, uncomment the following
-# and specify the fully qualified class name to the JavaScript interface
-# class:
-#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
-# public *;
-#}
-
-# Uncomment this to preserve the line number information for
-# debugging stack traces.
+# Library consumer rules preserve their runtime entry points. Keep release crash locations.
-keepattributes SourceFile,LineNumberTable
-
-# If you keep the line number information, uncomment this to
-# hide the original source file name.
-#-renamesourcefileattribute SourceFile
--keepattributes Signature
--keep class kotlin.coroutines.Continuation
--keep class androidx.datastore.*.** {*;}
-
-# Keep domain models for serialization
--keepclassmembers class com.anthonyla.paperize.domain.model.Album {
- !transient ;
-}
--keepclassmembers class com.anthonyla.paperize.domain.model.Wallpaper {
- !transient ;
-}
--keepclassmembers class com.anthonyla.paperize.domain.model.Folder {
- !transient ;
-}
-
-# Keep database entities
--keep class com.anthonyla.paperize.data.database.entities.** { *; }
-
-# Keep wallpaper service
--keep class com.anthonyla.paperize.service.wallpaper.WallpaperChangeService { *; }
--keep class com.anthonyla.paperize.service.wallpaper.WallpaperChangeService$* { *; }
-
-# Keep enums
--keep class com.anthonyla.paperize.core.WallpaperSourceType { *; }
--keep class com.anthonyla.paperize.core.ScreenType { *; }
--keep class com.anthonyla.paperize.core.ScalingType { *; }
-
-# Keep navigation routes for serialization
--keep class com.anthonyla.paperize.presentation.common.navigation.** { *; }
-
-# Keep Hilt generated classes (more specific to avoid overly broad rules)
--keep,allowobfuscation,allowshrinking @dagger.hilt.android.lifecycle.HiltViewModel class *
--keep,allowobfuscation,allowshrinking class * extends androidx.lifecycle.ViewModel
--keep class dagger.hilt.android.** { *; }
--keep class dagger.hilt.internal.** { *; }
--keep class javax.inject.** { *; }
-
-# Keep Room database
--keep class * extends androidx.room.RoomDatabase
--keep @androidx.room.Entity class *
--dontwarn androidx.room.paging.**
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/core/util/DocumentAccessInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/core/util/DocumentAccessInstrumentedTest.kt
index 578f3a7..b06e7ee 100644
--- a/app/src/androidTest/java/com/anthonyla/paperize/core/util/DocumentAccessInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/anthonyla/paperize/core/util/DocumentAccessInstrumentedTest.kt
@@ -19,7 +19,6 @@ import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.data.database.PaperizeDatabase
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
-import com.anthonyla.paperize.data.repository.WallpaperRepositoryImpl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
@@ -127,24 +126,53 @@ class DocumentAccessInstrumentedTest {
assertEquals(0L, cancelled.count)
}
- @Test fun cleanupCountsDuplicateRowsAndPreservesOtherAlbums() = runBlocking {
+ @Test fun cleanupHandlesDuplicateUrisAndConcurrentReorderingWithoutTouchingOtherAlbums() = runBlocking {
val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build()
try {
- db.albumDao().insertAlbum(AlbumEntity("one", "One", null, 0L, 0L))
+ db.albumDao().insertAlbum(AlbumEntity("one", "One", documentUri.toString(), 0L, 0L))
db.albumDao().insertAlbum(AlbumEntity("two", "Two", null, 0L, 0L))
val uri = documentUri.toString()
val missing = WallpaperEntity("first", "one", null, uri, "photo.png", 0L)
- // More than one page of duplicate URIs caught the old offset/counting bug.
- db.wallpaperDao().insertWallpapers((0..104).map { missing.copy(id = "missing-$it") })
+ db.wallpaperDao().insertWallpapers((0..504).map { missing.copy(id = "missing-$it") })
db.wallpaperDao().insertWallpaper(missing.copy(id = "other-album", albumId = "two"))
- provider.answer = { MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME)) }
- val repository = WallpaperRepositoryImpl(context, db.wallpaperDao(), db.wallpaperQueueDao(), db.wallpaperCurrentDao())
- assertEquals(Result.Success(105), repository.validateAndRemoveInvalidWallpapers("one"))
+ provider.answer = {
+ if (provider.queries == 1) {
+ // Move an unread image before the first page while that page is being scanned.
+ db.openHelper.writableDatabase.execSQL("UPDATE wallpapers SET displayOrder = -1 WHERE id = 'missing-99'")
+ }
+ MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME))
+ }
+ val repository = com.anthonyla.paperize.data.repository.AlbumRepositoryImpl(
+ com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
+ assertEquals(Result.Success(505), repository.pruneMissingEntries("one"))
assertEquals(0, db.wallpaperDao().getWallpaperCountByAlbum("one"))
+ assertNull(db.albumDao().getAlbumById("one")?.coverUri)
assertNotNull(db.wallpaperDao().getWallpaperById("other-album"))
} finally { db.close() }
}
+ @Test fun cancelledCleanupDoesNotLeavePartialDeletions() = runBlocking {
+ val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build()
+ try {
+ db.albumDao().insertAlbum(AlbumEntity("album", "Album", "content://test/document/first"))
+ db.wallpaperDao().insertWallpapers(listOf("first", "second").map {
+ WallpaperEntity(it, "album", null, "content://test/document/$it", "$it.png", 0L)
+ })
+ provider.answer = {
+ if (provider.queries == 2) throw kotlinx.coroutines.CancellationException()
+ MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME))
+ }
+ val repository = com.anthonyla.paperize.data.repository.AlbumRepositoryImpl(
+ com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
+ try {
+ repository.pruneMissingEntries("album")
+ fail("Expected cancellation")
+ } catch (_: kotlinx.coroutines.CancellationException) { }
+ assertEquals(2, db.wallpaperDao().getWallpaperCountByAlbum("album"))
+ assertEquals("content://test/document/first", db.albumDao().getAlbumById("album")?.coverUri)
+ } finally { db.close() }
+ }
+
private fun directoryCursor() = MatrixCursor(arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/core/util/WallpaperUtilInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/core/util/WallpaperUtilInstrumentedTest.kt
index 7567900..995b117 100644
--- a/app/src/androidTest/java/com/anthonyla/paperize/core/util/WallpaperUtilInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/anthonyla/paperize/core/util/WallpaperUtilInstrumentedTest.kt
@@ -33,6 +33,27 @@ class WallpaperUtilInstrumentedTest {
files.forEach(File::delete)
}
+ @Test
+ fun narrowImagesRetainAtLeastOnePixelInBothDecodePaths() {
+ val image = createJpeg(width = 1, height = 1000)
+ val uri = Uri.fromFile(image)
+ for (scaling in listOf(ScalingType.FIT, ScalingType.NONE)) {
+ val live = com.anthonyla.paperize.service.livewallpaper.renderer.ContentUriImageLoader(
+ context.contentResolver, uri, scaling
+ ).load(20, 20)
+ assertNotNull(live)
+ assertEquals(1, live?.width)
+ assertEquals(if (scaling == ScalingType.FIT) 20 else 40, live?.height)
+ live?.recycle()
+
+ val static = retrieveBitmap(context, uri, 20, 20, scaling)
+ assertNotNull(static)
+ assertEquals(20, static?.width)
+ assertEquals(20, static?.height)
+ static?.recycle()
+ }
+ }
+
@Test
fun imageDecoderAppliesExifRotation() {
val image = createJpeg(width = 40, height = 20)
@@ -108,6 +129,29 @@ class WallpaperUtilInstrumentedTest {
}
}
+ @Test
+ fun fallbackBitmapsUseTheRequestedScalingAndCenterCrop() {
+ ScalingType.entries.forEach { scaling ->
+ val source = mutableBitmap(80, 40, Color.RED)
+ for (y in 0 until 40) {
+ for (x in 20 until 60) source.setPixel(x, y, Color.GREEN)
+ }
+ val result = finalizeToCanvas(source, 40, 80, scaling)
+ try {
+ assertTrue(source.isRecycled)
+ assertEquals(40, result.width)
+ assertEquals(80, result.height)
+ assertEquals("Center for $scaling", Color.GREEN, result.getPixel(20, 40))
+ val top = if (scaling == ScalingType.FIT || scaling == ScalingType.NONE) Color.BLACK else Color.GREEN
+ assertEquals("Top for $scaling", top, result.getPixel(20, 0))
+ val side = if (scaling == ScalingType.FIT || scaling == ScalingType.STRETCH) Color.RED else Color.GREEN
+ assertEquals("Side for $scaling", side, result.getPixel(2, 40))
+ } finally {
+ result.recycle()
+ }
+ }
+ }
+
@Test
fun android17FoldableSizingIncludesInactiveBuiltInPanel() {
assumeTrue(Build.VERSION.SDK_INT >= 37)
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/data/database/LibraryMigrationInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/data/database/LibraryMigrationInstrumentedTest.kt
new file mode 100644
index 0000000..6f225c8
--- /dev/null
+++ b/app/src/androidTest/java/com/anthonyla/paperize/data/database/LibraryMigrationInstrumentedTest.kt
@@ -0,0 +1,79 @@
+package com.anthonyla.paperize.data.database
+
+import android.content.Context
+import android.database.sqlite.SQLiteDatabase
+import androidx.room.Room
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.platform.app.InstrumentationRegistry
+import com.anthonyla.paperize.core.ScreenType
+import kotlinx.coroutines.runBlocking
+import org.json.JSONObject
+import org.junit.Assert.*
+import org.junit.Test
+
+class LibraryMigrationInstrumentedTest {
+ private val context = ApplicationProvider.getApplicationContext()
+
+ @Test fun everyLegacyVersionPreservesLibraryAndQueue() = runBlocking {
+ for (version in 1..3) {
+ val name = "migration-test-$version"
+ context.deleteDatabase(name)
+ try {
+ createLegacyDatabase(name, version)
+ val db = Room.databaseBuilder(context, PaperizeDatabase::class.java, name)
+ .addMigrations(*LIBRARY_MIGRATIONS).build()
+ try {
+ assertEquals("My album", db.albumDao().getAlbumById("album")?.name)
+ assertEquals("content://image", db.albumDao().getAlbumById("album")?.coverUri)
+ val image = db.wallpaperDao().getWallpaperById("image")!!
+ assertEquals("folder", image.folderId)
+ assertEquals("photo.jpg", image.fileName)
+ assertEquals(7, image.displayOrder)
+ assertEquals(42L, image.addedAt)
+ assertEquals("content://image", db.folderDao().getFolderById("folder")?.coverUri)
+ assertEquals(listOf("image"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
+ assertEquals(if (version >= 3) "image" else null, db.wallpaperCurrentDao().getCurrentWallpaper("album", ScreenType.HOME)?.id)
+ db.openHelper.readableDatabase.query("PRAGMA foreign_key_check").use { assertEquals(0, it.count) }
+ db.albumDao().deleteAlbumById("album")
+ assertNull(db.wallpaperDao().getWallpaperById("image"))
+ assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
+ } finally { db.close() }
+ } finally { context.deleteDatabase(name) }
+ }
+ }
+
+ private fun createLegacyDatabase(name: String, version: Int) {
+ val schema = InstrumentationRegistry.getInstrumentation().context.assets
+ .open("com.anthonyla.paperize.data.database.PaperizeDatabase/4.json")
+ .bufferedReader().use { JSONObject(it.readText()).getJSONObject("database").getJSONArray("entities") }
+ val path = context.getDatabasePath(name)
+ path.parentFile!!.mkdirs()
+ SQLiteDatabase.openOrCreateDatabase(path, null).use { db ->
+ db.setForeignKeyConstraintsEnabled(true)
+ for (index in 0 until schema.length()) {
+ val entity = schema.getJSONObject(index)
+ val table = entity.getString("tableName")
+ if (table == "wallpaper_current" && version < 3) continue
+ var create = entity.getString("createSql").replace("\${TABLE_NAME}", table)
+ // Verified against the version 1, 2 and 3 entities in Git history.
+ if (table == "wallpapers") {
+ create = if (version == 1) create.replace("`mediaType` TEXT NOT NULL, ", "")
+ else create.replace("PRIMARY KEY(`id`)", "`cropOffsetX` REAL, `cropOffsetY` REAL, `cropScale` REAL, PRIMARY KEY(`id`)")
+ }
+ db.execSQL(create)
+ val indices = entity.optJSONArray("indices")
+ if (indices != null) for (i in 0 until indices.length()) {
+ db.execSQL(indices.getJSONObject(i).getString("createSql").replace("\${TABLE_NAME}", table))
+ }
+ }
+ db.execSQL("INSERT INTO albums VALUES ('album', 'My album', 'content://image', 1, 2)")
+ db.execSQL("INSERT INTO folders (id, albumId, name, uri, coverUri, dateModified, displayOrder, addedAt) VALUES ('folder', 'album', 'Photos', 'content://tree', 'content://image', 3, 0, 4)")
+ val mediaColumn = if (version > 1) ", mediaType" else ""
+ val mediaValue = if (version > 1) ", 'IMAGE'" else ""
+ db.execSQL("INSERT INTO wallpapers (id, albumId, folderId, uri, fileName, dateModified, displayOrder, sourceType, addedAt$mediaColumn) VALUES ('image', 'album', 'folder', 'content://image', 'photo.jpg', 5, 7, 'FOLDER', 42$mediaValue)")
+ db.execSQL("INSERT INTO wallpaper_queue VALUES (1, 'album', 'image', 'HOME', 2, 6)")
+ if (version >= 3) db.execSQL("INSERT INTO wallpaper_current VALUES ('album', 'HOME', 'image', 9)")
+ db.version = version
+ }
+ }
+}
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/data/datastore/PreferencesManagerInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/data/datastore/PreferencesManagerInstrumentedTest.kt
new file mode 100644
index 0000000..a742a10
--- /dev/null
+++ b/app/src/androidTest/java/com/anthonyla/paperize/data/datastore/PreferencesManagerInstrumentedTest.kt
@@ -0,0 +1,89 @@
+package com.anthonyla.paperize.data.datastore
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.anthonyla.paperize.core.ScreenType
+import com.anthonyla.paperize.core.ScalingType
+import com.anthonyla.paperize.core.WallpaperMode
+import com.anthonyla.paperize.domain.model.ScheduleSettings
+import com.anthonyla.paperize.domain.model.WallpaperEffects
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.launch
+import org.junit.Assert.*
+import org.junit.Test
+
+class PreferencesManagerInstrumentedTest {
+ @Test fun concurrentScheduleEditsReadTheLatestValueWithoutLosingSelections() = runBlocking {
+ val preferences = PreferencesManager(ApplicationProvider.getApplicationContext())
+ val previousSettings = preferences.getScheduleSettings()
+ try {
+ val initial = ScheduleSettings(homeAlbumId = "home", homeIntervalMinutes = 30)
+ preferences.updateScheduleSettings(initial)
+ coroutineScope {
+ repeat(20) {
+ launch {
+ preferences.updateScheduleSettings { current ->
+ current.copy(homeIntervalMinutes = current.homeIntervalMinutes + 1)
+ }
+ }
+ }
+ launch { preferences.updateHomeAlbumId("new-home") }
+ }
+ assertEquals(initial.copy(homeAlbumId = "new-home", homeIntervalMinutes = 50), preferences.getScheduleSettings())
+ } finally {
+ preferences.updateScheduleSettings(previousSettings)
+ }
+ }
+
+ @Test fun resettingSchedulesPreservesAppearanceAndWallpaperMode() = runBlocking {
+ val preferences = PreferencesManager(ApplicationProvider.getApplicationContext())
+ val previousSettings = preferences.getScheduleSettings()
+ val previousMode = preferences.getWallpaperMode()
+ val appearance = preferences.getAppSettings()
+ try {
+ preferences.updateWallpaperMode(WallpaperMode.LIVE)
+ val effects = WallpaperEffects(
+ enableBlur = true, blurPercentage = 30, enableDarken = true, darkenPercentage = 20,
+ enableVignette = true, vignettePercentage = 40, enableGrayscale = true, grayscalePercentage = 50,
+ enableDoubleTap = true, enableChangeOnScreenOff = true, enableParallax = true, parallaxIntensity = 60
+ )
+ preferences.updateScheduleSettings(ScheduleSettings(
+ enableChanger = true, separateSchedules = true, shuffleEnabled = true,
+ homeEnabled = true, lockEnabled = true, homeAlbumId = "home", lockAlbumId = "lock", liveAlbumId = "live",
+ homeIntervalMinutes = 25, lockIntervalMinutes = 35, liveIntervalMinutes = 45,
+ homeScalingType = ScalingType.FIT, lockScalingType = ScalingType.STRETCH, liveScalingType = ScalingType.NONE,
+ homeScrollingEnabled = true, homeEffects = effects, lockEffects = effects, liveEffects = effects,
+ adaptiveBrightness = true
+ ))
+ preferences.clearScheduleSettings()
+ assertEquals(ScheduleSettings(), preferences.getScheduleSettings())
+ assertEquals(appearance, preferences.getAppSettings())
+ assertEquals(WallpaperMode.LIVE, preferences.getWallpaperMode())
+ } finally {
+ preferences.updateScheduleSettings(previousSettings)
+ preferences.updateWallpaperMode(previousMode)
+ }
+ }
+
+ @Test fun clearingAnEmptyAlbumPreservesNewSelectionsAndOtherSettings() = runBlocking {
+ val preferences = PreferencesManager(ApplicationProvider.getApplicationContext())
+ val previousSettings = preferences.getScheduleSettings()
+ val previousMode = preferences.getWallpaperMode()
+ try {
+ preferences.updateWallpaperMode(WallpaperMode.STATIC)
+ val settings = ScheduleSettings(enableChanger = true, homeEnabled = true, lockEnabled = true,
+ homeAlbumId = "new-home", lockAlbumId = "lock", homeIntervalMinutes = 75)
+ preferences.updateScheduleSettings(settings)
+ preferences.clearEmptyAlbumSelection("old-home", ScreenType.HOME)
+ assertEquals(settings, preferences.getScheduleSettings())
+ preferences.clearEmptyAlbumSelection("new-home", ScreenType.HOME)
+ assertEquals(settings.copy(homeAlbumId = null), preferences.getScheduleSettings())
+ preferences.clearEmptyAlbumSelection("lock", ScreenType.LOCK)
+ assertEquals(settings.copy(homeAlbumId = null, lockAlbumId = null, enableChanger = false), preferences.getScheduleSettings())
+ } finally {
+ preferences.updateScheduleSettings(previousSettings)
+ preferences.updateWallpaperMode(previousMode)
+ }
+ }
+}
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt
index 5dd9f91..e02e0b6 100644
--- a/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/anthonyla/paperize/data/repository/AlbumRepositoryInstrumentedTest.kt
@@ -11,7 +11,8 @@ import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.mapper.toEntity
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
-import dagger.Lazy
+import kotlinx.coroutines.async
+import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
@@ -24,15 +25,15 @@ import org.junit.runner.RunWith
class AlbumRepositoryInstrumentedTest {
private val context = ApplicationProvider.getApplicationContext()
private val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build()
- private val wallpapers = WallpaperRepositoryImpl(context, db.wallpaperDao(), db.wallpaperQueueDao(), db.wallpaperCurrentDao())
- private val albums = AlbumRepositoryImpl(context, db, db.albumDao(), db.wallpaperDao(), db.folderDao(), Lazy { wallpapers })
+ private val wallpapers = WallpaperRepositoryImpl(db)
+ private val albums = AlbumRepositoryImpl(com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
@After fun close() = db.close()
@Test fun cancellingAChunkedFolderImportRollsBackAllRows() = runBlocking {
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
val folder = Folder.empty("folder", "album").copy(
- wallpapers = (0..599).map { Wallpaper.empty("image-$it", "album").copy(folderId = "folder") }
+ wallpapers = (0..599).map { Wallpaper.empty("image-$it", "album").copy(folderId = "folder", uri = "content://image-$it") }
)
try {
albums.addFolderToAlbum("album", folder) { saved, _ ->
@@ -53,7 +54,7 @@ class AlbumRepositoryInstrumentedTest {
db.folderDao().insertFolder(Folder.empty("folder", "album").toEntity())
val second = first.copy(id = "second", uri = "content://second", folderId = "folder")
- assertEquals(Result.Success(Unit), albums.addWallpapersToAlbum("album", listOf(second)))
+ assertEquals(Result.Success(1), albums.addWallpapersToAlbum("album", listOf(second)))
assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
assertEquals(2, db.wallpaperDao().getWallpaperCountByAlbum("album"))
assertEquals("content://second", db.folderDao().getFolderById("folder")?.coverUri)
@@ -66,9 +67,10 @@ class AlbumRepositoryInstrumentedTest {
val replacement = cover.copy(id = "replacement", uri = "content://replacement", displayOrder = 1)
db.wallpaperDao().insertWallpapers(listOf(cover, replacement, cover.copy(id = "other", albumId = "two")).map { it.toEntity() })
- assertEquals(Result.Success(Unit), albums.removeWallpapersFromAlbum("one", listOf("cover")))
+ assertEquals(Result.Success(Unit), albums.removeWallpapersFromAlbum("one", listOf("cover", "other")))
assertEquals("content://replacement", db.albumDao().getAlbumById("one")?.coverUri)
assertEquals("content://shared", db.albumDao().getAlbumById("two")?.coverUri)
+ assertNotNull(db.wallpaperDao().getWallpaperById("other"))
}
@Test fun coverRefreshUsesDisplayOrderAndClearsEmptyFolders() = runBlocking {
@@ -79,13 +81,73 @@ class AlbumRepositoryInstrumentedTest {
val direct = later.copy(id = "direct", folderId = null, uri = "content://direct", displayOrder = 99)
db.wallpaperDao().insertWallpapers(listOf(later, first, direct).map { it.toEntity() })
- assertEquals(Result.Success(Unit), albums.refreshFolderCovers("album"))
+ db.folderDao().refreshFolderCovers("album")
assertEquals("content://first", db.folderDao().getFolderById("folder")?.coverUri)
- assertEquals(Result.Success(Unit), albums.refreshAlbumCover("album"))
- assertEquals("content://direct", db.albumDao().getAlbumById("album")?.coverUri)
+ assertEquals("content://direct", db.wallpaperDao().getAlbumCoverUri("album"))
db.wallpaperDao().deleteWallpapersByFolder("folder")
- assertEquals(Result.Success(Unit), albums.refreshFolderCovers("album"))
+ db.folderDao().refreshFolderCovers("album")
assertNull(db.folderDao().getFolderById("folder")?.coverUri)
}
+
+ @Test fun concurrentImportsDeduplicateInsideTheTransaction() = runBlocking {
+ db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
+ val image = Wallpaper.empty("one", "album").copy(uri = "content://same")
+ val first = async(Dispatchers.IO) { albums.addWallpapersToAlbum("album", listOf(image)).getOrThrow() }
+ val second = async(Dispatchers.IO) { albums.addWallpapersToAlbum("album", listOf(image.copy(id = "two"))).getOrThrow() }
+ assertEquals(1, first.await() + second.await())
+ assertEquals(1, db.wallpaperDao().getWallpaperCountByAlbum("album"))
+
+ db.folderDao().insertFolder(Folder.empty("folder", "album").toEntity())
+ assertEquals(Result.Success(1), albums.addWallpapersToAlbum("album", listOf(image.copy(id = "folder-image", folderId = "folder"))))
+ db.folderDao().deleteFolderById("folder")
+ assertEquals(Result.Success(0), albums.addWallpapersToAlbum("album", listOf(image.copy(id = "stale", folderId = "folder"))))
+ }
+
+ @Test fun reorderPersistsNestedImagesWithoutOverwritingMetadata() = runBlocking {
+ db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
+ val first = Wallpaper.empty("first", "album").copy(uri = "content://first", folderId = "folder")
+ val second = first.copy(id = "second", uri = "content://second")
+ val folder = Folder.empty("folder", "album").copy(wallpapers = listOf(first, second))
+ albums.addFolderToAlbum("album", folder).getOrThrow()
+ wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, false).getOrThrow()
+ db.wallpaperDao().updateWallpaper(first.copy(fileName = "new-name.jpg").toEntity())
+
+ albums.reorderAlbum("album", listOf(folder.copy(wallpapers = listOf(second, first))), emptyList()).getOrThrow()
+ assertEquals(listOf("second", "first"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
+ assertEquals("new-name.jpg", db.wallpaperDao().getWallpaperById("first")?.fileName)
+ assertEquals("content://second", db.folderDao().getFolderById("folder")?.coverUri)
+ assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
+ }
+
+ @Test fun failedReorderRollsBackEarlierRowsAndPreservesQueue() = runBlocking {
+ db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
+ val first = Wallpaper.empty("first", "album").copy(uri = "content://first")
+ val second = first.copy(id = "second", uri = "content://second")
+ albums.addWallpapersToAlbum("album", listOf(first, second)).getOrThrow()
+ wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, false).getOrThrow()
+ db.openHelper.writableDatabase.execSQL("""
+ CREATE TRIGGER reject_order BEFORE UPDATE OF displayOrder ON wallpapers
+ WHEN NEW.id = 'first' BEGIN SELECT RAISE(ABORT, 'test write failure'); END
+ """)
+ assertTrue(albums.reorderAlbum("album", emptyList(), listOf(second, first)) is Result.Error)
+ assertEquals(listOf("first", "second"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
+ assertEquals(listOf("first", "second"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
+ }
+
+ @Test fun concurrentQueueCreationKeepsBothScreensInSyncAndDoesNotRefillConsumedItems() = runBlocking {
+ db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
+ albums.addWallpapersToAlbum("album", (1..8).map {
+ Wallpaper.empty("image-$it", "album").copy(uri = "content://image-$it")
+ }).getOrThrow()
+ val home = async(Dispatchers.IO) { wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true).getOrThrow() }
+ val lock = async(Dispatchers.IO) { wallpapers.ensureWallpaperQueue("album", ScreenType.LOCK, true).getOrThrow() }
+ home.await(); lock.await()
+ val expected = db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId }
+ assertEquals(8, expected.toSet().size)
+ assertEquals(expected, db.wallpaperQueueDao().getQueueItems("album", ScreenType.LOCK).map { it.wallpaperId })
+ wallpapers.getAndDequeueWallpaper("album", ScreenType.HOME)
+ wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true).getOrThrow()
+ assertEquals(expected.drop(1), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
+ }
}
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/domain/model/DisplayNameInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/domain/model/DisplayNameInstrumentedTest.kt
new file mode 100644
index 0000000..85f9179
--- /dev/null
+++ b/app/src/androidTest/java/com/anthonyla/paperize/domain/model/DisplayNameInstrumentedTest.kt
@@ -0,0 +1,18 @@
+package com.anthonyla.paperize.domain.model
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class DisplayNameInstrumentedTest {
+ @Test fun documentNamesDecodeEscapesAndPreserveLiteralPlusSigns() {
+ mapOf(
+ "primary%3APictures%2FSummer%20%2B%20Sun.jpg" to "Summer + Sun.jpg",
+ "primary%3APictures" to "Pictures",
+ "Pictures/Summer+Sun.jpg" to "Summer+Sun.jpg",
+ "" to ""
+ ).forEach { (stored, displayed) ->
+ assertEquals(displayed, Folder.empty().copy(name = stored).displayName)
+ assertEquals(displayed, Wallpaper.empty().copy(fileName = stored).displayFileName)
+ }
+ }
+}
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt
index 7826ec0..935a78b 100644
--- a/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/anthonyla/paperize/presentation/AlbumUiInstrumentedTest.kt
@@ -1,6 +1,17 @@
package com.anthonyla.paperize.presentation
import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Color
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.graphics.toPixelMap
+import com.anthonyla.paperize.domain.model.AlbumSummary
+import com.anthonyla.paperize.presentation.screens.library.components.AlbumItem
+import java.io.File
+import androidx.compose.runtime.mutableIntStateOf
+import com.anthonyla.paperize.core.constants.Constants
+import com.anthonyla.paperize.presentation.screens.wallpaper.components.TimeIntervalPicker
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.v2.createComposeRule
import androidx.test.core.app.ApplicationProvider
@@ -15,11 +26,93 @@ import androidx.compose.ui.unit.dp
import org.junit.Assert.*
import org.junit.Rule
import org.junit.Test
+import com.anthonyla.paperize.core.Result
+import com.anthonyla.paperize.domain.model.Album
+import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
+import kotlinx.coroutines.CompletableDeferred
+import androidx.compose.ui.semantics.SemanticsActions
+import com.anthonyla.paperize.core.WallpaperMode
+import com.anthonyla.paperize.domain.model.AppSettings
+import com.anthonyla.paperize.domain.model.ScheduleSettings
+import com.anthonyla.paperize.domain.model.WallpaperEffects
+import com.anthonyla.paperize.presentation.screens.wallpaper.WallpaperScreen
class AlbumUiInstrumentedTest {
@get:Rule val compose = createComposeRule()
private val context = ApplicationProvider.getApplicationContext()
+ @Test fun effectSlidersRouteDraftChangesToEnabledScreensAndLiveMode() {
+ val settings = mutableStateOf(ScheduleSettings(
+ homeEnabled = true, lockEnabled = true,
+ homeEffects = WallpaperEffects(enableBlur = true, blurPercentage = 45),
+ lockEffects = WallpaperEffects(enableBlur = true, blurPercentage = 65),
+ liveEffects = WallpaperEffects(enableBlur = true, blurPercentage = 80)
+ ))
+ val mode = mutableStateOf(WallpaperMode.STATIC)
+ var latest = settings.value
+ compose.setContent {
+ PaperizeTheme(false, false) {
+ WallpaperScreen(
+ albums = emptyList(), persistedScheduleSettings = settings.value,
+ appSettings = AppSettings(), wallpaperMode = mode.value,
+ onToggleChanger = {}, onSelectHomeAlbum = {}, onSelectLockAlbum = {}, onSelectLiveAlbum = {},
+ onUpdateScheduleSettings = { latest = it },
+ onUpdateScheduleSettingsDebounced = { latest = it },
+ onChangeWallpaperNow = {}, homeWallpaperUri = null, lockWallpaperUri = null
+ )
+ }
+ }
+ fun slide(index: Int, percentage: Float) {
+ compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress))[index]
+ .performScrollTo()
+ .performSemanticsAction(SemanticsActions.SetProgress) { it(percentage) }
+ }
+ slide(0, 20f)
+ slide(1, 75f)
+ compose.runOnIdle {
+ assertEquals(20, latest.homeEffects.blurPercentage)
+ assertEquals(75, latest.lockEffects.blurPercentage)
+ settings.value = latest.copy(homeEnabled = false)
+ }
+ slide(0, 55f)
+ compose.runOnIdle {
+ assertEquals(20, latest.homeEffects.blurPercentage)
+ assertEquals(55, latest.lockEffects.blurPercentage)
+ settings.value = latest
+ mode.value = WallpaperMode.LIVE
+ }
+ slide(0, 40f)
+ compose.runOnIdle {
+ assertEquals(20, latest.homeEffects.blurPercentage)
+ assertEquals(55, latest.lockEffects.blurPercentage)
+ assertEquals(40, latest.liveEffects.blurPercentage)
+ }
+ }
+
+ @Test fun failedAlbumCreationKeepsNameAndAllowsRetryAfterPendingSave() {
+ val pending = CompletableDeferred>()
+ var attempts = 0
+ compose.setContent {
+ PaperizeTheme(false, false) {
+ LibraryScreen(emptyList(), {}, { name ->
+ assertEquals("Mountains", name)
+ attempts++
+ if (attempts == 1) pending.await()
+ else Result.Success(Album.empty(id = "album", name = name))
+ })
+ }
+ }
+ compose.onNodeWithContentDescription(context.getString(R.string.add_album)).performClick()
+ compose.onNodeWithText(context.getString(R.string.album_name)).performTextInput("Mountains")
+ compose.onNodeWithText(context.getString(R.string.save)).performClick().assertIsNotEnabled()
+ compose.runOnIdle { pending.complete(Result.Error(IllegalStateException("Storage unavailable"))) }
+ compose.onNodeWithText(context.getString(R.string.album_create_failed)).assertIsDisplayed()
+ compose.onNodeWithText(context.getString(R.string.album_name)).assertTextContains("Mountains")
+ compose.onNodeWithText(context.getString(R.string.save)).performClick()
+ compose.onNodeWithText(context.getString(R.string.album_name)).assertDoesNotExist()
+ compose.runOnIdle { assertEquals(2, attempts) }
+ }
+
@Test fun sortSheetExposesCurrentSelectionAndAppliesNewChoice() {
var chosen: SortOption? = null
var dismissed = false
@@ -42,4 +135,54 @@ class AlbumUiInstrumentedTest {
compose.onNodeWithContentDescription("Mountains.jpg")
.assertIsSelected().assertHasClickAction()
}
+ @Test fun albumCoverLoadsThroughCoilAndFallsBackForMissingFiles() {
+ val file = File.createTempFile("album-cover", ".png", context.cacheDir)
+ val bitmap = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(Color.RED)
+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ bitmap.recycle()
+ val uri = mutableStateOf(file.toURI().toString())
+ try {
+ compose.setContent {
+ PaperizeTheme(false, false) {
+ AlbumItem(AlbumSummary.empty("album").copy(name = "Cover", coverUri = uri.value), {}, Modifier.size(180.dp))
+ }
+ }
+ fun centerColor(): Int {
+ val pixels = compose.onNodeWithContentDescription("Cover").captureToImage().toPixelMap()
+ return pixels[pixels.width / 2, pixels.height / 2].toArgb()
+ }
+ compose.waitUntil(5_000) { centerColor() == Color.RED }
+ compose.runOnIdle { uri.value = File(context.cacheDir, "missing-cover.png").toURI().toString() }
+ compose.waitUntil(5_000) { centerColor() != Color.RED }
+ compose.onNodeWithContentDescription("Cover").assertIsDisplayed()
+ } finally {
+ file.delete()
+ }
+ }
+
+ @Test fun intervalEditsDebounceAndExternalValuesCancelPendingEdits() {
+ val minutes = mutableIntStateOf(60)
+ val changes = mutableListOf()
+ compose.setContent {
+ PaperizeTheme(false, false) {
+ TimeIntervalPicker("Interval", minutes.intValue, { changes.add(it) })
+ }
+ }
+ compose.mainClock.autoAdvance = false
+ compose.mainClock.advanceTimeBy(Constants.DEBOUNCE_DELAY_MS + 50)
+ compose.runOnIdle { assertTrue(changes.isEmpty()) }
+ compose.onNodeWithText(context.getString(R.string.hours_txt)).performTextReplacement("0")
+ compose.mainClock.advanceTimeBy(100)
+ compose.onNodeWithText(context.getString(R.string.mins)).performTextReplacement("1")
+ compose.mainClock.advanceTimeBy(Constants.DEBOUNCE_DELAY_MS + 50)
+ compose.runOnIdle { assertEquals(listOf(Constants.MIN_INTERVAL_MINUTES), changes) }
+
+ compose.onNodeWithText(context.getString(R.string.mins)).performTextReplacement("30")
+ compose.runOnIdle { minutes.intValue = 120 }
+ compose.mainClock.advanceTimeBy(Constants.DEBOUNCE_DELAY_MS + 50)
+ compose.runOnIdle { assertEquals(1, changes.size) }
+ compose.onNodeWithText(context.getString(R.string.hours_txt)).assertTextContains("2")
+ }
+
}
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/service/livewallpaper/renderer/LiveWallpaperShaderInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/service/livewallpaper/renderer/LiveWallpaperShaderInstrumentedTest.kt
index 2619c49..07373a5 100644
--- a/app/src/androidTest/java/com/anthonyla/paperize/service/livewallpaper/renderer/LiveWallpaperShaderInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/anthonyla/paperize/service/livewallpaper/renderer/LiveWallpaperShaderInstrumentedTest.kt
@@ -17,6 +17,7 @@ import java.nio.ByteOrder
import java.nio.FloatBuffer
import org.junit.After
import org.junit.Assert.assertTrue
+import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@@ -87,12 +88,93 @@ class LiveWallpaperShaderInstrumentedTest {
EGL14.eglTerminate(display)
}
+ @Test
+ fun wallpaperConfigSupportsEs2WindowSurfaces() {
+ val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
+ val eglDisplay = egl.eglGetCurrentDisplay()
+ val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
+ .chooseConfig(egl, eglDisplay)
+ val attribute = IntArray(1)
+ assertTrue(egl.eglGetConfigAttrib(eglDisplay, config, EGL14.EGL_RENDERABLE_TYPE, attribute))
+ assertTrue(attribute[0] and EGL14.EGL_OPENGL_ES2_BIT != 0)
+ assertTrue(egl.eglGetConfigAttrib(eglDisplay, config, EGL14.EGL_SURFACE_TYPE, attribute))
+ assertTrue(attribute[0] and EGL14.EGL_WINDOW_BIT != 0)
+ }
+
+ @Test
+ fun rendererDrawsTheFinalCrossfadeFrameAndRejectsSupersededUploads() {
+ val app = androidx.test.core.app.ApplicationProvider.getApplicationContext()
+ val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
+ var renderRequests = 0
+ val renderer = PaperizeWallpaperRenderer(app, object : PaperizeWallpaperRenderer.Callbacks {
+ override fun queueEventOnGlThread(event: () -> Unit): Boolean = uploads.offer(event)
+ override fun requestRender() { renderRequests++ }
+ })
+ val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
+ val gl = egl.eglGetCurrentContext().gl as javax.microedition.khronos.opengles.GL10
+ val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
+ .chooseConfig(egl, egl.eglGetCurrentDisplay())
+ val file = java.io.File.createTempFile("live-renderer", ".png", app.cacheDir)
+ val replacement = java.io.File.createTempFile("live-renderer-next", ".png", app.cacheDir)
+ try {
+ val bitmap = solidBitmap(Color.WHITE)
+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ bitmap.recycle()
+ val loader = ContentUriImageLoader(app.contentResolver, android.net.Uri.fromFile(file))
+ renderer.onSurfaceCreated(gl, config)
+ renderer.onSurfaceChanged(gl, SIZE, SIZE)
+ renderer.queueWallpaper(loader)
+ val staleUpload = checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS))
+ renderer.queueWallpaper(loader)
+ val activeUpload = checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS))
+ staleUpload()
+ assertEquals(0, renderRequests)
+ activeUpload()
+ renderer.onDrawFrame(gl)
+ android.os.SystemClock.sleep(com.anthonyla.paperize.core.constants.Constants.CROSSFADE_DURATION_MS.toLong() + 50L)
+ val requestsBeforeFinalFrame = renderRequests
+ renderer.onDrawFrame(gl)
+ assertEquals(requestsBeforeFinalFrame, renderRequests)
+ assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
+
+ renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(
+ enableBlur = true, blurPercentage = 50
+ ))
+ renderer.onDrawFrame(gl)
+ assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
+
+ val red = solidBitmap(Color.RED)
+ replacement.outputStream().use { red.compress(Bitmap.CompressFormat.PNG, 100, it) }
+ red.recycle()
+ renderer.queueWallpaper(ContentUriImageLoader(app.contentResolver, android.net.Uri.fromFile(replacement)))
+ val uploadBeforeResize = checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS))
+ renderer.onSurfaceChanged(gl, SIZE, SIZE - 2)
+ uploadBeforeResize()
+ checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
+ renderer.onDrawFrame(gl)
+ assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
+ assertTrue(Color.green(readPixel(SIZE / 2, SIZE / 2)) <= 2)
+
+ destroyGlContext()
+ createGlContext()
+ renderer.onSurfaceCreated(gl, config)
+ renderer.onSurfaceChanged(gl, SIZE, SIZE)
+ checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
+ renderer.onDrawFrame(gl)
+ assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
+ assertTrue(Color.green(readPixel(SIZE / 2, SIZE / 2)) <= 2)
+ GLUtil.checkGLError("recreated wallpaper surface")
+ } finally {
+ renderer.destroy()
+ file.delete()
+ replacement.delete()
+ }
+ }
+
@Test
fun everyLiveWallpaperShaderCompilesAndLinksOnDevice() {
listOf(
- GLShaders.SIMPLE_FRAGMENT_SHADER,
- GLShaders.BLUR_HORIZONTAL_FRAGMENT_SHADER,
- GLShaders.BLUR_VERTICAL_FRAGMENT_SHADER,
+ GLShaders.BLUR_FRAGMENT_SHADER,
GLShaders.EFFECTS_FRAGMENT_SHADER
).forEach { fragmentShader ->
val program = GLUtil.createProgram(GLShaders.VERTEX_SHADER, fragmentShader)
@@ -142,23 +224,18 @@ class LiveWallpaperShaderInstrumentedTest {
val horizontalTexture = createTexture(horizontal)
val verticalTexture = createTexture(vertical)
- val horizontalProgram = GLUtil.createProgram(
+ val blurProgram = GLUtil.createProgram(
GLShaders.VERTEX_SHADER,
- GLShaders.BLUR_HORIZONTAL_FRAGMENT_SHADER
- )
- val verticalProgram = GLUtil.createProgram(
- GLShaders.VERTEX_SHADER,
- GLShaders.BLUR_VERTICAL_FRAGMENT_SHADER
+ GLShaders.BLUR_FRAGMENT_SHADER
)
try {
- drawBlur(horizontalProgram, horizontalTexture)
+ drawBlur(blurProgram, horizontalTexture, 1f, 0f)
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) in 10..245)
- drawBlur(verticalProgram, verticalTexture)
+ drawBlur(blurProgram, verticalTexture, 0f, 1f)
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) in 10..245)
} finally {
- GLES20.glDeleteProgram(horizontalProgram)
- GLES20.glDeleteProgram(verticalProgram)
+ GLES20.glDeleteProgram(blurProgram)
GLES20.glDeleteTextures(2, intArrayOf(horizontalTexture, verticalTexture), 0)
}
}
@@ -183,10 +260,11 @@ class LiveWallpaperShaderInstrumentedTest {
finishDraw(program)
}
- private fun drawBlur(program: Int, texture: Int) {
+ private fun drawBlur(program: Int, texture: Int, x: Float, y: Float) {
prepareDraw(program, texture)
GLES20.glUniform2f(GLES20.glGetUniformLocation(program, "u_resolution"), SIZE.toFloat(), SIZE.toFloat())
GLES20.glUniform1f(GLES20.glGetUniformLocation(program, "u_blurRadius"), 4f)
+ GLES20.glUniform2f(GLES20.glGetUniformLocation(program, "u_direction"), x, y)
finishDraw(program)
}
diff --git a/app/src/androidTest/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerInstrumentedTest.kt b/app/src/androidTest/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerInstrumentedTest.kt
index 0821af3..7940efe 100644
--- a/app/src/androidTest/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerInstrumentedTest.kt
+++ b/app/src/androidTest/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerInstrumentedTest.kt
@@ -39,7 +39,7 @@ class WallpaperSchedulerInstrumentedTest {
@Before
@After
fun clearTestSchedules() {
- targets.values.forEach { name ->
+ (targets.values + Constants.WORK_NAME_REFRESH).forEach { name ->
workManager.cancelUniqueWork(name).result.get(10, TimeUnit.SECONDS)
}
}
@@ -113,6 +113,46 @@ class WallpaperSchedulerInstrumentedTest {
assertEquals(lock.nextScheduleTimeMillis, sameLock.nextScheduleTimeMillis)
}
+ @Test
+ fun startupKeepsExistingCountdownsAndSwitchesBetweenCombinedAndSeparateJobs() = runBlocking {
+ scheduler.scheduleWallpaperChange(ScreenType.HOME, 60, resetInterval = true)
+ scheduler.scheduleWallpaperChange(ScreenType.LOCK, 90, resetInterval = true)
+ val home = awaitEnqueued(Constants.WORK_NAME_HOME)
+ val lock = awaitEnqueued(Constants.WORK_NAME_LOCK)
+
+ val settings = ScheduleSettings(
+ enableChanger = true, homeEnabled = true, lockEnabled = true,
+ homeAlbumId = "home", lockAlbumId = "lock", separateSchedules = true,
+ homeIntervalMinutes = 15, lockIntervalMinutes = 15
+ )
+ scheduler.updateSchedules(settings, WallpaperMode.STATIC, onlyIfNotScheduled = true)
+ awaitEnqueued(Constants.WORK_NAME_REFRESH)
+ for ((name, previous) in listOf(Constants.WORK_NAME_HOME to home, Constants.WORK_NAME_LOCK to lock)) {
+ val kept = awaitEnqueued(name)
+ assertEquals(previous.id, kept.id)
+ assertEquals(previous.generation, kept.generation)
+ assertEquals(previous.nextScheduleTimeMillis, kept.nextScheduleTimeMillis)
+ }
+
+ scheduler.updateSchedules(settings.copy(homeIntervalMinutes = 60, lockAlbumId = "home", separateSchedules = false), WallpaperMode.STATIC, onlyIfNotScheduled = true)
+ awaitEnqueued(Constants.WORK_NAME_BOTH)
+ awaitCancelled(Constants.WORK_NAME_HOME)
+ awaitCancelled(Constants.WORK_NAME_LOCK)
+
+ scheduler.updateSchedules(settings.copy(homeIntervalMinutes = 30, lockIntervalMinutes = 45), WallpaperMode.STATIC, onlyIfNotScheduled = true)
+ val newHome = awaitEnqueued(Constants.WORK_NAME_HOME)
+ val newLock = awaitEnqueued(Constants.WORK_NAME_LOCK)
+ awaitCancelled(Constants.WORK_NAME_BOTH)
+ assertTrue(home.id != newHome.id)
+ assertTrue(lock.id != newLock.id)
+ }
+
+ private suspend fun awaitCancelled(name: String) = withTimeout(10_000) {
+ workManager.getWorkInfosForUniqueWorkFlow(name).first { infos ->
+ infos.isNotEmpty() && infos.all { it.state == WorkInfo.State.CANCELLED }
+ }
+ }
+
private suspend fun awaitEnqueued(
name: String,
minimumGeneration: Int = 0
diff --git a/app/src/main/java/com/anthonyla/paperize/PaperizeApplication.kt b/app/src/main/java/com/anthonyla/paperize/PaperizeApplication.kt
index e514b89..1e02add 100644
--- a/app/src/main/java/com/anthonyla/paperize/PaperizeApplication.kt
+++ b/app/src/main/java/com/anthonyla/paperize/PaperizeApplication.kt
@@ -14,12 +14,6 @@ import com.anthonyla.paperize.service.worker.AlbumRefreshScheduler
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
-/**
- * Application class for Paperize
- *
- * Annotated with @HiltAndroidApp to enable dependency injection
- * Implements Configuration.Provider for WorkManager with Hilt support
- */
@HiltAndroidApp
class PaperizeApplication : Application(), Configuration.Provider, DefaultLifecycleObserver {
@@ -33,7 +27,6 @@ class PaperizeApplication : Application(), Configuration.Provider, DefaultLifecy
// Must run before any other initialization that accesses DB/preferences
DataResetManager.performResetIfNeeded(this)
- // Create notification channel (minSdk is 31, so always supported)
createNotificationChannel()
// Process lifecycle distinguishes real background/foreground transitions from activity
diff --git a/app/src/main/java/com/anthonyla/paperize/core/Result.kt b/app/src/main/java/com/anthonyla/paperize/core/Result.kt
index b5ffb00..3a832b3 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/Result.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/Result.kt
@@ -1,59 +1,27 @@
package com.anthonyla.paperize.core
-/**
- * A generic class that holds a value or an error
- */
+import kotlinx.coroutines.CancellationException
+
sealed class Result {
data class Success(val data: T) : Result()
data class Error(val exception: Throwable, val message: String? = exception.message) : Result()
- data object Loading : Result()
-
- val isSuccess: Boolean get() = this is Success
- val isError: Boolean get() = this is Error
- val isLoading: Boolean get() = this is Loading
fun getOrNull(): T? = if (this is Success) data else null
- fun exceptionOrNull(): Throwable? = if (this is Error) exception else null
- inline fun onSuccess(action: (T) -> Unit): Result {
- if (this is Success) action(data)
- return this
- }
-
- inline fun onError(action: (Throwable) -> Unit): Result {
- if (this is Error) action(exception)
- return this
+ fun getOrThrow(): T = when (this) {
+ is Success -> data
+ is Error -> throw exception
}
companion object {
inline fun runCatching(block: () -> T): Result {
return try {
Success(block())
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Error(e)
}
}
}
}
-
-/**
- * Map a Result to another type
- */
-inline fun Result.map(transform: (T) -> R): Result {
- return when (this) {
- is Result.Success -> Result.Success(transform(data))
- is Result.Error -> Result.Error(exception, message)
- is Result.Loading -> Result.Loading
- }
-}
-
-/**
- * Flat map a Result
- */
-inline fun Result.flatMap(transform: (T) -> Result): Result {
- return when (this) {
- is Result.Success -> transform(data)
- is Result.Error -> Result.Error(exception, message)
- is Result.Loading -> Result.Loading
- }
-}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/ScalingType.kt b/app/src/main/java/com/anthonyla/paperize/core/ScalingType.kt
index 878edc8..ff1a2aa 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/ScalingType.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/ScalingType.kt
@@ -1,8 +1,5 @@
package com.anthonyla.paperize.core
-/**
- * Wallpaper scaling options
- */
enum class ScalingType {
/**
* Fill the screen, cropping if necessary
@@ -14,9 +11,6 @@ enum class ScalingType {
*/
FIT,
- /**
- * Stretch the image to fill the screen
- */
STRETCH,
/**
diff --git a/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt b/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt
index a9020d2..edebb79 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt
@@ -1,8 +1,5 @@
package com.anthonyla.paperize.core
-/**
- * Screen types for wallpaper setting
- */
enum class ScreenType {
HOME,
LOCK,
diff --git a/app/src/main/java/com/anthonyla/paperize/core/WallpaperExceptions.kt b/app/src/main/java/com/anthonyla/paperize/core/WallpaperExceptions.kt
index d66110d..ef35095 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/WallpaperExceptions.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/WallpaperExceptions.kt
@@ -1,11 +1,5 @@
package com.anthonyla.paperize.core
-/**
- * Exception thrown when an album has no wallpapers available
- */
class EmptyAlbumException(message: String) : Exception(message)
-/**
- * Exception thrown when no valid wallpaper can be found after retries
- */
class NoValidWallpaperException(message: String) : Exception(message)
diff --git a/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt
index 738f7cc..9c53eca 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt
@@ -1,61 +1,11 @@
package com.anthonyla.paperize.core
-/**
- * Media type for wallpapers
- *
- * Determines what type of media the wallpaper file is, which affects
- * how it's rendered in live wallpaper mode.
- *
- * Note: Currently only IMAGE type is supported.
- */
+/** Stored in Room so existing library rows retain their media type. */
enum class WallpaperMediaType {
- /**
- * Image files: JPEG, PNG, WEBP, AVIF, HEIC, HEIF, BMP, GIF, TIFF
- * Supported in both static and live wallpaper modes
- */
IMAGE;
- /**
- * Supported file extensions for this media type
- */
- val supportedExtensions: Set
- get() = when (this) {
- IMAGE -> setOf(
- "jpg", "jpeg", "png", "webp", "avif",
- "heic", "heif", // HEIC/HEIF - Apple's high efficiency format
- "bmp", // Bitmap - legacy but still used
- "gif", // GIF - mostly for static images (first frame used)
- "tiff", "tif", // TIFF - high quality archival format
- "svg" // SVG - vector graphics (rasterized for wallpaper)
- )
- }
-
- /**
- * Whether this media type is supported in static wallpaper mode
- */
- val supportedInStaticMode: Boolean
- get() = this == IMAGE
-
- /**
- * Whether this media type is supported in live wallpaper mode
- */
- val supportedInLiveMode: Boolean
- get() = true // All types supported in live mode
-
companion object {
- /**
- * Detect media type from file extension
- */
- fun fromExtension(extension: String): WallpaperMediaType? {
- val ext = extension.lowercase()
- return entries.find { ext in it.supportedExtensions }
- }
-
- /**
- * Convert string to WallpaperMediaType
- */
- fun fromString(value: String?): WallpaperMediaType? {
- return entries.find { it.name.equals(value, ignoreCase = true) }
- }
+ fun fromString(value: String?): WallpaperMediaType? =
+ entries.find { it.name.equals(value, ignoreCase = true) }
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt
index b32476e..56ed20c 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt
@@ -29,10 +29,6 @@ enum class WallpaperMode {
LIVE;
companion object {
- /**
- * Convert string to WallpaperMode
- * Defaults to STATIC if string is null or doesn't match any mode
- */
fun fromString(value: String?): WallpaperMode {
return entries.find { it.name.equals(value, ignoreCase = true) } ?: STATIC
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/WallpaperSourceType.kt b/app/src/main/java/com/anthonyla/paperize/core/WallpaperSourceType.kt
index 8e1cf86..85db9fc 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/WallpaperSourceType.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/WallpaperSourceType.kt
@@ -1,16 +1,7 @@
package com.anthonyla.paperize.core
-/**
- * Source type for wallpapers
- */
enum class WallpaperSourceType {
- /**
- * Directly selected wallpaper files
- */
DIRECT,
- /**
- * Wallpapers from monitored folders
- */
FOLDER
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt b/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt
index cefe6b2..75d0a10 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt
@@ -1,8 +1,5 @@
package com.anthonyla.paperize.core.constants
-/**
- * Application-wide constants
- */
object Constants {
// Database
const val DATABASE_NAME = "paperize_database"
@@ -77,7 +74,6 @@ object Constants {
// Image processing
const val MAX_BLUR_RADIUS = 25.0f
const val BRIGHTNESS_SAMPLE_SIZE = 10 // Pixel sample size for brightness calculation
- const val DEFAULT_BRIGHTNESS = 0.5f // Default brightness fallback
// Luminance coefficients (ITU-R BT.709 standard)
const val LUMINANCE_RED = 0.2126
@@ -115,23 +111,17 @@ object Constants {
)
// Renderer
- /** Crossfade animation duration in milliseconds - consistent across all refresh rates */
const val CROSSFADE_DURATION_MS = 750f
const val RELOAD_THROTTLE_MS = 250L
const val BLUR_MIN_THRESHOLD = 0.01f
const val PERCENTAGE_DIVISOR = 100f
const val GL_ES_VERSION = 2
- const val SURFACE_POLL_INTERVAL_MS = 50L
- const val SURFACE_WAIT_TIMEOUT_MS = 1000L // Max wait for GL surface dimensions before falling back to display metrics
// Wallpaper loading
const val MAX_WALLPAPER_LOAD_RETRIES = 10
const val MAX_QUEUE_REBUILD_ATTEMPTS = 2
}
-/**
- * Preference keys for DataStore
- */
object PreferenceKeys {
// Theme
const val DARK_MODE = "dark_mode"
diff --git a/app/src/main/java/com/anthonyla/paperize/core/di/AppModule.kt b/app/src/main/java/com/anthonyla/paperize/core/di/AppModule.kt
index e6f2671..451037e 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/di/AppModule.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/di/AppModule.kt
@@ -5,18 +5,15 @@ import android.content.Context
import androidx.room.Room
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.data.database.PaperizeDatabase
-import com.anthonyla.paperize.data.database.dao.AlbumDao
-import com.anthonyla.paperize.data.database.dao.FolderDao
-import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
-import com.anthonyla.paperize.data.database.dao.WallpaperDao
-import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
import com.anthonyla.paperize.data.datastore.PreferencesManager
import com.anthonyla.paperize.data.repository.AlbumRepositoryImpl
import com.anthonyla.paperize.data.repository.SettingsRepositoryImpl
import com.anthonyla.paperize.data.repository.WallpaperRepositoryImpl
+import com.anthonyla.paperize.data.source.AndroidDocumentSource
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.WallpaperRepository
+import com.anthonyla.paperize.domain.source.DocumentSource
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -24,18 +21,17 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
-/**
- * Hilt dependency injection module
- *
- * Provides all application-wide dependencies
- */
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
- /**
- * Provide Room database
- */
+ @Provides
+ fun provideWallpaperManager(@ApplicationContext context: Context): android.app.WallpaperManager =
+ android.app.WallpaperManager.getInstance(context)
+
+ @Provides
+ fun provideDocumentSource(source: AndroidDocumentSource): DocumentSource = source
+
@Provides
@Singleton
fun providePaperizeDatabase(app: Application): PaperizeDatabase {
@@ -44,72 +40,21 @@ object AppModule {
PaperizeDatabase::class.java,
Constants.DATABASE_NAME
)
- .fallbackToDestructiveMigration(dropAllTables = true)
+ .addMigrations(*com.anthonyla.paperize.data.database.LIBRARY_MIGRATIONS)
.build()
}
- /**
- * Provide DAOs
- */
- @Provides
- @Singleton
- fun provideAlbumDao(database: PaperizeDatabase): AlbumDao =
- database.albumDao()
-
- @Provides
- @Singleton
- fun provideWallpaperDao(database: PaperizeDatabase): WallpaperDao =
- database.wallpaperDao()
-
- @Provides
- @Singleton
- fun provideFolderDao(database: PaperizeDatabase): FolderDao =
- database.folderDao()
-
- @Provides
- @Singleton
- fun provideWallpaperQueueDao(database: PaperizeDatabase): WallpaperQueueDao =
- database.wallpaperQueueDao()
-
- @Provides
- @Singleton
- fun provideWallpaperCurrentDao(database: PaperizeDatabase): WallpaperCurrentDao =
- database.wallpaperCurrentDao()
-
- /**
- * Provide PreferencesManager
- */
@Provides
@Singleton
fun providePreferencesManager(@ApplicationContext context: Context): PreferencesManager =
PreferencesManager(context)
- /**
- * Provide Repositories
- */
@Provides
- @Singleton
- fun provideAlbumRepository(
- @ApplicationContext context: Context,
- database: PaperizeDatabase,
- albumDao: AlbumDao,
- wallpaperDao: WallpaperDao,
- folderDao: FolderDao,
- wallpaperRepository: dagger.Lazy
- ): AlbumRepository = AlbumRepositoryImpl(context, database, albumDao, wallpaperDao, folderDao, wallpaperRepository)
+ fun provideAlbumRepository(repository: AlbumRepositoryImpl): AlbumRepository = repository
@Provides
- @Singleton
- fun provideWallpaperRepository(
- @ApplicationContext context: Context,
- wallpaperDao: WallpaperDao,
- wallpaperQueueDao: WallpaperQueueDao,
- wallpaperCurrentDao: WallpaperCurrentDao
- ): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao, wallpaperCurrentDao)
+ fun provideWallpaperRepository(repository: WallpaperRepositoryImpl): WallpaperRepository = repository
@Provides
- @Singleton
- fun provideSettingsRepository(
- preferencesManager: PreferencesManager
- ): SettingsRepository = SettingsRepositoryImpl(preferencesManager)
+ fun provideSettingsRepository(repository: SettingsRepositoryImpl): SettingsRepository = repository
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/BatteryOptimizationUtil.kt b/app/src/main/java/com/anthonyla/paperize/core/util/BatteryOptimizationUtil.kt
index 275abf6..0cc98a5 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/BatteryOptimizationUtil.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/BatteryOptimizationUtil.kt
@@ -2,39 +2,28 @@ package com.anthonyla.paperize.core.util
import android.content.Context
import android.content.Intent
-import android.net.Uri
+import androidx.core.net.toUri
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
-/**
- * Utility for handling battery optimization (Doze mode) exclusion
- */
object BatteryOptimizationUtil {
private const val TAG = "BatteryOptimizationUtil"
- /**
- * Check if the app is currently excluded from battery optimizations
- */
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
}
- /**
- * Request the user to exclude the app from battery optimizations
- * Opens the system battery optimization settings page
- */
fun requestIgnoreBatteryOptimizations(context: Context) {
try {
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
- data = Uri.parse("package:${context.packageName}")
+ data = "package:${context.packageName}".toUri()
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
} catch (e: Exception) {
Log.e(TAG, "Error requesting battery optimization exclusion", e)
- // Fallback: open general battery optimization settings
try {
val fallbackIntent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/BrightnessCalculator.kt b/app/src/main/java/com/anthonyla/paperize/core/util/BrightnessCalculator.kt
index dcca9d3..0f55dfc 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/BrightnessCalculator.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/BrightnessCalculator.kt
@@ -3,16 +3,9 @@ package com.anthonyla.paperize.core.util
import android.graphics.Bitmap
import com.anthonyla.paperize.core.constants.Constants
-/**
- * Utility class for brightness calculations and adaptive adjustments.
- * Extracted from WallpaperUtil for better testability.
- */
object BrightnessCalculator {
- /**
- * Calculate relative luminance of a single pixel using ITU-R BT.709 standard.
- * Use bitwise operations to avoid dependency on android.graphics.Color in core logic tests.
- */
+ /** Estimates luminance with BT.709 coefficients; channels remain in their encoded color space. */
fun calculateLuminance(pixel: Int): Double {
val r = ((pixel shr 16) and 0xFF) / 255.0
val g = ((pixel shr 8) and 0xFF) / 255.0
@@ -21,19 +14,11 @@ object BrightnessCalculator {
return Constants.LUMINANCE_RED * r + Constants.LUMINANCE_GREEN * g + Constants.LUMINANCE_BLUE * b
}
- /**
- * Calculate brightness estimate of bitmap (0.0 - 1.0).
- *
- * Reads one sampled row at a time using [Bitmap.getPixels] so the entire
- * sample set is fetched with (height / sampleSize) JNI calls instead of
- * (width / sampleSize) × (height / sampleSize) individual pixel lookups.
- * A reusable row buffer keeps allocations to one IntArray(width).
- */
+ /** Samples rows in bulk to avoid a JNI call for every pixel. Returns brightness in 0..1. */
fun calculateBitmapBrightness(bitmap: Bitmap): Float {
val sampleSize = Constants.BRIGHTNESS_SAMPLE_SIZE
val w = bitmap.width
val h = bitmap.height
- if (w <= 0 || h <= 0) return Constants.DEFAULT_BRIGHTNESS
val rowBuffer = IntArray(w)
var totalLuminance = 0.0
@@ -47,20 +32,9 @@ object BrightnessCalculator {
}
}
- return if (pixelCount > 0) {
- (totalLuminance / pixelCount).toFloat()
- } else {
- Constants.DEFAULT_BRIGHTNESS
- }
+ return (totalLuminance / pixelCount).toFloat()
}
- /**
- * Get adaptive brightness multiplier factor based on system dark/light mode.
- *
- * @param isDarkMode Whether the system is in dark mode
- * @param brightness Current image brightness (0.0 to 1.0)
- * @return Multiplier factor to apply to colors
- */
fun getAdaptiveMultiplier(isDarkMode: Boolean, brightness: Float): Float {
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
@@ -71,11 +45,8 @@ object BrightnessCalculator {
if (brightness < 0.01f) return 1.0f
return when {
- // In dark mode with very bright image: darken it
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
- // In light mode with very dark image: brighten it
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
- // No adjustment needed
else -> 1.0f
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/DataResetManager.kt b/app/src/main/java/com/anthonyla/paperize/core/util/DataResetManager.kt
index 57d6c85..3f83c77 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/DataResetManager.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/DataResetManager.kt
@@ -2,7 +2,9 @@ package com.anthonyla.paperize.core.util
import android.content.Context
import android.util.Log
-import java.io.File
+import androidx.core.content.edit
+import androidx.datastore.preferences.preferencesDataStoreFile
+import com.anthonyla.paperize.core.constants.Constants
/**
* Manages one-time data reset for major version upgrades.
@@ -13,10 +15,6 @@ import java.io.File
object DataResetManager {
private const val TAG = "DataResetManager"
- /**
- * Version tracking preferences - stored separately from main app prefs
- * so it survives the data wipe.
- */
private const val VERSION_PREFS_NAME = "version_prefs"
private const val KEY_LAST_RESET_VERSION = "last_reset_version"
@@ -28,12 +26,6 @@ object DataResetManager {
*/
private const val TARGET_RESET_VERSION = 4
- /**
- * Database and DataStore names to clear (must match Constants)
- */
- private const val DATABASE_NAME = "paperize_database"
- private const val DATASTORE_NAME = "paperize_preferences.preferences_pb"
-
/**
* Performs a complete data reset if needed for the current app version.
*
@@ -53,78 +45,17 @@ object DataResetManager {
Log.w(TAG, "Performing data reset: upgrading from version $lastResetVersion to $TARGET_RESET_VERSION")
- try {
- // 1. Delete Room database files
- deleteDatabase(context)
-
- // 2. Delete DataStore file
- deleteDataStore(context)
-
- // 3. Update version after successful wipe
- versionPrefs.edit()
- .putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION)
- .apply()
-
+ return try {
+ context.deleteDatabase(Constants.DATABASE_NAME)
+ context.preferencesDataStoreFile(Constants.PREFERENCES_NAME).delete()
Log.i(TAG, "Data reset completed successfully")
- return true
-
+ true
} catch (e: Exception) {
Log.e(TAG, "Error during data reset", e)
- // Still mark as reset to avoid infinite reset loops on corrupted data
- versionPrefs.edit()
- .putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION)
- .apply()
- return false
- }
- }
-
- /**
- * Deletes Room database and all related files (WAL, SHM, journal)
- */
- private fun deleteDatabase(context: Context) {
- val dbPath = context.getDatabasePath(DATABASE_NAME)
- val dbDir = dbPath.parentFile
-
- if (dbDir != null && dbDir.exists()) {
- // Delete main database file and all related files
- val filesToDelete = listOf(
- DATABASE_NAME,
- "$DATABASE_NAME-wal",
- "$DATABASE_NAME-shm",
- "$DATABASE_NAME-journal"
- )
-
- for (fileName in filesToDelete) {
- val file = File(dbDir, fileName)
- if (file.exists()) {
- val deleted = file.delete()
- Log.d(TAG, "Deleted $fileName: $deleted")
- }
- }
- }
-
- // Also use Context.deleteDatabase for good measure
- val deleted = context.deleteDatabase(DATABASE_NAME)
- Log.d(TAG, "Context.deleteDatabase result: $deleted")
- }
-
- /**
- * Deletes DataStore preferences file
- */
- private fun deleteDataStore(context: Context) {
- val dataStoreFile = File(context.filesDir, "datastore/$DATASTORE_NAME")
- if (dataStoreFile.exists()) {
- val deleted = dataStoreFile.delete()
- Log.d(TAG, "Deleted DataStore file: $deleted")
- }
-
- // Also delete the datastore directory if empty
- val dataStoreDir = File(context.filesDir, "datastore")
- if (dataStoreDir.exists() && dataStoreDir.isDirectory) {
- val files = dataStoreDir.listFiles()
- if (files.isNullOrEmpty()) {
- dataStoreDir.delete()
- }
+ false
+ } finally {
+ // Do not repeat a destructive upgrade attempt on the next launch after a failure.
+ versionPrefs.edit { putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION) }
}
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt b/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt
index b9ba27f..00ed8b0 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/Extensions.kt
@@ -5,7 +5,6 @@ import android.content.Context
import android.net.Uri
import android.os.CancellationSignal
import android.provider.DocumentsContract
-import androidx.documentfile.provider.DocumentFile
import com.anthonyla.paperize.core.constants.Constants
import android.database.Cursor
import java.io.IOException
@@ -33,10 +32,6 @@ fun Uri.isValid(contentResolver: ContentResolver): Boolean {
}
}
-fun Uri.getFileName(context: Context): String? {
- return DocumentFile.fromSingleUri(context, this)?.name
-}
-
/** Only a successful, complete query with no rows proves that a document was removed. */
fun Uri.isDocumentMissing(contentResolver: ContentResolver): Boolean {
if (scheme != ContentResolver.SCHEME_CONTENT) return false
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/ImageSizing.kt b/app/src/main/java/com/anthonyla/paperize/core/util/ImageSizing.kt
new file mode 100644
index 0000000..6f99935
--- /dev/null
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/ImageSizing.kt
@@ -0,0 +1,24 @@
+package com.anthonyla.paperize.core.util
+
+import com.anthonyla.paperize.core.ScalingType
+import kotlin.math.roundToInt
+
+internal fun calculateDecodeSize(
+ sourceWidth: Int,
+ sourceHeight: Int,
+ targetWidth: Int,
+ targetHeight: Int,
+ scaling: ScalingType
+): Pair {
+ val widthRatio = targetWidth.toFloat() / sourceWidth
+ val heightRatio = targetHeight.toFloat() / sourceHeight
+ val scale = when (scaling) {
+ ScalingType.FILL -> maxOf(widthRatio, heightRatio)
+ ScalingType.FIT -> minOf(widthRatio, heightRatio)
+ // Keep native size unless decoding would exceed twice the screen size.
+ ScalingType.NONE -> minOf(1f, widthRatio * 2, heightRatio * 2)
+ ScalingType.STRETCH -> return targetWidth to targetHeight
+ }
+ return (sourceWidth * scale).roundToInt().coerceAtLeast(1) to
+ (sourceHeight * scale).roundToInt().coerceAtLeast(1)
+}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/QueueBuilder.kt b/app/src/main/java/com/anthonyla/paperize/core/util/QueueBuilder.kt
index 191b240..2ace3ed 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/QueueBuilder.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/QueueBuilder.kt
@@ -1,39 +1,6 @@
package com.anthonyla.paperize.core.util
-/**
- * Utility object for building and managing wallpaper queues
- * Extracted from WallpaperRepositoryImpl for testability
- *
- * Note: The DAO-specific operations remain in the repository,
- * but the pure logic functions are extracted here for testing.
- */
object QueueBuilder {
-
- /**
- * Build a queue of wallpaper IDs based on display order (sequential mode)
- * @param wallpaperIds List of wallpaper IDs with their display orders
- * @return List of IDs sorted by display order
- */
- fun buildSequentialQueue(wallpaperIds: List>): List {
- return wallpaperIds.sortedBy { it.second }.map { it.first }
- }
-
- /**
- * Build a shuffled queue of wallpaper IDs
- * @param wallpaperIds List of wallpaper IDs to shuffle
- * @return Shuffled list of IDs
- */
- fun buildShuffledQueue(wallpaperIds: List): List {
- return wallpaperIds.shuffled()
- }
-
- /**
- * Merge existing queue with new wallpapers while preserving existing order
- * Used when new wallpapers are added to an album during shuffle mode
- * @param existingQueueIds Current queue order (filtered to valid IDs)
- * @param allWallpaperIds All current wallpaper IDs in the album
- * @return Combined list with existing order preserved, new IDs shuffled at end
- */
fun mergeWithExistingQueue(
existingQueueIds: List,
allWallpaperIds: List
@@ -44,45 +11,4 @@ object QueueBuilder {
val newWallpaperIds = allWallpaperIds.filter { it !in existingSet }
return existingValid + newWallpaperIds.shuffled()
}
-
- /**
- * Deterministic version of mergeWithExistingQueue for testing
- * New wallpapers are appended in their original order instead of shuffled
- */
- fun mergeWithExistingQueueDeterministic(
- existingQueueIds: List,
- allWallpaperIds: List
- ): List {
- val allSet = allWallpaperIds.toHashSet()
- val existingSet = existingQueueIds.toHashSet()
- val existingValid = existingQueueIds.filter { it in allSet }
- val newWallpaperIds = allWallpaperIds.filter { it !in existingSet }
- return existingValid + newWallpaperIds
- }
-
- /**
- * Build a wallpaper queue based on shuffle and existing queues
- * @param wallpapers Current list of wallpapers in the album
- * @param shuffle Whether shuffle is enabled
- * @param otherScreenQueue Optional existing queue for another screen type to synchronize with
- * @return List of wallpaper IDs for the new queue
- */
- fun buildQueue(
- wallpapers: List,
- shuffle: Boolean,
- otherScreenQueue: List? = null
- ): List {
- return if (shuffle) {
- if (otherScreenQueue != null && otherScreenQueue.isNotEmpty()) {
- // Synchronize with existing queue from another screen
- mergeWithExistingQueue(otherScreenQueue, wallpapers.map { it.id })
- } else {
- // New shuffled order
- buildShuffledQueue(wallpapers.map { it.id })
- }
- } else {
- // Sequential order by displayOrder
- buildSequentialQueue(wallpapers.map { it.id to it.displayOrder })
- }
- }
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperManagerExt.kt b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperManagerExt.kt
index 7b49db6..de7828e 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperManagerExt.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperManagerExt.kt
@@ -8,11 +8,6 @@ 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
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperRenderer.kt b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperRenderer.kt
new file mode 100644
index 0000000..6bdafbb
--- /dev/null
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperRenderer.kt
@@ -0,0 +1,52 @@
+package com.anthonyla.paperize.core.util
+
+import android.content.Context
+import android.graphics.Bitmap
+import androidx.core.net.toUri
+import com.anthonyla.paperize.core.ScreenType
+import com.anthonyla.paperize.domain.model.ScheduleSettings
+import com.anthonyla.paperize.domain.model.Wallpaper
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
+import javax.inject.Inject
+
+class WallpaperRenderer @Inject constructor(@param:ApplicationContext private val context: Context) {
+ suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings): Bitmap? {
+ currentCoroutineContext().ensureActive()
+ val effects = when (screen) {
+ ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
+ ScreenType.LOCK -> settings.lockEffects
+ ScreenType.LIVE -> settings.liveEffects
+ }
+ val scaling = when (screen) {
+ ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
+ ScreenType.LOCK -> settings.lockScalingType
+ ScreenType.LIVE -> settings.liveScalingType
+ }
+ val size = getDeviceScreenSize(context)
+ var bitmap = retrieveBitmap(context, wallpaper.uri.toUri(), size.width, size.height, scaling,
+ usesLauncherManagedScrolling(screen, scaling, settings.homeScrollingEnabled)) ?: return null
+ try {
+ val processed = 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 (processed !== bitmap) bitmap.recycle()
+ bitmap = processed
+ if (settings.adaptiveBrightness) {
+ val adjusted = adaptiveBrightnessAdjustment(context, bitmap)
+ if (adjusted !== bitmap) bitmap.recycle()
+ bitmap = adjusted
+ }
+ currentCoroutineContext().ensureActive()
+ return bitmap
+ } catch (e: Exception) {
+ bitmap.recycle()
+ throw e
+ }
+ }
+}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperSorter.kt b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperSorter.kt
index 2936538..769bf27 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperSorter.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperSorter.kt
@@ -3,98 +3,8 @@ package com.anthonyla.paperize.core.util
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
-/**
- * Utility object for sorting wallpapers and folders
- * Extracted from ViewModels for testability
- */
object WallpaperSorter {
- /**
- * Sort wallpapers by filename (alphabetically)
- * @param wallpapers List of wallpapers to sort
- * @param ascending True for A-Z, false for Z-A
- * @return New sorted list preserving original list
- */
- fun sortWallpapersByName(
- wallpapers: List,
- ascending: Boolean = true
- ): List {
- return if (ascending) {
- wallpapers.sortedBy { it.fileName.lowercase() }
- } else {
- wallpapers.sortedByDescending { it.fileName.lowercase() }
- }
- }
-
- /**
- * Sort wallpapers by date added (addedAt timestamp)
- * @param wallpapers List of wallpapers to sort
- * @param ascending True for oldest first, false for newest first
- * @return New sorted list preserving original list
- */
- fun sortWallpapersByDateAdded(
- wallpapers: List,
- ascending: Boolean = true
- ): List {
- return if (ascending) {
- wallpapers.sortedBy { it.addedAt }
- } else {
- wallpapers.sortedByDescending { it.addedAt }
- }
- }
-
- /**
- * Sort wallpapers by date modified (dateModified timestamp)
- * @param wallpapers List of wallpapers to sort
- * @param ascending True for oldest first, false for newest first
- * @return New sorted list preserving original list
- */
- fun sortWallpapersByDateModified(
- wallpapers: List,
- ascending: Boolean = true
- ): List {
- return if (ascending) {
- wallpapers.sortedBy { it.dateModified }
- } else {
- wallpapers.sortedByDescending { it.dateModified }
- }
- }
-
- /**
- * Sort folders by name (alphabetically)
- */
- fun sortFoldersByName(
- folders: List,
- ascending: Boolean = true
- ): List {
- return if (ascending) {
- folders.sortedBy { it.name.lowercase() }
- } else {
- folders.sortedByDescending { it.name.lowercase() }
- }
- }
-
- /**
- * Sort folders by date modified
- */
- fun sortFoldersByDateModified(
- folders: List,
- ascending: Boolean = true
- ): List {
- return if (ascending) {
- folders.sortedBy { it.dateModified }
- } else {
- folders.sortedByDescending { it.dateModified }
- }
- }
-
- /**
- * Shift a wallpaper within a list (drag and drop)
- * @param wallpapers Current list of wallpapers
- * @param fromUri URI of the wallpaper being moved
- * @param toUri URI of the target position
- * @return New list with wallpaper moved and display orders updated
- */
fun shiftWallpaper(
wallpapers: List,
fromUri: String,
@@ -112,13 +22,6 @@ object WallpaperSorter {
return applyDisplayOrder(mutableList)
}
- /**
- * Shift a folder within a list (drag and drop)
- * @param folders Current list of folders
- * @param fromUri URI of the folder being moved
- * @param toUri URI of the target position
- * @return New list with folder moved and display orders updated
- */
fun shiftFolder(
folders: List,
fromUri: String,
@@ -136,14 +39,6 @@ object WallpaperSorter {
return applyFolderDisplayOrder(mutableList)
}
- /**
- * Shift a wallpaper within a folder's wallpaper list
- * @param folders List of all folders
- * @param folderId ID of the folder containing the wallpaper
- * @param fromUri URI of the wallpaper being moved
- * @param toUri URI of the target position
- * @return Pair of updated folders list and the new cover URI for the folder
- */
fun shiftWallpaperInFolder(
folders: List,
folderId: String,
@@ -155,7 +50,7 @@ object WallpaperSorter {
val updatedWallpapers = shiftWallpaper(folder.wallpapers, fromUri, toUri)
folder.copy(
wallpapers = updatedWallpapers,
- coverUri = updatedWallpapers.firstOrNull()?.uri ?: folder.coverUri
+ coverUri = updatedWallpapers.firstOrNull()?.uri
)
} else {
folder
@@ -163,85 +58,47 @@ object WallpaperSorter {
}
}
- /**
- * Sort all folders and wallpapers alphabetically
- */
fun sortAllAlphabetically(
folders: List,
wallpapers: List,
ascending: Boolean = true
- ): Pair, List> {
- val sortedFolders = folders.map { folder ->
- val sortedWallpapers = sortWallpapersByName(folder.wallpapers, ascending)
- val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
- folder.copy(
- wallpapers = orderedWallpapers,
- coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
- )
- }
-
- val finalFolders = if (ascending) {
- sortedFolders.sortedBy { it.name.lowercase() }
- } else {
- sortedFolders.sortedByDescending { it.name.lowercase() }
- }
-
- val finalWallpapers = sortWallpapersByName(wallpapers, ascending)
-
- return Pair(
- applyFolderDisplayOrder(finalFolders),
- applyDisplayOrder(finalWallpapers)
- )
- }
+ ): Pair, List> = sortAll(
+ folders, wallpapers, ascending,
+ compareBy { it.name.lowercase() }, compareBy { it.fileName.lowercase() }
+ )
- /**
- * Sort all folders and wallpapers by date modified
- */
fun sortAllByDateModified(
folders: List,
wallpapers: List,
ascending: Boolean = true
+ ): Pair, List> = sortAll(
+ folders, wallpapers, ascending,
+ compareBy { it.dateModified }, compareBy { it.dateModified }
+ )
+
+ private fun sortAll(
+ folders: List,
+ wallpapers: List,
+ ascending: Boolean,
+ folderComparator: Comparator,
+ wallpaperComparator: Comparator
): Pair, List> {
- val sortedFolders = folders.map { folder ->
- val sortedWallpapers = sortWallpapersByDateModified(folder.wallpapers, ascending)
- val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
- folder.copy(
- wallpapers = orderedWallpapers,
- coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
- )
+ val folderOrder = if (ascending) folderComparator else folderComparator.reversed()
+ val wallpaperOrder = if (ascending) wallpaperComparator else wallpaperComparator.reversed()
+ val sortedFolders = folders.sortedWith(folderOrder).mapIndexed { index, folder ->
+ val images = applyDisplayOrder(folder.wallpapers.sortedWith(wallpaperOrder))
+ folder.copy(displayOrder = index, wallpapers = images, coverUri = images.firstOrNull()?.uri)
}
-
- val finalFolders = if (ascending) {
- sortedFolders.sortedBy { it.dateModified }
- } else {
- sortedFolders.sortedByDescending { it.dateModified }
- }
-
- val finalWallpapers = sortWallpapersByDateModified(wallpapers, ascending)
-
- return Pair(
- applyFolderDisplayOrder(finalFolders),
- applyDisplayOrder(finalWallpapers)
- )
+ return sortedFolders to applyDisplayOrder(wallpapers.sortedWith(wallpaperOrder))
}
- /**
- * Apply displayOrder indices to sorted wallpapers
- * @param wallpapers Sorted list of wallpapers
- * @return New list with displayOrder updated to match list position
- */
- fun applyDisplayOrder(wallpapers: List): List {
+ private fun applyDisplayOrder(wallpapers: List): List {
return wallpapers.mapIndexed { index, wallpaper ->
wallpaper.copy(displayOrder = index)
}
}
- /**
- * Apply displayOrder indices to sorted folders
- * @param folders Sorted list of folders
- * @return New list with folder moved and display orders updated
- */
- fun applyFolderDisplayOrder(folders: List): List {
+ private fun applyFolderDisplayOrder(folders: List): List {
return folders.mapIndexed { index, folder ->
folder.copy(displayOrder = index)
}
diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt
index 6f7c360..6f1213e 100644
--- a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt
+++ b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt
@@ -5,6 +5,7 @@ import android.app.WallpaperManager
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
+import androidx.core.graphics.createBitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
@@ -20,6 +21,7 @@ import android.graphics.PorterDuffXfermode
import android.graphics.RadialGradient
import android.graphics.RenderEffect
import android.graphics.RenderNode
+import android.graphics.RectF
import android.graphics.Shader
import android.hardware.display.DisplayManager
import android.hardware.HardwareBuffer
@@ -34,26 +36,11 @@ 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
-
-/**
- * Wallpaper utility functions for bitmap processing and effects
- *
- * Improvements:
- * - Added EXIF orientation handling
- * - API-safe blur with fallback for Android < S
- * - Memory management with bitmap recycling
- * - Effect enable flags respected
- * - Quality optimization options
- */
private const val TAG = "WallpaperUtil"
private const val BUILT_IN_DISPLAY_CATEGORY =
"android.hardware.display.category.BUILT_IN_DISPLAYS"
-/**
- * Get EXIF orientation from URI
- */
fun Uri.getExifOrientation(context: Context): Int {
return try {
context.contentResolver.openInputStream(this)?.use { inputStream ->
@@ -66,9 +53,6 @@ fun Uri.getExifOrientation(context: Context): Int {
}
}
-/**
- * Create transformation matrix for EXIF orientation
- */
fun getExifTransformationMatrix(orientation: Int, width: Int, height: Int): Matrix {
val matrix = Matrix()
@@ -106,9 +90,6 @@ fun getExifTransformationMatrix(orientation: Int, width: Int, height: Int): Matr
return matrix
}
-/**
- * Calculate the inSampleSize for the image
- */
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
if (imageSize.width == 0 || imageSize.height == 0) return 1
if (width == 0 || height == 0) return 1
@@ -124,9 +105,6 @@ fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
return 1
}
-/**
- * Get device screen size without orientation
- */
object ScreenMetricsCompat {
fun getScreenSize(context: Context): Size {
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
@@ -166,7 +144,6 @@ object ScreenMetricsCompat {
}
}
-/** Prefer stable natural-orientation panel modes, falling back to the current window if needed. */
internal fun selectWallpaperDisplayDimensions(
currentWindow: Pair,
supportedModes: Iterable>
@@ -174,11 +151,6 @@ internal fun selectWallpaperDisplayDimensions(
?: currentWindow.takeIf { (width, height) -> width > 0 && height > 0 }
?: (1 to 1)
-/**
- * Select the highest-resolution display dimensions.
- *
- * Kept platform-independent so foldable sizing behavior is covered by local unit tests.
- */
internal fun selectLargestDisplayDimensions(
candidates: Iterable>
): Pair? = candidates
@@ -191,25 +163,8 @@ internal fun selectLargestDisplayDimensions(
)
)
-/**
- * Get the stable natural-orientation size of the largest built-in display panel.
- */
fun getDeviceScreenSize(context: Context): Size = ScreenMetricsCompat.getScreenSize(context)
-/**
- * Get the target render size for a wallpaper bitmap.
- *
- * Every static scaling mode is rendered against one physical panel. A launcher's desired
- * wallpaper canvas may be much wider than the display; using it for FIT/NONE creates black-only
- * viewports and using it for STRETCH distorts the image. Optional FILL scrolling retains real
- * source overflow after decoding instead of inflating the target canvas.
- */
-fun getWallpaperRenderSize(
- context: Context,
- screenType: com.anthonyla.paperize.core.ScreenType,
- scaling: ScalingType = ScalingType.FIT
-): Size = getDeviceScreenSize(context)
-
/**
* Whether a static wallpaper should retain source overflow for launcher-managed scrolling.
*
@@ -225,14 +180,6 @@ internal fun usesLauncherManagedScrolling(
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.
- *
- * ImageDecoder is the primary path: it auto-applies EXIF orientation and exposes
- * post-EXIF dimensions in the callback via info.size, so we no longer need a
- * separate getImageDimensions() pre-read. The BitmapFactory fallback computes its
- * own inSampleSize inline to avoid an extra stream open on the happy path.
- */
fun retrieveBitmap(
context: Context,
wallpaperUri: Uri,
@@ -241,52 +188,22 @@ fun retrieveBitmap(
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.
+ // ImageDecoder reports dimensions after applying EXIF orientation.
var decodedWithImageDecoder = false
val bitmap = try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
val result = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
- val srcWidth = info.size.width
- val srcHeight = info.size.height
-
- when (scaling) {
- ScalingType.FILL -> {
- // Scale to fill, then crop to canvas during decode.
- // setCrop avoids allocating the full fill-scale bitmap (which can be
- // much taller/wider than the canvas) — major OOM prevention.
- val scale = maxOf(width.toFloat() / srcWidth, height.toFloat() / srcHeight)
- val targetW = (srcWidth * scale).fastRoundToInt()
- val targetH = (srcHeight * scale).fastRoundToInt()
- decoder.setTargetSize(targetW, targetH)
- 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(
- cropX, cropY, cropX + width, cropY + height
- ))
- }
- }
- ScalingType.FIT -> {
- val scale = minOf(width.toFloat() / srcWidth, height.toFloat() / srcHeight)
- decoder.setTargetSize(
- (srcWidth * scale).fastRoundToInt(),
- (srcHeight * scale).fastRoundToInt()
- )
- }
- ScalingType.STRETCH -> decoder.setTargetSize(width, height)
- ScalingType.NONE -> {
- val maxWidth = width * 2
- val maxHeight = height * 2
- if (srcWidth > maxWidth || srcHeight > maxHeight) {
- val scale = minOf(maxWidth.toFloat() / srcWidth, maxHeight.toFloat() / srcHeight)
- decoder.setTargetSize(
- (srcWidth * scale).fastRoundToInt(),
- (srcHeight * scale).fastRoundToInt()
- )
- }
- // else: decode at original resolution
- }
+ val (targetW, targetH) = calculateDecodeSize(
+ info.size.width, info.size.height, width, height, scaling
+ )
+ decoder.setTargetSize(targetW, targetH)
+ // Crop during decode to avoid allocating fill-scale overflow.
+ if (scaling == ScalingType.FILL && !preserveSourceOverflow &&
+ (targetW > width || targetH > height)
+ ) {
+ val cropX = ((targetW - width) / 2).coerceAtLeast(0)
+ val cropY = ((targetH - height) / 2).coerceAtLeast(0)
+ decoder.setCrop(android.graphics.Rect(cropX, cropY, cropX + width, cropY + height))
}
decoder.isMutableRequired = true
@@ -297,8 +214,6 @@ fun retrieveBitmap(
} catch (e: Exception) {
Log.w(TAG, "ImageDecoder failed, falling back to BitmapFactory: $e")
try {
- // Compute inSampleSize from a bounds-only pass, then decode in a second pass.
- // Two opens only on the rare fallback path — the primary ImageDecoder path is free.
val sampleSize = context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeStream(stream, null, opts)
@@ -324,13 +239,7 @@ fun retrieveBitmap(
// Only apply EXIF orientation for the BitmapFactory path — ImageDecoder already handles it
val oriented = if (decodedWithImageDecoder) bitmap else bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
- // Composite onto an exact (width × height) canvas so WallpaperManager.setBitmap() receives
- // a bitmap that already matches the desired canvas dimensions. Without this step the launcher
- // still has to scale/position the bitmap, which undoes the scaling mode the user chose:
- // FILL → decoded bitmap may be taller than canvas; center-crop to canvas size.
- // 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.
+ // An exact canvas prevents the launcher from undoing the selected scaling mode.
return oriented?.let {
if (preserveSourceOverflow && scaling == ScalingType.FILL) {
scaleToFillPreservingOverflow(it, width, height)
@@ -364,73 +273,29 @@ private fun scaleToFillPreservingOverflow(
return scaled
}
-/**
- * Produce a bitmap of exactly [canvasW] × [canvasH] pixels according to [scaling]:
- *
- * - FILL: the source already fills (or overflows) the canvas because [retrieveBitmap]
- * decoded it at fill-scale. Center-crop any overflow.
- * - FIT: the source fits within the canvas but may leave empty margins.
- * Draw it centered on a black [canvasW]×[canvasH] bitmap.
- * - STRETCH: [retrieveBitmap] decoded to the exact canvas size; nothing to do.
- * - NONE: the source is at most canvas-sized (possibly smaller).
- * Draw it centered on a black [canvasW]×[canvasH] bitmap.
- */
-private fun finalizeToCanvas(source: Bitmap, canvasW: Int, canvasH: Int, scaling: ScalingType): Bitmap {
- val sw = source.width
- val sh = source.height
-
- return when (scaling) {
- ScalingType.FILL -> {
- // Primary path (ImageDecoder): source was decoded at fill-scale so it is
- // >= canvasW wide AND >= canvasH tall. Center-crop to exact canvas size.
- // Fallback path (BitmapFactory): source may be smaller if the image needed
- // upscaling — scale up first, then center-crop.
- val fillSrc = if (sw < canvasW || sh < canvasH) {
- val scale = maxOf(canvasW.toFloat() / sw, canvasH.toFloat() / sh)
- val scaledW = (sw * scale).fastRoundToInt()
- val scaledH = (sh * scale).fastRoundToInt()
- val scaled = Bitmap.createScaledBitmap(source, scaledW, scaledH, true)
- if (scaled !== source) source.recycle()
- scaled
- } else source
- val fsw = fillSrc.width
- val fsh = fillSrc.height
- if (fsw == canvasW && fsh == canvasH) return fillSrc
- val x = ((fsw - canvasW) / 2).coerceAtLeast(0)
- val y = ((fsh - canvasH) / 2).coerceAtLeast(0)
- val cropped = Bitmap.createBitmap(fillSrc, x, y, canvasW, canvasH)
- if (cropped !== fillSrc) fillSrc.recycle()
- cropped
- }
-
- ScalingType.FIT, ScalingType.NONE -> {
- // FIT / NONE: source fits within the canvas; center it on a black background.
- if (sw == canvasW && sh == canvasH) return source
- compositeCenter(source, canvasW, canvasH)
- }
-
- ScalingType.STRETCH -> source // decoder was given exact canvas dimensions
+/** Render either decoder's output onto the requested canvas; consumes [source]. */
+internal fun finalizeToCanvas(source: Bitmap, canvasW: Int, canvasH: Int, scaling: ScalingType): Bitmap {
+ if (source.width == canvasW && source.height == canvasH) return source
+ val widthRatio = canvasW.toFloat() / source.width
+ val heightRatio = canvasH.toFloat() / source.height
+ val scale = when (scaling) {
+ ScalingType.FILL -> maxOf(widthRatio, heightRatio)
+ ScalingType.FIT -> minOf(widthRatio, heightRatio)
+ ScalingType.NONE, ScalingType.STRETCH -> 1f
+ }
+ val width = if (scaling == ScalingType.STRETCH) canvasW.toFloat() else source.width * scale
+ val height = if (scaling == ScalingType.STRETCH) canvasH.toFloat() else source.height * scale
+ val left = (canvasW - width) / 2f
+ val top = (canvasH - height) / 2f
+ val result = createBitmap(canvasW, canvasH)
+ Canvas(result).apply {
+ drawColor(Color.BLACK)
+ drawBitmap(source, null, RectF(left, top, left + width, top + height), Paint(Paint.FILTER_BITMAP_FLAG))
}
-}
-
-/**
- * Draw [source] centered on a new [canvasW]×[canvasH] black bitmap and return the result.
- * [source] is recycled unless it is the same object as the returned bitmap.
- */
-private fun compositeCenter(source: Bitmap, canvasW: Int, canvasH: Int): Bitmap {
- val canvas = Bitmap.createBitmap(canvasW, canvasH, Bitmap.Config.ARGB_8888)
- val c = Canvas(canvas)
- c.drawColor(Color.BLACK)
- val offsetX = ((canvasW - source.width) / 2f).coerceAtLeast(0f)
- val offsetY = ((canvasH - source.height) / 2f).coerceAtLeast(0f)
- c.drawBitmap(source, offsetX, offsetY, null)
source.recycle()
- return canvas
+ return result
}
-/**
- * Apply EXIF orientation to bitmap
- */
private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bitmap {
val orientation = uri.getExifOrientation(context)
if (orientation == ExifInterface.ORIENTATION_UNDEFINED || orientation == ExifInterface.ORIENTATION_NORMAL) {
@@ -453,120 +318,48 @@ private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bi
}
}
-
-
-
/**
* Darken the bitmap by a certain percentage
* @param darkenPercent 0-100 (0 is original brightness, 100 is completely dark/black)
*/
-fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap {
- if (!source.isMutable) {
- Log.w(TAG, "darkenBitmap received an immutable bitmap. Creating a mutable copy.")
- val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
- // Do not recycle source here — caller owns the lifecycle and handles recycling
- return darkenBitmap(mutableCopy, darkenPercent)
- }
-
- // Convert darkenPercent to brightness factor (invert)
- val targetBrightnessFactor = (100 - darkenPercent.coerceIn(0, 100)) / 100f
- if (targetBrightnessFactor >= 1.0f) {
- return source
- }
-
- val paint = Paint().apply {
- colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
- setScale(targetBrightnessFactor, targetBrightnessFactor, targetBrightnessFactor, 1f)
- })
- xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
- }
- Canvas(source).drawBitmap(source, 0f, 0f, paint)
- return source
-}
+fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap =
+ adjustBitmapBrightness(source, (100 - darkenPercent.coerceIn(0, 100)) / 100f)
/**
* Blur the bitmap using GPU acceleration
* @param percent 0-100
*/
-fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
- val clampedPercent = percent.coerceIn(0, 100)
- if (clampedPercent == 0) {
- return source
- }
-
- val maxBlurRadius = Constants.MAX_BLUR_RADIUS
- val radius = (clampedPercent / 100.0f) * maxBlurRadius
-
- val imageReader = ImageReader.newInstance(
- source.width, source.height,
- PixelFormat.RGBA_8888, 1,
- HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
- )
-
- val renderNode = RenderNode("BlurEffect")
- val hardwareRenderer = HardwareRenderer()
-
- var resultBitmap: Bitmap?
- try {
- hardwareRenderer.setSurface(imageReader.surface)
- hardwareRenderer.setContentRoot(renderNode)
- renderNode.setPosition(0, 0, source.width, source.height)
-
- val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP)
- renderNode.setRenderEffect(blurEffect)
-
- val canvas = renderNode.beginRecording()
- canvas.drawBitmap(source, 0f, 0f, null)
- renderNode.endRecording()
-
- hardwareRenderer.createRenderRequest()
- .setWaitForPresent(true)
- .syncAndDraw()
-
- val image = imageReader.acquireNextImage()
- ?: throw IllegalStateException("Failed to acquire blurred image")
-
- try {
- val hardwareBuffer = image.hardwareBuffer
- ?: throw IllegalStateException("Failed to acquire hardware buffer")
-
- try {
- val hardwareBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
- ?: throw IllegalStateException("Failed to create bitmap from hardware buffer")
-
- // Convert hardware bitmap to regular bitmap for further processing
- // Use mutable=true to allow subsequent effects to modify in-place
- resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, true)
- ?: throw IllegalStateException("Failed to copy hardware bitmap to software bitmap")
-
- hardwareBitmap.recycle()
- } finally {
- hardwareBuffer.close()
- }
- } finally {
- image.close()
- }
-
+fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
+ if (percent <= 0) return source
+ return try {
+ processBitmapGpu(source, false, 0, true, percent, false, 0, false, 0)
} catch (e: Exception) {
- Log.e(TAG, "Error blurring bitmap: $e")
- return source
+ Log.e(TAG, "Error blurring bitmap", e)
+ source
} catch (e: OutOfMemoryError) {
- Log.e(TAG, "OOM blurring bitmap: $e")
- return source
- } finally {
- hardwareRenderer.destroy()
- renderNode.discardDisplayList()
- imageReader.close()
+ Log.e(TAG, "OOM blurring bitmap", e)
+ source
}
-
- return resultBitmap
}
-/**
- * Blur bitmap using GPU acceleration
- */
-fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
- return blurBitmapHardware(source, percent)
+private fun drawVignette(canvas: Canvas, width: Int, height: Int, percent: Int) {
+ val centerX = width / 2f
+ val centerY = height / 2f
+ val radius = (kotlin.math.hypot(centerX, centerY) *
+ (1 - percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))
+ .coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = RadialGradient(
+ centerX, centerY, radius,
+ intArrayOf(
+ Color.TRANSPARENT,
+ Color.argb((Constants.VIGNETTE_INNER_ALPHA * 255).toInt(), 0, 0, 0),
+ Color.argb((Constants.VIGNETTE_OUTER_ALPHA * 255).toInt(), 0, 0, 0)
+ ),
+ Constants.VIGNETTE_GRADIENT_POSITIONS, Shader.TileMode.CLAMP
+ )
+ }
+ canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
}
/**
@@ -583,29 +376,7 @@ fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
}
return try {
- val canvas = Canvas(source)
- // Use corner-to-center diagonal so the vignette darkens uniformly in all directions
- val halfW = source.width / 2f
- val halfH = source.height / 2f
- val diagonal = kotlin.math.sqrt(halfW * halfW + halfH * halfH)
- val rad = (diagonal * (1 - (percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))).coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
- val centerX = source.width / 2f
- val centerY = source.height / 2f
-
- val colors = intArrayOf(
- Color.TRANSPARENT,
- Color.argb((Constants.VIGNETTE_INNER_ALPHA * 255).toInt(), 0, 0, 0),
- Color.argb((Constants.VIGNETTE_OUTER_ALPHA * 255).toInt(), 0, 0, 0)
- )
- val pos = Constants.VIGNETTE_GRADIENT_POSITIONS
-
- val vignettePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
- shader = RadialGradient(
- centerX, centerY, rad,
- colors, pos, Shader.TileMode.CLAMP
- )
- }
- canvas.drawRect(0f, 0f, source.width.toFloat(), source.height.toFloat(), vignettePaint)
+ drawVignette(Canvas(source), source.width, source.height, percent)
source
} catch (e: Exception) {
Log.e(TAG, "Error applying vignette: $e")
@@ -630,7 +401,6 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
}
val factor = percent.coerceIn(0, 100) / 100f
- if (factor <= 0f) return source
val colorMatrix = ColorMatrix().apply { setSaturation(1 - factor) }
val paint = Paint().apply {
@@ -642,14 +412,6 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
return source
}
-/**
- * Calculate brightness estimate of bitmap (0.0 - 1.0)
- * Uses luminance calculation based on RGB values
- */
-fun calculateBitmapBrightness(bitmap: Bitmap): Float {
- return BrightnessCalculator.calculateBitmapBrightness(bitmap)
-}
-
/**
* Adjust bitmap brightness by a multiplier
* @param brightnessFactor Brightness multiplier (e.g., 0.7 to darken, 1.5 to brighten)
@@ -673,14 +435,6 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
return source
}
-
-/**
- * Get adaptive brightness multiplier factor based on system dark/light mode
- *
- * @param context Application context
- * @param brightness Current image brightness (0.0 to 1.0)
- * @return Multiplier factor to apply to colors
- */
fun getAdaptiveBrightnessMultiplier(context: Context, brightness: Float): Float {
val isDarkMode = (context.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
@@ -704,16 +458,6 @@ fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
}
}
-/**
- * Process bitmap with all effects - now respects enable flags
- * Properly manages bitmap lifecycle by recycling intermediate results
- *
- * Uses a GPU-accelerated pipeline via [RenderEffect] chaining when possible (API 31+).
- * All colour-filter effects (darken, grayscale) and blur are composed into a single
- * RenderNode draw call so there is only **one** GPU→CPU copy at the end.
- * Vignette is drawn on the same RenderNode canvas before read-back.
- * Falls back to the sequential CPU path on error.
- */
fun processBitmap(
source: Bitmap,
enableDarken: Boolean = false,
@@ -725,14 +469,12 @@ fun processBitmap(
enableGrayscale: Boolean = false,
grayscalePercent: Int = 0
): Bitmap {
- // Fast path – nothing to do
val hasDarken = enableDarken && darkenPercent > 0
val hasBlur = enableBlur && blurPercent > 0
val hasVignette = enableVignette && vignettePercent > 0
val hasGrayscale = enableGrayscale && grayscalePercent > 0
if (!hasDarken && !hasBlur && !hasVignette && !hasGrayscale) return source
- // Try GPU-chained path
try {
return processBitmapGpu(
source,
@@ -747,7 +489,6 @@ fun processBitmap(
Log.w(TAG, "OOM in GPU effects pipeline, falling back to CPU: $e")
}
- // CPU fallback
return processBitmapCpu(
source,
hasDarken, darkenPercent,
@@ -785,7 +526,6 @@ private fun processBitmapGpu(
hardwareRenderer.setContentRoot(renderNode)
renderNode.setPosition(0, 0, w, h)
- // --- Build chained RenderEffect (darken → blur → grayscale) ---
var effect: RenderEffect? = null
if (hasDarken) {
@@ -820,56 +560,28 @@ private fun processBitmapGpu(
renderNode.setRenderEffect(effect)
}
- // --- Record canvas commands ---
val canvas = renderNode.beginRecording()
canvas.drawBitmap(source, 0f, 0f, null)
- // Vignette is an overlay drawn on top of the source in the same pass
if (hasVignette) {
- val halfW = w / 2f
- val halfH = h / 2f
- val diagonal = kotlin.math.sqrt(halfW * halfW + halfH * halfH)
- val rad = (diagonal * (1 - (vignettePercent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR)))
- .coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
- val colors = intArrayOf(
- Color.TRANSPARENT,
- Color.argb((Constants.VIGNETTE_INNER_ALPHA * 255).toInt(), 0, 0, 0),
- Color.argb((Constants.VIGNETTE_OUTER_ALPHA * 255).toInt(), 0, 0, 0)
- )
- val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
- shader = RadialGradient(
- halfW, halfH, rad,
- colors, Constants.VIGNETTE_GRADIENT_POSITIONS, Shader.TileMode.CLAMP
- )
- }
- canvas.drawRect(0f, 0f, w.toFloat(), h.toFloat(), paint)
+ drawVignette(canvas, w, h, vignettePercent)
}
renderNode.endRecording()
- // --- Single GPU render + single read-back ---
hardwareRenderer.createRenderRequest()
.setWaitForPresent(true)
.syncAndDraw()
- val image = imageReader.acquireNextImage()
- ?: throw IllegalStateException("Failed to acquire image after GPU render")
-
- try {
- val hwBuffer = image.hardwareBuffer
- ?: throw IllegalStateException("Failed to acquire hardware buffer")
- try {
- val hwBitmap = Bitmap.wrapHardwareBuffer(hwBuffer, null)
- ?: throw IllegalStateException("Failed to wrap hardware buffer")
- val result = hwBitmap.copy(Bitmap.Config.ARGB_8888, true)
- ?: throw IllegalStateException("Failed to copy hardware bitmap")
- hwBitmap.recycle()
- return result
- } finally {
- hwBuffer.close()
+ return checkNotNull(imageReader.acquireNextImage()) { "Failed to acquire rendered image" }.use { image ->
+ checkNotNull(image.hardwareBuffer) { "Failed to acquire hardware buffer" }.use { buffer ->
+ val bitmap = checkNotNull(Bitmap.wrapHardwareBuffer(buffer, null)) { "Failed to wrap hardware buffer" }
+ try {
+ checkNotNull(bitmap.copy(Bitmap.Config.ARGB_8888, true)) { "Failed to copy hardware bitmap" }
+ } finally {
+ bitmap.recycle()
+ }
}
- } finally {
- image.close()
}
} finally {
hardwareRenderer.destroy()
@@ -878,9 +590,6 @@ private fun processBitmapGpu(
}
}
-/**
- * CPU fallback: applies effects sequentially (original implementation).
- */
private fun processBitmapCpu(
source: Bitmap,
hasDarken: Boolean, darkenPercent: Int,
@@ -921,47 +630,6 @@ private fun processBitmapCpu(
return result
}
-/**
- * Detect media type from URI
- *
- * Examines the file extension and MIME type to determine the media type.
- * Returns null if the media type cannot be determined or is unsupported.
- */
-fun Uri.detectMediaType(context: Context): WallpaperMediaType? {
- try {
- // First try to get file extension from path
- val path = this.path
- if (path != null) {
- val extension = path.substringAfterLast('.', "")
- if (extension.isNotEmpty()) {
- val mediaType = WallpaperMediaType.fromExtension(extension)
- if (mediaType != null) {
- return mediaType
- }
- }
- }
-
- // Fallback: Try to get MIME type from content resolver
- val mimeType = context.contentResolver.getType(this)
- if (mimeType != null) {
- return when {
- mimeType.startsWith("image/") -> WallpaperMediaType.IMAGE
- else -> null
- }
- }
-
- // If all else fails, assume IMAGE for backward compatibility
- return WallpaperMediaType.IMAGE
- } catch (e: Exception) {
- Log.e(TAG, "Error detecting media type for URI: $this", e)
- return WallpaperMediaType.IMAGE // Default to IMAGE on error
- }
-}
-
-/**
- * Check if Paperize live wallpaper is currently active/selected
- * Returns true if the Paperize live wallpaper service is the current wallpaper
- */
fun isPaperizeLiveWallpaperActive(context: Context): Boolean {
return try {
// If we are checking from within the service itself (e.g. preview mode), we are active
@@ -973,13 +641,11 @@ fun isPaperizeLiveWallpaperActive(context: Context): Boolean {
val wallpaperManager = WallpaperManager.getInstance(context)
val wallpaperInfo = wallpaperManager.wallpaperInfo
- // If wallpaperInfo is null, user has a static wallpaper (not a live wallpaper)
if (wallpaperInfo == null) {
Log.d(TAG, "isPaperizeLiveWallpaperActive: wallpaperInfo is null (static wallpaper), returning false")
return false
}
- // Check if the service component matches Paperize live wallpaper
val expectedComponent = android.content.ComponentName(
context.packageName,
"com.anthonyla.paperize.service.livewallpaper.PaperizeLiveWallpaperService"
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/LibraryMigrations.kt b/app/src/main/java/com/anthonyla/paperize/data/database/LibraryMigrations.kt
new file mode 100644
index 0000000..22b05c4
--- /dev/null
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/LibraryMigrations.kt
@@ -0,0 +1,42 @@
+package com.anthonyla.paperize.data.database
+
+import androidx.room.migration.Migration
+import androidx.sqlite.db.SupportSQLiteDatabase
+
+/** Versions 1–3 used the same library tables, with extra crop columns in versions 2–3. */
+val LIBRARY_MIGRATIONS: Array = (1..3).map { version ->
+ object : Migration(version, 4) {
+ override fun migrate(db: SupportSQLiteDatabase) {
+ // Rebuilding the parent table would cascade-delete these rows; preserve them first.
+ db.execSQL("CREATE TEMP TABLE saved_queue AS SELECT * FROM wallpaper_queue")
+ db.execSQL("DROP TABLE wallpaper_queue")
+ if (version >= 3) {
+ db.execSQL("CREATE TEMP TABLE saved_current AS SELECT * FROM wallpaper_current")
+ db.execSQL("DROP TABLE wallpaper_current")
+ }
+ db.execSQL("CREATE TABLE IF NOT EXISTS `wallpapers_new` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )")
+ val mediaType = if (version == 1) "'IMAGE'" else "mediaType"
+ db.execSQL("""
+ INSERT INTO wallpapers_new (id, albumId, folderId, uri, fileName, dateModified, displayOrder, sourceType, addedAt, mediaType)
+ SELECT id, albumId, folderId, uri, fileName, dateModified, displayOrder, sourceType, addedAt, $mediaType FROM wallpapers
+ """)
+ db.execSQL("DROP TABLE wallpapers")
+ db.execSQL("ALTER TABLE wallpapers_new RENAME TO wallpapers")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `wallpapers` (`albumId`)")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `wallpapers` (`folderId`)")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `wallpapers` (`uri`)")
+ db.execSQL("CREATE TABLE IF NOT EXISTS `wallpaper_queue` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `wallpaper_queue` (`albumId`, `screenType`)")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `wallpaper_queue` (`wallpaperId`)")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `wallpaper_queue` (`queuePosition`)")
+ db.execSQL("CREATE TABLE IF NOT EXISTS `wallpaper_current` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )")
+ db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `wallpaper_current` (`wallpaperId`)")
+ db.execSQL("INSERT INTO wallpaper_queue SELECT * FROM saved_queue")
+ db.execSQL("DROP TABLE saved_queue")
+ if (version >= 3) {
+ db.execSQL("INSERT INTO wallpaper_current SELECT * FROM saved_current")
+ db.execSQL("DROP TABLE saved_current")
+ }
+ }
+ }
+}.toTypedArray()
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt b/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt
index 474952a..6595302 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/PaperizeDatabase.kt
@@ -16,19 +16,6 @@ import com.anthonyla.paperize.data.database.entities.WallpaperEntity
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
import com.anthonyla.paperize.core.constants.Constants
-/**
- * Paperize Room Database
- *
- * **MAJOR ARCHITECTURAL IMPROVEMENT:**
- * - Properly normalized schema (no nested collections in entities)
- * - NO CursorWindow reflection hack needed!
- * - Proper foreign keys with cascade delete
- * - Indexed columns for performance
- * - Separate queue management table
- * - Room migrations support (no destructive migrations!)
- *
- * Version: 1
- */
@Database(
entities = [
AlbumEntity::class,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt b/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt
index 4476a68..03d41ed 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt
@@ -2,13 +2,9 @@ package com.anthonyla.paperize.data.database.converters
import androidx.room.TypeConverter
import com.anthonyla.paperize.core.ScreenType
-import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.core.WallpaperSourceType
-/**
- * Room type converters for enum types
- */
class TypeConverters {
@TypeConverter
fun fromScreenType(value: ScreenType): String = value.name
@@ -16,12 +12,6 @@ class TypeConverters {
@TypeConverter
fun toScreenType(value: String): ScreenType = ScreenType.fromString(value)
- @TypeConverter
- fun fromScalingType(value: ScalingType): String = value.name
-
- @TypeConverter
- fun toScalingType(value: String): ScalingType = ScalingType.fromString(value)
-
@TypeConverter
fun fromWallpaperSourceType(value: WallpaperSourceType): String = value.name
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt
index 21d30d0..68d3e00 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/AlbumDao.kt
@@ -1,26 +1,17 @@
package com.anthonyla.paperize.data.database.dao
import androidx.room.Dao
-import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
-import androidx.room.Update
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
import kotlinx.coroutines.flow.Flow
-/**
- * Data Access Object for Album operations
- */
@Dao
interface AlbumDao {
- /**
- * Get all album summaries (lightweight metadata + counts)
- * Efficiently handles large libraries by avoiding loading all wallpaper objects
- */
@Query("""
SELECT
a.id,
@@ -35,89 +26,28 @@ interface AlbumDao {
""")
fun getAlbumSummaries(): Flow>
- /**
- * Get all albums with their wallpapers and folders
- */
- @Transaction
- @Query("SELECT * FROM albums ORDER BY modifiedAt DESC")
- fun getAllAlbumsWithDetails(): Flow>
-
- /**
- * Get a specific album by ID with details
- */
@Transaction
@Query("SELECT * FROM albums WHERE id = :albumId")
fun getAlbumWithDetails(albumId: String): Flow
- /**
- * Get all albums (without relations)
- */
- @Query("SELECT * FROM albums ORDER BY modifiedAt DESC")
- fun getAllAlbums(): Flow>
-
- /**
- * Get a specific album by ID
- */
@Query("SELECT * FROM albums WHERE id = :albumId")
suspend fun getAlbumById(albumId: String): AlbumEntity?
- /**
- * Get a specific album by name
- */
@Query("SELECT * FROM albums WHERE name = :name LIMIT 1")
suspend fun getAlbumByName(name: String): AlbumEntity?
- /**
- * Get album count
- */
- @Query("SELECT COUNT(*) FROM albums")
- suspend fun getAlbumCount(): Int
-
- /**
- * Insert album
- */
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAlbum(album: AlbumEntity)
- /**
- * Update album
- */
- @Update
- suspend fun updateAlbum(album: AlbumEntity)
-
- /**
- * Delete album
- */
- @Delete
- suspend fun deleteAlbum(album: AlbumEntity)
-
- /**
- * Delete album by ID
- */
@Query("DELETE FROM albums WHERE id = :albumId")
suspend fun deleteAlbumById(albumId: String)
- /**
- * Update album name
- */
- @Query("UPDATE albums SET name = :name, modifiedAt = :modifiedAt WHERE id = :albumId")
- suspend fun updateAlbumName(albumId: String, name: String, modifiedAt: Long)
-
- /**
- * Update album cover
- */
@Query("UPDATE albums SET coverUri = :coverUri, modifiedAt = :modifiedAt WHERE id = :albumId")
suspend fun updateAlbumCover(albumId: String, coverUri: String?, modifiedAt: Long)
- /**
- * Update album modified time
- */
@Query("UPDATE albums SET modifiedAt = :modifiedAt WHERE id = :albumId")
suspend fun updateAlbumModifiedTime(albumId: String, modifiedAt: Long)
- /**
- * Delete all albums
- */
@Query("DELETE FROM albums")
suspend fun deleteAllAlbums()
}
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/FolderDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/FolderDao.kt
index ec7ba8e..06d6772 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/FolderDao.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/FolderDao.kt
@@ -5,13 +5,24 @@ import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
-import androidx.room.Update
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
import kotlinx.coroutines.flow.Flow
@Dao
interface FolderDao {
+ @Query("SELECT * FROM folders WHERE albumId = :albumId ORDER BY displayOrder, id")
+ suspend fun getFoldersByAlbum(albumId: String): List
+
+ @Query("DELETE FROM folders WHERE id = :folderId AND albumId = :albumId")
+ suspend fun deleteAlbumFolder(albumId: String, folderId: String): Int
+
+ @Query("SELECT EXISTS(SELECT 1 FROM folders WHERE albumId = :albumId AND uri = :uri)")
+ suspend fun containsUri(albumId: String, uri: String): Boolean
+
+ @Query("SELECT COALESCE(MAX(displayOrder), -1) FROM folders WHERE albumId = :albumId")
+ suspend fun getMaxOrder(albumId: String): Int
+
@Transaction
@Query("SELECT * FROM folders WHERE id = :folderId")
fun getFolderWithWallpapers(folderId: String): Flow
@@ -22,8 +33,8 @@ interface FolderDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFolder(folder: FolderEntity)
- @Update
- suspend fun updateFolder(folder: FolderEntity)
+ @Query("UPDATE folders SET displayOrder = :order WHERE id = :folderId AND albumId = :albumId")
+ suspend fun updateFolderOrder(albumId: String, folderId: String, order: Int)
@Query("UPDATE folders SET coverUri = :coverUri WHERE id = :folderId")
suspend fun updateFolderCover(folderId: String, coverUri: String?)
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt
index 491c8b5..ca4cbd9 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt
@@ -24,7 +24,6 @@ interface WallpaperCurrentDao {
""")
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity?
- /** Reactive variant of [getCurrentWallpaper]; re-emits when the recorded wallpaper changes. */
@Query("""
SELECT w.* FROM wallpapers w
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
@@ -33,7 +32,6 @@ interface WallpaperCurrentDao {
""")
fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow
- /** Record (or overwrite) the current wallpaper for an album/screen pair. */
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsertCurrentWallpaper(entity: WallpaperCurrentEntity)
}
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt
index 9285f6d..4509c06 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperDao.kt
@@ -1,27 +1,25 @@
package com.anthonyla.paperize.data.database.dao
import androidx.room.Dao
-import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
-import kotlinx.coroutines.flow.Flow
@Dao
interface WallpaperDao {
- @Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
- fun getWallpapersByAlbum(albumId: String): Flow>
+ @Query("DELETE FROM wallpapers WHERE albumId = :albumId AND id IN (:ids)")
+ suspend fun deleteAlbumWallpapers(albumId: String, ids: List): Int
- @Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND folderId IS NULL ORDER BY displayOrder ASC")
- fun getDirectWallpapersByAlbum(albumId: String): Flow>
+ @Query("SELECT uri FROM wallpapers WHERE albumId = :albumId AND folderId IS :folderId")
+ suspend fun getUrisInCollection(albumId: String, folderId: String?): List
- @Query("SELECT EXISTS(SELECT 1 FROM wallpapers WHERE albumId = :albumId AND uri = :uri)")
- suspend fun containsUri(albumId: String, uri: String): Boolean
+ @Query("SELECT COALESCE(MAX(displayOrder), -1) FROM wallpapers WHERE albumId = :albumId")
+ suspend fun getMaxOrder(albumId: String): Int
- @Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC, id ASC LIMIT :limit OFFSET :offset")
- suspend fun getWallpapersByAlbumPaged(albumId: String, limit: Int, offset: Int): List
+ @Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND (:afterId IS NULL OR id > :afterId) ORDER BY id LIMIT :limit")
+ suspend fun getWallpapersByAlbumPage(albumId: String, limit: Int, afterId: String?): List
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId ORDER BY folderId IS NOT NULL, displayOrder, id LIMIT 1")
suspend fun getAlbumCoverUri(albumId: String): String?
@@ -29,9 +27,6 @@ interface WallpaperDao {
@Query("SELECT uri FROM wallpapers WHERE folderId = :folderId ORDER BY displayOrder, id LIMIT 1")
suspend fun getFolderCoverUri(folderId: String): String?
- @Query("SELECT * FROM wallpapers WHERE folderId = :folderId ORDER BY displayOrder ASC")
- fun getWallpapersByFolder(folderId: String): Flow>
-
@Query("SELECT * FROM wallpapers WHERE id = :wallpaperId")
suspend fun getWallpaperById(wallpaperId: String): WallpaperEntity?
@@ -44,17 +39,8 @@ interface WallpaperDao {
@Update
suspend fun updateWallpaper(wallpaper: WallpaperEntity)
- @Query("UPDATE wallpapers SET displayOrder = :order WHERE id = :wallpaperId")
- suspend fun updateWallpaperOrder(wallpaperId: String, order: Int)
-
- @Delete
- suspend fun deleteWallpaper(wallpaper: WallpaperEntity)
-
- @Query("DELETE FROM wallpapers WHERE id = :wallpaperId")
- suspend fun deleteWallpaperById(wallpaperId: String)
-
- @Query("DELETE FROM wallpapers WHERE id IN (:wallpaperIds)")
- suspend fun deleteWallpapersByIds(wallpaperIds: List)
+ @Query("UPDATE wallpapers SET displayOrder = :order WHERE id = :wallpaperId AND albumId = :albumId")
+ suspend fun updateAlbumWallpaperOrder(albumId: String, wallpaperId: String, order: Int)
@Query("DELETE FROM wallpapers WHERE folderId = :folderId")
suspend fun deleteWallpapersByFolder(folderId: String)
@@ -62,23 +48,9 @@ interface WallpaperDao {
@Query("SELECT COUNT(*) FROM wallpapers WHERE albumId = :albumId")
suspend fun getWallpaperCountByAlbum(albumId: String): Int
- /**
- * Get wallpaper IDs only for queue building (shuffle mode).
- * Avoids loading full entities when only IDs are needed.
- */
@Query("SELECT id FROM wallpapers WHERE albumId = :albumId")
suspend fun getWallpaperIdsByAlbum(albumId: String): List
- /**
- * Get wallpaper IDs with display order for queue building (sequential mode).
- * Avoids loading full entities when only ID + order are needed.
- */
- @Query("SELECT id, displayOrder FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
- suspend fun getWallpaperIdsAndOrderByAlbum(albumId: String): List
+ @Query("SELECT id FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder, id")
+ suspend fun getOrderedWallpaperIdsByAlbum(albumId: String): List
}
-
-/** Lightweight projection used for queue building — avoids loading full WallpaperEntity. */
-data class WallpaperIdAndOrder(
- val id: String,
- val displayOrder: Int
-)
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt
index 0d9edf0..3142cdc 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt
@@ -9,16 +9,8 @@ import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
-/**
- * Data Access Object for Wallpaper Queue operations
- *
- * This replaces the manual queue management in the old Album entity
- */
@Dao
interface WallpaperQueueDao {
- /**
- * Get next wallpaper in queue
- */
@Query("""
SELECT w.* FROM wallpapers w
INNER JOIN wallpaper_queue wq ON w.id = wq.wallpaperId
@@ -28,39 +20,21 @@ interface WallpaperQueueDao {
""")
suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): WallpaperEntity?
- /**
- * Atomically get and remove next wallpaper from queue
- * This prevents race conditions when multiple services try to get wallpapers simultaneously
- */
@Transaction
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? {
val wallpaper = getNextWallpaperInQueue(albumId, screenType)
if (wallpaper != null) {
- // Delete specifically the item we just retrieved to ensure atomicity
deleteQueueItem(albumId, screenType, wallpaper.id)
}
return wallpaper
}
- /**
- * Get queue items for album and screen type
- */
@Query("SELECT * FROM wallpaper_queue WHERE albumId = :albumId AND screenType = :screenType ORDER BY queuePosition ASC")
suspend fun getQueueItems(albumId: String, screenType: ScreenType): List
- /**
- * Insert multiple queue items
- */
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertQueueItems(items: List)
- /**
- * Delete a specific queue item by wallpaperId.
- *
- * The MIN() subquery was removed because [getAndDequeueWallpaper] already retrieves
- * the item at the minimum position before calling this, so the subquery is redundant.
- * The [wallpaperId] index makes this O(log n) instead of O(n) with the subquery.
- */
@Query("""
DELETE FROM wallpaper_queue
WHERE albumId = :albumId AND screenType = :screenType
@@ -74,9 +48,6 @@ interface WallpaperQueueDao {
""")
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,
@@ -97,27 +68,15 @@ interface WallpaperQueueDao {
)
}
- /**
- * Clear queue for album and screen type
- */
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId AND screenType = :screenType")
suspend fun clearQueue(albumId: String, screenType: ScreenType)
- /**
- * Clear all queues for an album
- */
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId")
suspend fun clearAllQueues(albumId: String)
- /**
- * Delete all queue items
- */
@Query("DELETE FROM wallpaper_queue")
suspend fun deleteAllQueueItems()
- /**
- * Rebuild queue with wallpaper IDs
- */
@Transaction
suspend fun rebuildQueue(
albumId: String,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt
index c9b5a55..bbefd33 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumEntity.kt
@@ -3,11 +3,6 @@ package com.anthonyla.paperize.data.database.entities
import androidx.room.Entity
import androidx.room.PrimaryKey
-/**
- * Room entity for Album
- *
- * Stores album metadata without nested collections to avoid CursorWindow issues
- */
@Entity(tableName = "albums")
data class AlbumEntity(
@PrimaryKey
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumSummaryEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumSummaryEntity.kt
index bcd5047..c90503c 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumSummaryEntity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/AlbumSummaryEntity.kt
@@ -1,8 +1,5 @@
package com.anthonyla.paperize.data.database.entities
-/**
- * Entity for holding lightweight album summary query results
- */
data class AlbumSummaryEntity(
val id: String,
val name: String,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/FolderEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/FolderEntity.kt
index cf6538a..2603ec4 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/FolderEntity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/FolderEntity.kt
@@ -1,16 +1,10 @@
package com.anthonyla.paperize.data.database.entities
-import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
-/**
- * Room entity for Folder
- *
- * No longer stores nested wallpapers - they're separate entities with foreign keys
- */
@Entity(
tableName = "folders",
foreignKeys = [
@@ -30,7 +24,6 @@ data class FolderEntity(
@PrimaryKey
val id: String,
- @ColumnInfo(name = "albumId")
val albumId: String,
val name: String,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperCurrentEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperCurrentEntity.kt
index b2d0b23..e9e6b45 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperCurrentEntity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperCurrentEntity.kt
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.data.database.entities
-import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
@@ -33,12 +32,10 @@ import com.anthonyla.paperize.core.ScreenType
indices = [Index(value = ["wallpaperId"])]
)
data class WallpaperCurrentEntity(
- @ColumnInfo(name = "albumId")
val albumId: String,
val screenType: ScreenType,
- @ColumnInfo(name = "wallpaperId")
val wallpaperId: String,
val appliedAt: Long = System.currentTimeMillis()
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt
index c304fcc..ac147e1 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt
@@ -1,6 +1,5 @@
package com.anthonyla.paperize.data.database.entities
-import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
@@ -8,11 +7,6 @@ import androidx.room.PrimaryKey
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.core.WallpaperSourceType
-/**
- * Room entity for Wallpaper
- *
- * Properly indexed foreign key to Album and optional foreign key to Folder
- */
@Entity(
tableName = "wallpapers",
foreignKeys = [
@@ -39,10 +33,8 @@ data class WallpaperEntity(
@PrimaryKey
val id: String,
- @ColumnInfo(name = "albumId")
val albumId: String,
- @ColumnInfo(name = "folderId")
val folderId: String? = null,
val uri: String,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperQueueEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperQueueEntity.kt
index b60b078..cb14973 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperQueueEntity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperQueueEntity.kt
@@ -1,18 +1,11 @@
package com.anthonyla.paperize.data.database.entities
-import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.anthonyla.paperize.core.ScreenType
-/**
- * Room entity for Wallpaper Queue
- *
- * Properly manages wallpaper queues instead of storing them as JSON lists in Album
- * Separate queues for HOME and LOCK screens
- */
@Entity(
tableName = "wallpaper_queue",
foreignKeys = [
@@ -39,10 +32,8 @@ data class WallpaperQueueEntity(
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
- @ColumnInfo(name = "albumId")
val albumId: String,
- @ColumnInfo(name = "wallpaperId")
val wallpaperId: String,
val screenType: ScreenType,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/relations/AlbumWithDetails.kt b/app/src/main/java/com/anthonyla/paperize/data/database/relations/AlbumWithDetails.kt
index fe144a6..1c79f60 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/relations/AlbumWithDetails.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/relations/AlbumWithDetails.kt
@@ -6,12 +6,6 @@ import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
-/**
- * Room relation combining Album with its Wallpapers and Folders
- *
- * This replaces the old AlbumWithWallpaperAndFolder but with proper foreign keys
- * No nested collections in entities - avoiding CursorWindow issues!
- */
data class AlbumWithDetails(
@Embedded
val album: AlbumEntity,
@@ -29,19 +23,4 @@ data class AlbumWithDetails(
entity = FolderEntity::class
)
val folders: List = emptyList()
-) {
- /**
- * Get direct wallpapers (not from folders)
- */
- val directWallpapers: List
- get() = wallpapers.filter { it.folderId == null }
-
- /**
- * Get total count including folder wallpapers
- */
- fun getTotalWallpaperCount(folderWallpapers: Map): Int {
- val directCount = directWallpapers.size
- val folderCount = folders.sumOf { folderWallpapers[it.id] ?: 0 }
- return directCount + folderCount
- }
-}
+)
diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/relations/FolderWithWallpapers.kt b/app/src/main/java/com/anthonyla/paperize/data/database/relations/FolderWithWallpapers.kt
index b62e7ad..fd5a519 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/database/relations/FolderWithWallpapers.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/database/relations/FolderWithWallpapers.kt
@@ -5,9 +5,6 @@ import androidx.room.Relation
import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
-/**
- * Room relation combining Folder with its Wallpapers
- */
data class FolderWithWallpapers(
@Embedded
val folder: FolderEntity,
diff --git a/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt b/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt
index 89709ba..b9f7132 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt
@@ -6,9 +6,9 @@ import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
-import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
+import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.constants.Constants
@@ -22,35 +22,17 @@ import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
-/**
- * Context extension for DataStore
- */
private val Context.dataStore: DataStore by preferencesDataStore(
name = Constants.PREFERENCES_NAME
)
-/**
- * PreferencesManager - Clean interface for DataStore operations
- *
- * Replaces the old SettingsDataStore with better organization and type safety
- */
@Singleton
class PreferencesManager @Inject constructor(
context: Context
) {
private val dataStore = context.dataStore
- // ============ App Settings ============
-
- suspend fun getAppSettings(): AppSettings {
- val prefs = dataStore.data.first()
- return AppSettings(
- darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)],
- dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: false,
- animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
- firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true
- )
- }
+ suspend fun getAppSettings(): AppSettings = getAppSettingsFlow().first()
fun getAppSettingsFlow(): Flow = dataStore.data.map { prefs ->
AppSettings(
@@ -61,182 +43,93 @@ class PreferencesManager @Inject constructor(
)
}
- suspend fun updateAppSettings(settings: AppSettings) {
- dataStore.edit { prefs ->
- if (settings.darkMode != null) {
- prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = settings.darkMode
- } else {
- prefs.remove(booleanPreferencesKey(PreferenceKeys.DARK_MODE))
- }
- prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = settings.dynamicTheming
- prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = settings.animate
- prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = settings.firstLaunch
- }
- }
+ suspend fun getWallpaperMode(): WallpaperMode = getWallpaperModeFlow().first()
- // ============ Wallpaper Mode ============
-
- /**
- * Get current wallpaper mode (STATIC or LIVE)
- * Defaults to STATIC for new installations and backward compatibility
- */
- suspend fun getWallpaperMode(): WallpaperMode {
- val prefs = dataStore.data.first()
- val modeString = prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]
- return WallpaperMode.fromString(modeString)
- }
-
- /**
- * Get wallpaper mode as a Flow for reactive updates
- */
fun getWallpaperModeFlow(): Flow = dataStore.data.map { prefs ->
val modeString = prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]
WallpaperMode.fromString(modeString)
}
- /**
- * Update wallpaper mode
- * IMPORTANT: Caller should handle data reset when switching modes
- */
+ /** The caller must reset library and schedule data when switching modes. */
suspend fun updateWallpaperMode(mode: WallpaperMode) {
dataStore.edit { prefs ->
prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)] = mode.name
}
}
- // ============ Schedule Settings ============
+ suspend fun getScheduleSettings(): ScheduleSettings = getScheduleSettingsFlow().first()
- suspend fun getScheduleSettings(): ScheduleSettings {
- val prefs = dataStore.data.first()
- return ScheduleSettings(
- enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
- separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
- shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
- homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
- lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
- homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
- lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
- liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
- homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
- ?: Constants.DEFAULT_INTERVAL_MINUTES,
- lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
- ?: Constants.DEFAULT_INTERVAL_MINUTES,
- liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
- ?: Constants.DEFAULT_INTERVAL_MINUTES,
- homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
- lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
- liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
- homeScrollingEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED)] ?: false,
- homeEffects = WallpaperEffects(
- enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
- blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
- enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
- darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
- enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
- vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
- enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
- grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
- enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
- enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
- parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
- ),
- lockEffects = WallpaperEffects(
- enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
- blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
- enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
- darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
- enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
- vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
- enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
- grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
- enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
- enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
- parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
- ),
- liveEffects = WallpaperEffects(
- enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] ?: false,
- blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] ?: 0,
- enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] ?: false,
- darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
- enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
- vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
- enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
- grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
- enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
- enableChangeOnScreenOff = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF)] ?: false,
- enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
- parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
- ),
- adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
- )
- }
+ fun getScheduleSettingsFlow(): Flow = dataStore.data.map(::scheduleSettings)
- fun getScheduleSettingsFlow(): Flow = dataStore.data.map { prefs ->
- ScheduleSettings(
- enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
- separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
- shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
- homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
- lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
- homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
- lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
- liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
- homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
- ?: Constants.DEFAULT_INTERVAL_MINUTES,
- lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
- ?: Constants.DEFAULT_INTERVAL_MINUTES,
- liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
- ?: Constants.DEFAULT_INTERVAL_MINUTES,
- homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
- lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
- liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
- homeScrollingEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED)] ?: false,
- homeEffects = WallpaperEffects(
- enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
- blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
- enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
- darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
- enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
- vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
- enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
- grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
- enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
- enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
- parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
- ),
- lockEffects = WallpaperEffects(
- enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
- blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
- enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
- darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
- enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
- vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
- enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
- grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
- enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
- enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
- parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
- ),
- liveEffects = WallpaperEffects(
- enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] ?: false,
- blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] ?: 0,
- enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] ?: false,
- darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
- enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
- vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
- enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
- grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
- enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
- enableChangeOnScreenOff = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF)] ?: false,
- enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
- parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
- ),
- adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
- )
- }
+ private fun scheduleSettings(prefs: Preferences): ScheduleSettings = ScheduleSettings(
+ enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
+ separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
+ shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
+ homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
+ lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
+ homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
+ lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
+ liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
+ homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
+ ?: Constants.DEFAULT_INTERVAL_MINUTES,
+ lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
+ ?: Constants.DEFAULT_INTERVAL_MINUTES,
+ liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
+ ?: Constants.DEFAULT_INTERVAL_MINUTES,
+ homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
+ lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
+ liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
+ homeScrollingEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED)] ?: false,
+ homeEffects = WallpaperEffects(
+ enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
+ blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
+ enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
+ darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
+ enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
+ vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
+ enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
+ grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
+ enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
+ enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
+ parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
+ ),
+ lockEffects = WallpaperEffects(
+ enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
+ blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
+ enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
+ darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
+ enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
+ vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
+ enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
+ grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
+ enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
+ enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
+ parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
+ ),
+ liveEffects = WallpaperEffects(
+ enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] ?: false,
+ blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] ?: 0,
+ enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] ?: false,
+ darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
+ enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
+ vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
+ enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
+ grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
+ enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
+ enableChangeOnScreenOff = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF)] ?: false,
+ enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
+ parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
+ ),
+ adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
+ )
suspend fun updateScheduleSettings(settings: ScheduleSettings) {
- dataStore.edit { prefs ->
+ updateScheduleSettings { settings }
+ }
+
+ suspend fun updateScheduleSettings(transform: (ScheduleSettings) -> ScheduleSettings): ScheduleSettings {
+ val updated = dataStore.edit { prefs ->
+ val settings = transform(scheduleSettings(prefs))
prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] = settings.enableChanger
prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] = settings.separateSchedules
prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] = settings.shuffleEnabled
@@ -265,7 +158,6 @@ class PreferencesManager @Inject constructor(
prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)] = settings.liveScalingType.name
prefs[booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED)] = settings.homeScrollingEnabled
- // Home effects
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] = settings.homeEffects.enableBlur
prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] = settings.homeEffects.blurPercentage
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] = settings.homeEffects.enableDarken
@@ -278,7 +170,6 @@ class PreferencesManager @Inject constructor(
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] = settings.homeEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] = settings.homeEffects.parallaxIntensity
- // Lock effects
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] = settings.lockEffects.enableBlur
prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] = settings.lockEffects.blurPercentage
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] = settings.lockEffects.enableDarken
@@ -291,7 +182,6 @@ class PreferencesManager @Inject constructor(
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] = settings.lockEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] = settings.lockEffects.parallaxIntensity
- // Live effects
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] = settings.liveEffects.enableBlur
prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] = settings.liveEffects.blurPercentage
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] = settings.liveEffects.enableDarken
@@ -305,17 +195,11 @@ class PreferencesManager @Inject constructor(
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] = settings.liveEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] = settings.liveEffects.parallaxIntensity
- // Adaptive brightness
prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] = settings.adaptiveBrightness
}
+ return scheduleSettings(updated)
}
- // ============ Atomic Album Selection Operations ============
-
- /**
- * Atomically update home album ID without race conditions
- * This prevents lost updates when both home and lock albums are selected simultaneously
- */
suspend fun updateHomeAlbumId(albumId: String?) {
dataStore.edit { prefs ->
if (albumId != null) {
@@ -326,10 +210,6 @@ class PreferencesManager @Inject constructor(
}
}
- /**
- * Atomically update lock album ID without race conditions
- * This prevents lost updates when both home and lock albums are selected simultaneously
- */
suspend fun updateLockAlbumId(albumId: String?) {
dataStore.edit { prefs ->
if (albumId != null) {
@@ -340,9 +220,6 @@ class PreferencesManager @Inject constructor(
}
}
- /**
- * Atomically update live album ID without race conditions
- */
suspend fun updateLiveAlbumId(albumId: String?) {
dataStore.edit { prefs ->
if (albumId != null) {
@@ -353,186 +230,68 @@ class PreferencesManager @Inject constructor(
}
}
- /**
- * Atomically clear album selections if they match the given album ID
- * Used when deleting an album to prevent race conditions
- * Returns true if any selections were cleared
- */
suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean {
var wasCleared = false
dataStore.edit { prefs ->
- // Reset on each attempt — DataStore may retry the lambda on concurrent write conflicts
- wasCleared = false
-
- val homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)]
- val lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)]
- val liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)]
-
- // Clear home album if it matches
- if (homeAlbumId == albumId) {
- prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
- wasCleared = true
- }
-
- // Clear lock album if it matches
- if (lockAlbumId == albumId) {
- prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
- wasCleared = true
- }
-
- // Clear live album if it matches
- if (liveAlbumId == albumId) {
- prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
- wasCleared = true
- }
+ val targets = listOf(PreferenceKeys.HOME_ALBUM_ID, PreferenceKeys.LOCK_ALBUM_ID, PreferenceKeys.LIVE_ALBUM_ID)
+ .map(::stringPreferencesKey).filter { prefs[it] == albumId }
+ targets.forEach { prefs.remove(it) }
+ wasCleared = targets.isNotEmpty()
}
return wasCleared
}
- // ============ Atomic AppSettings Operations ============
+ suspend fun clearEmptyAlbumSelection(albumId: String, screen: ScreenType) {
+ dataStore.edit { prefs ->
+ val targets = when (screen) {
+ ScreenType.HOME -> listOf(PreferenceKeys.HOME_ALBUM_ID)
+ ScreenType.LOCK -> listOf(PreferenceKeys.LOCK_ALBUM_ID)
+ ScreenType.BOTH -> listOf(PreferenceKeys.HOME_ALBUM_ID, PreferenceKeys.LOCK_ALBUM_ID)
+ ScreenType.LIVE -> listOf(PreferenceKeys.LIVE_ALBUM_ID)
+ }.map(::stringPreferencesKey).filter { prefs[it] == albumId }
+ if (targets.isEmpty()) return@edit
+ targets.forEach { prefs.remove(it) }
+ val active = if (WallpaperMode.fromString(prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]) == WallpaperMode.LIVE) {
+ prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)] != null
+ } else {
+ (prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] == true && prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)] != null) ||
+ (prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] == true && prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)] != null)
+ }
+ if (!active) prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] = false
+ }
+ }
- /**
- * Atomically update dark mode setting without race conditions
- */
suspend fun updateDarkMode(enabled: Boolean) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = enabled
}
}
- /**
- * Atomically update dynamic theming setting without race conditions
- */
suspend fun updateDynamicTheming(enabled: Boolean) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = enabled
}
}
- /**
- * Atomically update animate setting without race conditions
- */
suspend fun updateAnimate(enabled: Boolean) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = enabled
}
}
- /**
- * Atomically update first launch setting without race conditions
- */
suspend fun updateFirstLaunch(isFirstLaunch: Boolean) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = isFirstLaunch
}
}
- // ============ Atomic ScheduleSettings Operations ============
-
- /**
- * Atomically update enableChanger setting without race conditions
- */
suspend fun updateEnableChanger(enabled: Boolean) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] = enabled
}
}
- // ============ Individual Preference Operations ============
-
- suspend fun setValue(key: String, value: T) {
- dataStore.edit { prefs ->
- when (value) {
- is Boolean -> prefs[booleanPreferencesKey(key)] = value
- is Int -> prefs[intPreferencesKey(key)] = value
- is Long -> prefs[longPreferencesKey(key)] = value
- is String -> prefs[stringPreferencesKey(key)] = value
- else -> throw IllegalArgumentException("Unsupported preference type")
- }
- }
- }
-
- suspend fun getValue(key: String, defaultValue: T): T {
- val prefs = dataStore.data.first()
- @Suppress("UNCHECKED_CAST")
- return when (defaultValue) {
- is Boolean -> prefs[booleanPreferencesKey(key)] ?: defaultValue
- is Int -> prefs[intPreferencesKey(key)] ?: defaultValue
- is Long -> prefs[longPreferencesKey(key)] ?: defaultValue
- is String -> prefs[stringPreferencesKey(key)] ?: defaultValue
- else -> throw IllegalArgumentException("Unsupported preference type")
- } as T
- }
-
- /**
- * Clear schedule settings (reset to defaults)
- * Used when switching wallpaper modes
- */
- suspend fun clearScheduleSettings() {
- dataStore.edit { prefs ->
- // Clear scheduling settings
- prefs.remove(booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLED))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED))
- prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
- prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
- prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
- prefs.remove(intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES))
- prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES))
- prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES))
-
- // Clear home effects
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR))
- prefs.remove(intPreferencesKey(PreferenceKeys.HOME_BLUR))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN))
- prefs.remove(intPreferencesKey(PreferenceKeys.HOME_DARKEN))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE))
- prefs.remove(intPreferencesKey(PreferenceKeys.HOME_VIGNETTE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE))
- prefs.remove(intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX))
- prefs.remove(intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY))
-
- // Clear lock effects
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR))
- prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_BLUR))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN))
- prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_DARKEN))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE))
- prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE))
- prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX))
- prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY))
-
- // Clear live effects
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR))
- prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_BLUR))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN))
- prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_DARKEN))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE))
- prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE))
- prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX))
- prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY))
-
- // Clear scaling
- prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE))
- prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE))
- prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE))
- prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_SCROLLING_ENABLED))
-
- // Clear adaptive brightness
- prefs.remove(booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS))
- }
- }
+ suspend fun clearScheduleSettings() = updateScheduleSettings(ScheduleSettings())
suspend fun clear() {
dataStore.edit { it.clear() }
diff --git a/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt b/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt
index c42b0a0..b217462 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/mapper/AlbumMapper.kt
@@ -4,10 +4,6 @@ import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
import com.anthonyla.paperize.domain.model.Album
-/**
- * Mappers for Album entity <-> domain model conversion
- */
-
fun AlbumEntity.toDomainModel(
wallpapers: List = emptyList(),
folders: List = emptyList()
@@ -30,7 +26,6 @@ fun Album.toEntity(): AlbumEntity = AlbumEntity(
)
fun AlbumWithDetails.toDomainModel(): Album {
- // Optimization: Group wallpapers by folderId once to avoid repeated filtering
val wallpapersByFolder = wallpapers.groupBy { it.folderId }
val domainWallpapers = wallpapersByFolder[null]?.map { it.toDomainModel() } ?: emptyList()
@@ -46,10 +41,6 @@ fun AlbumWithDetails.toDomainModel(): Album {
)
}
-fun List.toDomainModels(): List = map { it.toDomainModel() }
-
-fun List.toDomainModelsFromRelations(): List = map { it.toDomainModel() }
-
fun com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity.toDomainModel(): com.anthonyla.paperize.domain.model.AlbumSummary =
com.anthonyla.paperize.domain.model.AlbumSummary(
id = id,
@@ -60,6 +51,3 @@ fun com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity.toDomainMod
createdAt = createdAt,
modifiedAt = modifiedAt
)
-
-fun List.toDomainModelsFromSummaries(): List =
- map { it.toDomainModel() }
diff --git a/app/src/main/java/com/anthonyla/paperize/data/mapper/FolderMapper.kt b/app/src/main/java/com/anthonyla/paperize/data/mapper/FolderMapper.kt
index 8f57b31..bbb751b 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/mapper/FolderMapper.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/mapper/FolderMapper.kt
@@ -4,10 +4,6 @@ import com.anthonyla.paperize.data.database.entities.FolderEntity
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
import com.anthonyla.paperize.domain.model.Folder
-/**
- * Mappers for Folder entity <-> domain model conversion
- */
-
fun FolderEntity.toDomainModel(
wallpapers: List = emptyList()
): Folder = Folder(
@@ -36,7 +32,3 @@ fun Folder.toEntity(): FolderEntity = FolderEntity(
fun FolderWithWallpapers.toDomainModel(): Folder = folder.toDomainModel(
wallpapers = wallpapers.map { it.toDomainModel() }
)
-
-fun List.toDomainModels(): List = map { it.toDomainModel() }
-
-fun List.toDomainModelsFromRelations(): List = map { it.toDomainModel() }
diff --git a/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt b/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt
index 00c0676..2436920 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt
@@ -3,10 +3,6 @@ package com.anthonyla.paperize.data.mapper
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
import com.anthonyla.paperize.domain.model.Wallpaper
-/**
- * Mappers for Wallpaper entity <-> domain model conversion
- */
-
fun WallpaperEntity.toDomainModel(): Wallpaper = Wallpaper(
id = id,
albumId = albumId,
@@ -32,7 +28,3 @@ fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
addedAt = addedAt,
mediaType = mediaType
)
-
-fun List.toDomainModels(): List = map { it.toDomainModel() }
-
-fun List.toEntities(): List = map { it.toEntity() }
diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt
index 2364dfd..d755a8a 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/repository/AlbumRepositoryImpl.kt
@@ -1,56 +1,37 @@
package com.anthonyla.paperize.data.repository
-import android.content.Context
-import android.net.Uri
-import android.provider.DocumentsContract
import androidx.room.withTransaction
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.core.util.generateId
-import com.anthonyla.paperize.core.util.isDocumentMissing
import com.anthonyla.paperize.data.database.PaperizeDatabase
-import com.anthonyla.paperize.data.database.dao.AlbumDao
-import com.anthonyla.paperize.data.database.dao.FolderDao
-import com.anthonyla.paperize.data.database.dao.WallpaperDao
-import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.mapper.toDomainModel
-import com.anthonyla.paperize.data.mapper.toDomainModelsFromRelations
-import com.anthonyla.paperize.data.mapper.toDomainModelsFromSummaries
-import com.anthonyla.paperize.data.mapper.toEntities
import com.anthonyla.paperize.data.mapper.toEntity
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.AlbumRepository
-import dagger.hilt.android.qualifiers.ApplicationContext
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.CancellationException
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.map
+import com.anthonyla.paperize.domain.source.DocumentSource
import javax.inject.Inject
import javax.inject.Singleton
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
@Singleton
class AlbumRepositoryImpl @Inject constructor(
- @param:ApplicationContext private val context: Context,
- private val database: PaperizeDatabase,
- private val albumDao: AlbumDao,
- private val wallpaperDao: WallpaperDao,
- private val folderDao: FolderDao,
- private val wallpaperRepository: dagger.Lazy
+ private val documents: DocumentSource,
+ private val database: PaperizeDatabase
) : AlbumRepository {
+ private val albumDao = database.albumDao()
+ private val wallpaperDao = database.wallpaperDao()
+ private val folderDao = database.folderDao()
companion object {
private const val WALLPAPER_BATCH_SIZE = 500
}
override fun getAlbumSummaries(): Flow> =
- albumDao.getAlbumSummaries().map { it.toDomainModelsFromSummaries() }
-
- override fun getAllAlbums(): Flow> =
- albumDao.getAllAlbumsWithDetails().map { it.toDomainModelsFromRelations() }
+ albumDao.getAlbumSummaries().map { it.map { summary -> summary.toDomainModel() } }
override fun getAlbumById(albumId: String): Flow =
albumDao.getAlbumWithDetails(albumId).map { it?.toDomainModel() }
@@ -61,92 +42,25 @@ class AlbumRepositoryImpl @Inject constructor(
override fun getFolderById(folderId: String): Flow =
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
- override suspend fun createAlbum(name: String, coverUri: String?): Result {
- return try {
- val album = Album(
- id = generateId(),
- name = name,
- coverUri = coverUri,
- createdAt = System.currentTimeMillis(),
- modifiedAt = System.currentTimeMillis()
- )
- albumDao.insertAlbum(album.toEntity())
- Result.Success(album)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
+ override suspend fun createAlbum(name: String, coverUri: String?): Result = Result.runCatching {
+ val now = System.currentTimeMillis()
+ val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now)
+ albumDao.insertAlbum(album.toEntity())
+ album
}
- override suspend fun updateAlbum(album: Album): Result {
- return try {
- albumDao.updateAlbum(album.toEntity())
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun deleteAlbum(albumId: String): Result {
- return try {
- database.withTransaction {
- albumDao.deleteAlbumById(albumId)
- wallpaperRepository.get().clearQueuesForAlbum(albumId)
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun updateAlbumName(albumId: String, name: String): Result {
- return try {
- albumDao.updateAlbumName(albumId, name, System.currentTimeMillis())
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result {
- return try {
- albumDao.updateAlbumCover(albumId, coverUri, System.currentTimeMillis())
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
+ override suspend fun deleteAlbum(albumId: String): Result = Result.runCatching {
+ albumDao.deleteAlbumById(albumId)
}
override suspend fun addWallpapersToAlbum(
albumId: String,
wallpapers: List,
onProgress: (saved: Int, total: Int) -> Unit
- ): Result {
- return try {
- database.withTransaction {
- insertWallpapersChunked(wallpapers, onProgress)
- wallpapers.mapNotNull { it.folderId }.toSet().forEach { folderId ->
- folderDao.updateFolderCover(folderId, wallpaperDao.getFolderCoverUri(folderId))
- }
- database.wallpaperQueueDao().clearAllQueues(albumId)
- albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
-
- updateAlbumCoverIfNeeded(albumId)
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
+ ): Result = Result.runCatching {
+ database.withTransaction {
+ checkNotNull(albumDao.getAlbumById(albumId))
+ insertNewWallpapers(albumId, wallpapers, onProgress)
}
}
@@ -154,29 +68,48 @@ class AlbumRepositoryImpl @Inject constructor(
albumId: String,
folder: Folder,
onProgress: (saved: Int, total: Int) -> Unit
- ): Result {
- return try {
- database.withTransaction {
- folderDao.insertFolder(folder.toEntity())
- insertWallpapersChunked(folder.wallpapers, onProgress)
- database.wallpaperQueueDao().clearAllQueues(albumId)
- albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
-
- updateAlbumCoverIfNeeded(albumId)
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
+ ): Result = Result.runCatching {
+ database.withTransaction {
+ checkNotNull(albumDao.getAlbumById(albumId))
+ if (folderDao.containsUri(albumId, folder.uri)) return@withTransaction false
+ folderDao.insertFolder(folder.toEntity().copy(
+ albumId = albumId, displayOrder = folderDao.getMaxOrder(albumId) + 1, coverUri = null
+ ))
+ insertNewWallpapers(albumId, folder.wallpapers.map { it.copy(folderId = folder.id) }, onProgress)
+ albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
+ true
}
}
- /**
- * Insert [wallpapers] in chunks, mapping each chunk to entities only as it is written so the
- * full entity list is never materialized at once, and reporting progress after each chunk.
- * Must be called inside a transaction so the overall insert stays atomic.
- */
+ private suspend fun insertNewWallpapers(
+ albumId: String,
+ wallpapers: List,
+ onProgress: (Int, Int) -> Unit
+ ): Int {
+ var nextOrder = wallpaperDao.getMaxOrder(albumId) + 1
+ val additions = wallpapers.groupBy { it.folderId }.flatMap { (folderId, images) ->
+ // A folder can be removed while its provider scan is in flight.
+ if (folderId != null && folderDao.getFolderById(folderId)?.albumId != albumId) {
+ emptyList()
+ } else {
+ val existing = wallpaperDao.getUrisInCollection(albumId, folderId).toHashSet()
+ images.filter { existing.add(it.uri) }.map {
+ it.copy(albumId = albumId, displayOrder = nextOrder++)
+ }
+ }
+ }
+ if (additions.isEmpty()) return 0
+ insertWallpapersChunked(additions, onProgress)
+ additions.mapNotNull { it.folderId }.toSet().forEach { folderId ->
+ folderDao.updateFolderCover(folderId, wallpaperDao.getFolderCoverUri(folderId))
+ }
+ database.wallpaperQueueDao().clearAllQueues(albumId)
+ albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
+ updateAlbumCoverIfNeeded(albumId)
+ return additions.size
+ }
+
+ /** Report chunk progress within the caller's transaction; cancellation rolls back every chunk. */
private suspend fun insertWallpapersChunked(
wallpapers: List,
onProgress: (saved: Int, total: Int) -> Unit
@@ -184,139 +117,83 @@ class AlbumRepositoryImpl @Inject constructor(
val total = wallpapers.size
var saved = 0
wallpapers.chunked(WALLPAPER_BATCH_SIZE).forEach { chunk ->
- wallpaperDao.insertWallpapers(chunk.toEntities())
+ wallpaperDao.insertWallpapers(chunk.map { it.toEntity() })
saved += chunk.size
onProgress(saved, total)
}
}
- override suspend fun updateFolder(folder: Folder): Result {
- return try {
- folderDao.updateFolder(folder.toEntity())
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
+ override suspend fun reorderAlbum(
+ albumId: String,
+ folders: List,
+ wallpapers: List
+ ): Result = Result.runCatching {
+ database.withTransaction {
+ folders.forEachIndexed { index, folder ->
+ folderDao.updateFolderOrder(albumId, folder.id, index)
+ }
+ // Rotation follows direct images, then each folder in the saved order.
+ (wallpapers.asSequence() + folders.asSequence().flatMap { it.wallpapers })
+ .forEachIndexed { index, wallpaper ->
+ wallpaperDao.updateAlbumWallpaperOrder(albumId, wallpaper.id, index)
+ }
+ folderDao.refreshFolderCovers(albumId)
+ updateAlbumCoverIfNeeded(albumId)
+ albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
+ database.wallpaperQueueDao().clearAllQueues(albumId)
}
}
override suspend fun removeWallpapersFromAlbum(
albumId: String,
wallpaperIds: List
- ): Result {
- return try {
- if (wallpaperIds.isEmpty()) {
- return Result.Success(Unit)
+ ): Result = Result.runCatching {
+ if (wallpaperIds.isEmpty()) return@runCatching
+ database.withTransaction {
+ wallpaperIds.chunked(WALLPAPER_BATCH_SIZE).forEach {
+ wallpaperDao.deleteAlbumWallpapers(albumId, it)
}
-
- database.withTransaction {
- val album = albumDao.getAlbumById(albumId)
- val currentCoverUri = album?.coverUri
-
- wallpaperIds.chunked(WALLPAPER_BATCH_SIZE).forEach {
- wallpaperDao.deleteWallpapersByIds(it)
- }
- albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
-
- if (currentCoverUri != null && !wallpaperDao.containsUri(albumId, currentCoverUri)) {
- updateAlbumCoverIfNeeded(albumId)
- }
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun removeFolderFromAlbum(albumId: String, folderId: String): Result {
- return try {
- database.withTransaction {
- folderDao.deleteFolderById(folderId)
- albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
-
- // Always refresh cover after folder deletion (folder wallpapers might be cover)
- updateAlbumCoverIfNeeded(albumId)
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun getAlbumCount(): Int = albumDao.getAlbumCount()
-
- override suspend fun deleteAllAlbums(): Result {
- return try {
- database.withTransaction {
- albumDao.deleteAllAlbums()
- wallpaperRepository.get().clearAllQueues()
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun validateAndRemoveInvalidFolders(albumId: String): Result {
- return try {
- val album = albumDao.getAlbumWithDetails(albumId).first() ?: return Result.Success(0)
- val folders = album.folders.map { it.toDomainModel() }
-
- val invalidFolderIds = withContext(Dispatchers.IO) {
- folders.filter { folder ->
- val treeUri = Uri.parse(folder.uri)
- val documentUri = DocumentsContract.buildDocumentUriUsingTree(
- treeUri, DocumentsContract.getTreeDocumentId(treeUri)
- )
- documentUri.isDocumentMissing(context.contentResolver)
- }.map { it.id }
- }
-
- if (invalidFolderIds.isNotEmpty()) {
- database.withTransaction {
- invalidFolderIds.forEach { folderId ->
- folderDao.deleteFolderById(folderId)
- }
- updateAlbumCoverIfNeeded(albumId)
- }
- }
-
- Result.Success(invalidFolderIds.size)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun refreshAlbumCover(albumId: String): Result {
- return try {
- database.withTransaction {
- updateAlbumCoverIfNeeded(albumId)
- }
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun refreshFolderCovers(albumId: String): Result {
- return try {
+ albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
folderDao.refreshFolderCovers(albumId)
- Result.Success(Unit)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
+ updateAlbumCoverIfNeeded(albumId)
+ }
+ }
+
+ override suspend fun removeFolderFromAlbum(albumId: String, folderId: String): Result = Result.runCatching {
+ database.withTransaction {
+ folderDao.deleteAlbumFolder(albumId, folderId)
+ albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
+ updateAlbumCoverIfNeeded(albumId)
+ }
+ }
+
+ override suspend fun deleteAllAlbums(): Result = Result.runCatching {
+ albumDao.deleteAllAlbums()
+ }
+
+ override suspend fun pruneMissingEntries(albumId: String): Result = Result.runCatching {
+ val missingFolders = folderDao.getFoldersByAlbum(albumId)
+ .filter { documents.isMissing(it.uri, isTree = true) }.map { it.id }.toSet()
+ val missingImages = mutableListOf()
+ var afterId: String? = null
+ while (true) {
+ val batch = wallpaperDao.getWallpapersByAlbumPage(albumId, WALLPAPER_BATCH_SIZE, afterId)
+ if (batch.isEmpty()) break
+ batch.filter { it.folderId !in missingFolders && documents.isMissing(it.uri) }
+ .mapTo(missingImages) { it.id }
+ afterId = batch.last().id
+ }
+ database.withTransaction {
+ var removed = missingFolders.sumOf { folderDao.deleteAlbumFolder(albumId, it) }
+ missingImages.chunked(WALLPAPER_BATCH_SIZE).forEach {
+ removed += wallpaperDao.deleteAlbumWallpapers(albumId, it)
+ }
+ if (removed > 0) {
+ folderDao.refreshFolderCovers(albumId)
+ updateAlbumCoverIfNeeded(albumId)
+ albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
+ }
+ removed
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt
index e6bc97f..ee81b93 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.data.repository
+import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.data.datastore.PreferencesManager
import com.anthonyla.paperize.domain.model.AppSettings
@@ -9,9 +10,6 @@ import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
-/**
- * Implementation of SettingsRepository
- */
@Singleton
class SettingsRepositoryImpl @Inject constructor(
private val preferencesManager: PreferencesManager
@@ -23,9 +21,6 @@ class SettingsRepositoryImpl @Inject constructor(
override fun getAppSettingsFlow(): Flow =
preferencesManager.getAppSettingsFlow()
- override suspend fun updateAppSettings(settings: AppSettings) =
- preferencesManager.updateAppSettings(settings)
-
override suspend fun getWallpaperMode(): WallpaperMode =
preferencesManager.getWallpaperMode()
@@ -44,6 +39,9 @@ class SettingsRepositoryImpl @Inject constructor(
override suspend fun updateScheduleSettings(settings: ScheduleSettings) =
preferencesManager.updateScheduleSettings(settings)
+ override suspend fun updateScheduleSettings(transform: (ScheduleSettings) -> ScheduleSettings): ScheduleSettings =
+ preferencesManager.updateScheduleSettings(transform)
+
override suspend fun clearAllSettings() =
preferencesManager.clear()
@@ -62,7 +60,8 @@ class SettingsRepositoryImpl @Inject constructor(
override suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean =
preferencesManager.clearAlbumSelectionsIfMatches(albumId)
- // ============ Atomic AppSettings Operations ============
+ override suspend fun clearEmptyAlbumSelection(albumId: String, screen: ScreenType) =
+ preferencesManager.clearEmptyAlbumSelection(albumId, screen)
override suspend fun updateDarkMode(enabled: Boolean) =
preferencesManager.updateDarkMode(enabled)
@@ -76,8 +75,6 @@ class SettingsRepositoryImpl @Inject constructor(
override suspend fun updateFirstLaunch(isFirstLaunch: Boolean) =
preferencesManager.updateFirstLaunch(isFirstLaunch)
- // ============ Atomic ScheduleSettings Operations ============
-
override suspend fun updateEnableChanger(enabled: Boolean) =
preferencesManager.updateEnableChanger(enabled)
}
diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt
index cf8861d..2f17e3e 100644
--- a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt
+++ b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt
@@ -1,158 +1,31 @@
package com.anthonyla.paperize.data.repository
-import android.content.ContentResolver
-import android.content.Context
-import android.net.Uri
-import androidx.core.net.toUri
+import androidx.room.withTransaction
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.core.ScreenType
-import com.anthonyla.paperize.core.WallpaperSourceType
-import com.anthonyla.paperize.core.util.generateId
-import com.anthonyla.paperize.core.util.isDocumentMissing
-import com.anthonyla.paperize.core.util.scanFolderImages
-import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
-import com.anthonyla.paperize.data.database.dao.WallpaperDao
-import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
+import com.anthonyla.paperize.core.util.QueueBuilder
+import com.anthonyla.paperize.data.database.PaperizeDatabase
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
import com.anthonyla.paperize.data.mapper.toDomainModel
-import com.anthonyla.paperize.data.mapper.toDomainModels
-import com.anthonyla.paperize.data.mapper.toEntity
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.WallpaperRepository
-import dagger.hilt.android.qualifiers.ApplicationContext
-import kotlinx.coroutines.flow.Flow
-import kotlinx.coroutines.CancellationException
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import kotlinx.coroutines.flow.map
-import kotlinx.coroutines.sync.Mutex
-import kotlinx.coroutines.sync.withLock
import javax.inject.Inject
import javax.inject.Singleton
-import java.util.concurrent.ConcurrentHashMap
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
-/**
- * Implementation of WallpaperRepository
- */
@Singleton
class WallpaperRepositoryImpl @Inject constructor(
- @param:ApplicationContext private val context: Context,
- private val wallpaperDao: WallpaperDao,
- private val wallpaperQueueDao: WallpaperQueueDao,
- private val wallpaperCurrentDao: WallpaperCurrentDao
+ private val database: PaperizeDatabase
) : WallpaperRepository {
- private val contentResolver: ContentResolver = context.contentResolver
-
- /**
- * Mutexes to synchronize queue rebuild operations per (albumId, screenType)
- * Prevents duplicate rebuilds when multiple threads detect empty queue simultaneously
- */
- private val queueRebuildMutexes = ConcurrentHashMap()
-
- override fun getWallpapersByAlbum(albumId: String): Flow> =
- wallpaperDao.getWallpapersByAlbum(albumId).map { it.toDomainModels() }
-
- override fun getDirectWallpapersByAlbum(albumId: String): Flow> =
- wallpaperDao.getDirectWallpapersByAlbum(albumId).map { it.toDomainModels() }
-
- override fun getWallpapersByFolder(folderId: String): Flow> =
- wallpaperDao.getWallpapersByFolder(folderId).map { it.toDomainModels() }
+ private val wallpaperDao = database.wallpaperDao()
+ private val wallpaperQueueDao = database.wallpaperQueueDao()
+ private val wallpaperCurrentDao = database.wallpaperCurrentDao()
override suspend fun getWallpaperById(wallpaperId: String): Wallpaper? =
wallpaperDao.getWallpaperById(wallpaperId)?.toDomainModel()
- override suspend fun addWallpaper(wallpaper: Wallpaper): Result {
- return try {
- wallpaperDao.insertWallpaper(wallpaper.toEntity())
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun updateWallpaper(wallpaper: Wallpaper): Result {
- return try {
- wallpaperDao.updateWallpaper(wallpaper.toEntity())
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun deleteWallpaper(wallpaperId: String): Result {
- return try {
- wallpaperDao.deleteWallpaperById(wallpaperId)
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun deleteWallpapers(wallpaperIds: List): Result {
- return try {
- if (wallpaperIds.isEmpty()) {
- return Result.Success(Unit)
- }
- wallpaperDao.deleteWallpapersByIds(wallpaperIds)
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun deleteWallpapersByFolderId(folderId: String): Result {
- return try {
- wallpaperDao.deleteWallpapersByFolder(folderId)
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun updateWallpaperOrder(wallpaperId: String, order: Int): Result {
- return try {
- wallpaperDao.updateWallpaperOrder(wallpaperId, order)
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
- override suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result {
- return try {
- var totalRemoved = 0
- val batchSize = 100 // Process in smaller batches to avoid memory spikes
- var offset = 0
-
- while (true) {
- val wallpapers = wallpaperDao.getWallpapersByAlbumPaged(albumId, batchSize, offset)
- if (wallpapers.isEmpty()) break
-
- val missingIds = withContext(Dispatchers.IO) {
- wallpapers.filter { it.uri.toUri().isDocumentMissing(contentResolver) }
- .map { it.id }
- }
-
- if (missingIds.isNotEmpty()) {
- wallpaperDao.deleteWallpapersByIds(missingIds)
- totalRemoved += missingIds.size
- // Advance offset only by the number of valid items in this batch,
- // so valid items already checked are not re-fetched next iteration
- offset += wallpapers.size - missingIds.size
- } else {
- offset += batchSize
- }
- }
-
- Result.Success(totalRemoved)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
override suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): Wallpaper? =
wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType)?.toDomainModel()
@@ -175,101 +48,38 @@ class WallpaperRepositoryImpl @Inject constructor(
wallpaperQueueDao.restoreQueueItem(albumId, screenType, wallpaperId)
}
- override suspend fun buildWallpaperQueue(
+ override suspend fun ensureWallpaperQueue(
albumId: String,
screenType: ScreenType,
shuffle: Boolean
- ): Result {
- // In shuffle mode, use album-level mutex to ensure synchronized shuffle order
- // In sequential mode, use per-screen mutex for independent rebuilds
- val mutexKey = if (shuffle) albumId else "$albumId:$screenType"
- val mutex = queueRebuildMutexes.getOrPut(mutexKey) { Mutex() }
-
- return mutex.withLock {
- try {
- // Load only IDs (+ order for sequential mode) instead of full WallpaperEntity
- // objects, to avoid deserializing every field for every wallpaper in the album.
- val otherScreenType: ScreenType? = if (shuffle) when (screenType) {
- ScreenType.HOME -> ScreenType.LOCK
- ScreenType.LOCK -> ScreenType.HOME
- else -> null
- } else null
-
- val wallpaperIds = if (shuffle) {
- val ids = wallpaperDao.getWallpaperIdsByAlbum(albumId)
-
- // In shuffle mode, sync with the other screen's queue if it exists
- val otherScreenQueueIds = otherScreenType?.let {
- try {
- wallpaperQueueDao.getQueueItems(albumId, it)
- .map { item -> item.wallpaperId }
- } catch (_: Exception) { null }
- }
-
- if (otherScreenQueueIds != null && otherScreenQueueIds.isNotEmpty()) {
- com.anthonyla.paperize.core.util.QueueBuilder.mergeWithExistingQueue(otherScreenQueueIds, ids)
- } else {
- com.anthonyla.paperize.core.util.QueueBuilder.buildShuffledQueue(ids)
- }
- } else {
- val idsWithOrder = wallpaperDao.getWallpaperIdsAndOrderByAlbum(albumId)
- com.anthonyla.paperize.core.util.QueueBuilder.buildSequentialQueue(
- idsWithOrder.map { it.id to it.displayOrder }
- )
- }
-
- wallpaperQueueDao.rebuildQueue(albumId, screenType, wallpaperIds)
-
- // In shuffle mode, pre-populate the other screen's queue with the same order
- // if it doesn't yet exist. This ensures both screens start from the same
- // shuffle sequence, preventing drift when switching to separate schedules.
- if (shuffle && otherScreenType != null) {
- try {
- val otherQueueIsEmpty = wallpaperQueueDao
- .getQueueItems(albumId, otherScreenType).isEmpty()
- if (otherQueueIsEmpty) {
- wallpaperQueueDao.rebuildQueue(albumId, otherScreenType, wallpaperIds)
- }
- } catch (_: Exception) {
- // Best-effort: if pre-population fails the other screen will build its
- // own queue on demand via mergeWithExistingQueue
- }
- }
-
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
+ ): Result = Result.runCatching {
+ database.withTransaction {
+ // Recheck inside the transaction: another caller may already have filled it.
+ if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return@withTransaction
+ val otherScreen = if (shuffle) when (screenType) {
+ ScreenType.HOME -> ScreenType.LOCK
+ ScreenType.LOCK -> ScreenType.HOME
+ else -> null
+ } else null
+ val otherQueue = otherScreen?.let { wallpaperQueueDao.getQueueItems(albumId, it) }.orEmpty()
+ val ids = if (shuffle) {
+ val available = wallpaperDao.getWallpaperIdsByAlbum(albumId)
+ if (otherQueue.isEmpty()) available.shuffled()
+ else QueueBuilder.mergeWithExistingQueue(otherQueue.map { it.wallpaperId }, available)
+ } else {
+ wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId)
+ }
+ wallpaperQueueDao.rebuildQueue(albumId, screenType, ids)
+ if (otherScreen != null && otherQueue.isEmpty()) {
+ wallpaperQueueDao.rebuildQueue(albumId, otherScreen, ids)
}
}
}
- override suspend fun clearAllQueues(): Result {
- return try {
- wallpaperQueueDao.deleteAllQueueItems()
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
+ override suspend fun clearAllQueues(): Result = Result.runCatching {
+ wallpaperQueueDao.deleteAllQueueItems()
}
- override suspend fun clearQueuesForAlbum(albumId: String): Result {
- return try {
- wallpaperQueueDao.clearAllQueues(albumId)
-
- // Prune mutexes for this album to prevent memory leak
- // Keys are either albumId (shuffled) or $albumId:$screenType (sequential)
- // Use exact match or prefix with colon to avoid false positives (e.g., album1 vs album10)
- queueRebuildMutexes.keys.filter { it == albumId || it.startsWith("$albumId:") }.forEach {
- queueRebuildMutexes.remove(it)
- }
-
- Result.Success(Unit)
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
-
override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel()
@@ -282,25 +92,4 @@ class WallpaperRepositoryImpl @Inject constructor(
)
}
- override suspend fun scanFolderForWallpapers(folderUri: Uri): Result> {
- return try {
- val wallpapers = withContext(Dispatchers.IO) { folderUri.scanFolderImages(context) }.map { image ->
- Wallpaper(
- id = generateId(),
- albumId = "",
- folderId = null,
- uri = image.uri.toString(),
- fileName = image.name,
- dateModified = image.lastModified,
- sourceType = WallpaperSourceType.FOLDER
- )
- }
- Result.Success(wallpapers)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
- }
-
}
diff --git a/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt b/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt
new file mode 100644
index 0000000..473326e
--- /dev/null
+++ b/app/src/main/java/com/anthonyla/paperize/data/source/AndroidDocumentSource.kt
@@ -0,0 +1,45 @@
+package com.anthonyla.paperize.data.source
+
+import android.content.Context
+import android.content.Intent
+import android.provider.DocumentsContract
+import androidx.core.net.toUri
+import androidx.documentfile.provider.DocumentFile
+import com.anthonyla.paperize.core.util.isDocumentMissing
+import com.anthonyla.paperize.core.util.scanFolderImages
+import com.anthonyla.paperize.domain.source.DocumentSource
+import com.anthonyla.paperize.domain.source.SourceFolder
+import com.anthonyla.paperize.domain.source.SourceImage
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import javax.inject.Inject
+
+class AndroidDocumentSource @Inject constructor(
+ @param:ApplicationContext private val context: Context
+) : DocumentSource {
+ override suspend fun retainReadPermission(uri: String): Unit = withContext(Dispatchers.IO) {
+ context.contentResolver.takePersistableUriPermission(uri.toUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+
+ override suspend fun readImage(uri: String): SourceImage = withContext(Dispatchers.IO) {
+ val document = DocumentFile.fromSingleUri(context, uri.toUri())
+ SourceImage(uri, document?.name ?: uri.substringAfterLast('/'), document?.lastModified() ?: 0L)
+ }
+
+ override suspend fun readFolder(uri: String, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
+ val tree = uri.toUri()
+ val images = tree.scanFolderImages(context, onProgress).map {
+ SourceImage(it.uri.toString(), it.name, it.lastModified)
+ }
+ SourceFolder(DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'), images)
+ }
+
+ override suspend fun isMissing(uri: String, isTree: Boolean): Boolean = withContext(Dispatchers.IO) {
+ val source = uri.toUri()
+ val document = if (isTree) {
+ DocumentsContract.buildDocumentUriUsingTree(source, DocumentsContract.getTreeDocumentId(source))
+ } else source
+ document.isDocumentMissing(context.contentResolver)
+ }
+}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt
index da29f0a..242c517 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/Album.kt
@@ -1,10 +1,5 @@
package com.anthonyla.paperize.domain.model
-/**
- * Domain model for Album
- *
- * Pure Kotlin data class without Room annotations
- */
data class Album(
val id: String,
val name: String,
@@ -14,30 +9,6 @@ data class Album(
val createdAt: Long = System.currentTimeMillis(),
val modifiedAt: Long = System.currentTimeMillis()
) {
- /**
- * Get total wallpaper count (direct + in folders)
- */
- val totalWallpaperCount: Int
- get() = wallpapers.size + folders.sumOf { it.wallpapers.size }
-
- /**
- * Get all wallpapers (direct + from folders)
- */
- val allWallpapers: List
- get() = wallpapers + folders.flatMap { it.wallpapers }
-
- /**
- * Get all wallpapers sorted by display order
- */
- val sortedWallpapers: List
- get() = allWallpapers.sortedBy { it.displayOrder }
-
- /**
- * Check if album is empty
- */
- val isEmpty: Boolean
- get() = totalWallpaperCount == 0
-
companion object {
fun empty(id: String = "", name: String = "") = Album(
id = id,
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/AlbumSummary.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/AlbumSummary.kt
index 872a1c8..41f37ba 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/AlbumSummary.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/AlbumSummary.kt
@@ -14,12 +14,6 @@ data class AlbumSummary(
val createdAt: Long,
val modifiedAt: Long
) {
- /**
- * Check if album is empty without a full object load
- */
- val isEmpty: Boolean
- get() = wallpaperCount == 0
-
companion object {
fun empty(id: String = "", name: String = "") = AlbumSummary(
id = id,
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt
index 6288f49..f61c412 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt
@@ -1,15 +1,9 @@
package com.anthonyla.paperize.domain.model
-/**
- * Domain model for App Settings (theme, preferences, etc.)
- */
data class AppSettings(
val darkMode: Boolean? = null, // null = system default, true = dark, false = light
val dynamicTheming: Boolean = false,
val animate: Boolean = true,
val firstLaunch: Boolean = true
) {
- companion object {
- fun default() = AppSettings()
- }
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/Folder.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/Folder.kt
index c06387b..985edf8 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/Folder.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/Folder.kt
@@ -2,11 +2,6 @@ package com.anthonyla.paperize.domain.model
import android.net.Uri
-/**
- * Domain model for Folder
- *
- * Pure Kotlin data class without Room annotations
- */
data class Folder(
val id: String,
val albumId: String,
@@ -18,36 +13,11 @@ data class Folder(
val wallpapers: List = emptyList(),
val addedAt: Long = System.currentTimeMillis()
) {
- /**
- * Get URL-decoded name for display (last path segment only)
- */
val displayName: String
- get() = try {
- val decoded = Uri.decode(name)
- // Extract just the folder name (last segment after / or :)
+ get() = Uri.decode(name).let { decoded ->
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
- } catch (e: Exception) {
- name
}
- /**
- * Get wallpaper count
- */
- val wallpaperCount: Int
- get() = wallpapers.size
-
- /**
- * Check if folder is empty
- */
- val isEmpty: Boolean
- get() = wallpapers.isEmpty()
-
- /**
- * Get sorted wallpapers
- */
- val sortedWallpapers: List
- get() = wallpapers.sortedBy { it.displayOrder }
-
companion object {
fun empty(id: String = "", albumId: String = "") = Folder(
id = id,
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt
index 402475d..144c71b 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt
@@ -1,11 +1,10 @@
package com.anthonyla.paperize.domain.model
+import com.anthonyla.paperize.core.ScreenType
+import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.constants.Constants
-/**
- * Domain model for Wallpaper Schedule Settings
- */
data class ScheduleSettings(
val enableChanger: Boolean = false,
val separateSchedules: Boolean = false,
@@ -20,16 +19,39 @@ data class ScheduleSettings(
val homeScalingType: ScalingType = ScalingType.FILL,
val lockScalingType: ScalingType = ScalingType.FILL,
val homeScrollingEnabled: Boolean = false,
- val homeEffects: WallpaperEffects = WallpaperEffects.none(),
- val lockEffects: WallpaperEffects = WallpaperEffects.none(),
+ val homeEffects: WallpaperEffects = WallpaperEffects(),
+ val lockEffects: WallpaperEffects = WallpaperEffects(),
val liveAlbumId: String? = null,
val liveScalingType: ScalingType = ScalingType.FILL,
- val liveEffects: WallpaperEffects = WallpaperEffects.none(),
+ val liveEffects: WallpaperEffects = WallpaperEffects(),
val adaptiveBrightness: Boolean = false
) {
- /**
- * Validate interval values
- */
+ val effectiveLockIntervalMinutes: Int
+ get() = if (homeEnabled && lockEnabled && separateSchedules) lockIntervalMinutes else homeIntervalMinutes
+
+ fun hasRequiredAlbums(mode: WallpaperMode): Boolean = when (mode) {
+ WallpaperMode.LIVE -> liveAlbumId != null
+ WallpaperMode.STATIC -> (homeEnabled || lockEnabled) &&
+ (!homeEnabled || homeAlbumId != null) && (!lockEnabled || lockAlbumId != null)
+ }
+
+ fun activeScreens(mode: WallpaperMode): Set {
+ if (mode == WallpaperMode.LIVE) return if (liveAlbumId != null) setOf(ScreenType.LIVE) else emptySet()
+ val home = homeEnabled && homeAlbumId != null
+ val lock = lockEnabled && lockAlbumId != null
+ if (home && lock && homeAlbumId == lockAlbumId && !separateSchedules) return setOf(ScreenType.BOTH)
+ return buildSet {
+ if (home) add(ScreenType.HOME)
+ if (lock) add(ScreenType.LOCK)
+ }
+ }
+
+ fun intervalMinutes(screen: ScreenType): Int = when (screen) {
+ ScreenType.HOME, ScreenType.BOTH -> homeIntervalMinutes
+ ScreenType.LOCK -> effectiveLockIntervalMinutes
+ ScreenType.LIVE -> liveIntervalMinutes
+ }
+
fun validate(): ScheduleSettings = copy(
homeIntervalMinutes = homeIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
lockIntervalMinutes = lockIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
@@ -39,19 +61,12 @@ data class ScheduleSettings(
liveEffects = liveEffects.validate()
)
- /**
- * Check if scheduling-related settings changed (not just display settings)
- *
- * Returns true if any of these changed:
- * - Screen enable/disable
- * - Interval timing
- * - Separate schedules toggle
- * - Shuffle (handled separately with queue clearing)
- *
- * Display-only settings (scaling, effects, adaptive brightness) don't affect scheduling
- */
fun hasSchedulingChanges(other: ScheduleSettings): Boolean {
- return homeEnabled != other.homeEnabled ||
+ return enableChanger != other.enableChanger ||
+ homeAlbumId != other.homeAlbumId ||
+ lockAlbumId != other.lockAlbumId ||
+ liveAlbumId != other.liveAlbumId ||
+ homeEnabled != other.homeEnabled ||
lockEnabled != other.lockEnabled ||
homeIntervalMinutes != other.homeIntervalMinutes ||
lockIntervalMinutes != other.lockIntervalMinutes ||
@@ -59,12 +74,7 @@ data class ScheduleSettings(
liveIntervalMinutes != other.liveIntervalMinutes
}
- /**
- * Check if display settings changed (scaling, effects, adaptive brightness)
- *
- * When these change, we should reapply the current wallpaper immediately
- * to show the user the effect, but we don't need to reschedule WorkManager
- */
+ /** Display changes reapply the current wallpaper without rescheduling periodic work. */
fun hasDisplayChanges(other: ScheduleSettings): Boolean {
return homeScalingType != other.homeScalingType ||
lockScalingType != other.lockScalingType ||
@@ -76,9 +86,6 @@ data class ScheduleSettings(
adaptiveBrightness != other.adaptiveBrightness
}
- companion object {
- fun default() = ScheduleSettings()
- }
}
/**
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt
index 0d5aadc..c9bcde2 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt
@@ -4,11 +4,6 @@ import android.net.Uri
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.core.WallpaperSourceType
-/**
- * Domain model for Wallpaper
- *
- * Pure Kotlin data class without Room annotations
- */
data class Wallpaper(
val id: String,
val albumId: String,
@@ -21,36 +16,11 @@ data class Wallpaper(
val addedAt: Long = System.currentTimeMillis(),
val mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE
) {
- /**
- * Get URL-decoded file name for display (filename only, no path)
- */
val displayFileName: String
- get() = try {
- val decoded = Uri.decode(fileName)
- // Extract just the filename (last segment after / or :)
+ get() = Uri.decode(fileName).let { decoded ->
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
- } catch (e: Exception) {
- fileName
}
- /**
- * Check if wallpaper is from a folder
- */
- val isFromFolder: Boolean
- get() = folderId != null && sourceType == WallpaperSourceType.FOLDER
-
- /**
- * Get file extension
- */
- val extension: String
- get() = fileName.substringAfterLast('.', "").lowercase()
-
- /**
- * Check if file is a valid image
- */
- val isValidImage: Boolean
- get() = extension in setOf("jpg", "jpeg", "png", "webp", "avif")
-
companion object {
fun empty(id: String = "", albumId: String = "") = Wallpaper(
id = id,
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt
index 60e0430..d8482be 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt
@@ -2,14 +2,7 @@ package com.anthonyla.paperize.domain.model
import com.anthonyla.paperize.core.constants.Constants
-/**
- * Domain model for Wallpaper Effects
- *
- * Represents the visual effects applied to wallpapers
- * Includes both visual effects (blur, darken, etc.) and interactive effects (double-tap, parallax)
- */
data class WallpaperEffects(
- // Visual effects (available in both static and live modes)
val enableBlur: Boolean = false,
val blurPercentage: Int = Constants.DEFAULT_BLUR_PERCENTAGE,
val enableDarken: Boolean = false,
@@ -25,18 +18,6 @@ data class WallpaperEffects(
val enableParallax: Boolean = false,
val parallaxIntensity: Int = Constants.DEFAULT_PARALLAX_INTENSITY
) {
- /**
- * Check if any effects are applied
- */
- val hasEffects: Boolean
- get() = (enableBlur && blurPercentage > 0) ||
- (enableDarken && darkenPercentage > 0) ||
- (enableVignette && vignettePercentage > 0) ||
- (enableGrayscale && grayscalePercentage > 0)
-
- /**
- * Validate effect percentages
- */
fun validate(): WallpaperEffects = copy(
darkenPercentage = darkenPercentage.coerceIn(0, 100),
blurPercentage = blurPercentage.coerceIn(0, 100),
@@ -44,9 +25,4 @@ data class WallpaperEffects(
grayscalePercentage = grayscalePercentage.coerceIn(0, 100),
parallaxIntensity = parallaxIntensity.coerceIn(0, 100)
)
-
- companion object {
- fun default() = WallpaperEffects()
- fun none() = WallpaperEffects()
- }
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt
index 58dd28b..49f4d9d 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/AlbumRepository.kt
@@ -7,125 +7,41 @@ import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.model.Folder
import kotlinx.coroutines.flow.Flow
-/**
- * Repository interface for Album operations
- *
- * Clean interface following repository pattern - implementation in data layer
- */
interface AlbumRepository {
- /**
- * Get all album summaries (lightweight metadata + counts)
- */
fun getAlbumSummaries(): Flow>
- /**
- * Get all albums with their wallpapers and folders
- */
- fun getAllAlbums(): Flow>
-
- /**
- * Get a specific album by ID
- */
fun getAlbumById(albumId: String): Flow
- /**
- * Get a specific album by name
- */
suspend fun getAlbumByName(name: String): Album?
- /**
- * Get a specific folder by ID
- */
fun getFolderById(folderId: String): Flow
- /**
- * Create a new album
- */
suspend fun createAlbum(name: String, coverUri: String? = null): Result
- /**
- * Update album
- */
- suspend fun updateAlbum(album: Album): Result
-
- /**
- * Delete album
- */
suspend fun deleteAlbum(albumId: String): Result
- /**
- * Update album name
- */
- suspend fun updateAlbumName(albumId: String, name: String): Result
-
- /**
- * Update album cover
- */
- suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result
-
- /**
- * Add wallpapers to album.
- *
- * [onProgress] is invoked as rows are written, with the number saved so far and the total,
- * so callers can show import progress.
- */
+ /** Returns the number of new images. Progress counts rows written within the transaction. */
suspend fun addWallpapersToAlbum(
albumId: String,
wallpapers: List,
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
- ): Result
+ ): Result
- /**
- * Add folder to album.
- *
- * [onProgress] is invoked as the folder's wallpapers are written, with the number saved so far
- * and the total, so callers can show import progress.
- */
+ /** Returns false for an existing folder URI. Progress counts images written within the transaction. */
suspend fun addFolderToAlbum(
albumId: String,
folder: Folder,
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
- ): Result
+ ): Result
- /**
- * Update folder
- */
- suspend fun updateFolder(folder: Folder): Result
+ suspend fun reorderAlbum(albumId: String, folders: List, wallpapers: List): Result
- /**
- * Remove multiple wallpapers from album (batch operation)
- * Updates album modified time and refreshes cover art
- */
suspend fun removeWallpapersFromAlbum(albumId: String, wallpaperIds: List): Result
- /**
- * Remove folder from album
- */
suspend fun removeFolderFromAlbum(albumId: String, folderId: String): Result
- /**
- * Get album count
- */
- suspend fun getAlbumCount(): Int
-
- /**
- * Delete all albums
- */
suspend fun deleteAllAlbums(): Result
- /**
- * Validate folder URIs and remove invalid ones
- * Returns number of folders removed
- */
- suspend fun validateAndRemoveInvalidFolders(albumId: String): Result
-
- /**
- * Refresh album cover art based on current wallpapers
- */
- suspend fun refreshAlbumCover(albumId: String): Result
-
- /**
- * Refresh all folder covers in an album based on their current wallpapers
- */
- suspend fun refreshFolderCovers(albumId: String): Result
+ /** Removes confirmed missing entries and updates covers in the same transaction. */
+ suspend fun pruneMissingEntries(albumId: String): Result
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt
index 82ebd34..1496472 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt
@@ -1,113 +1,51 @@
package com.anthonyla.paperize.domain.repository
+import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.model.ScheduleSettings
import kotlinx.coroutines.flow.Flow
-/**
- * Repository interface for Settings operations
- */
interface SettingsRepository {
- /**
- * Get app settings
- */
suspend fun getAppSettings(): AppSettings
- /**
- * Get app settings as Flow
- */
fun getAppSettingsFlow(): Flow
- /**
- * Update app settings
- */
- suspend fun updateAppSettings(settings: AppSettings)
-
- /**
- * Get wallpaper mode (STATIC or LIVE)
- */
suspend fun getWallpaperMode(): WallpaperMode
- /**
- * Get wallpaper mode as Flow
- */
fun getWallpaperModeFlow(): Flow
- /**
- * Update wallpaper mode
- * IMPORTANT: Caller must handle data reset when switching modes
- */
+ /** The caller must reset library and schedule data when switching modes. */
suspend fun updateWallpaperMode(mode: WallpaperMode)
- /**
- * Get schedule settings
- */
suspend fun getScheduleSettings(): ScheduleSettings
- /**
- * Get schedule settings as Flow
- */
fun getScheduleSettingsFlow(): Flow
- /**
- * Update schedule settings
- */
suspend fun updateScheduleSettings(settings: ScheduleSettings)
- /**
- * Clear all settings
- */
+ /** Apply an edit to the latest stored settings in one DataStore transaction. */
+ suspend fun updateScheduleSettings(transform: (ScheduleSettings) -> ScheduleSettings): ScheduleSettings
+
suspend fun clearAllSettings()
- /**
- * Clear schedule settings (reset to defaults)
- * Used when switching wallpaper modes to reset all scheduling configuration
- */
suspend fun clearScheduleSettings()
- /**
- * Set wallpaper mode (wrapper for updateWallpaperMode)
- */
- suspend fun setWallpaperMode(mode: WallpaperMode) = updateWallpaperMode(mode)
-
- /**
- * Atomically update home album ID to prevent race conditions
- * Use this instead of updateScheduleSettings when only changing home album
- */
suspend fun updateHomeAlbumId(albumId: String?)
- /**
- * Atomically update lock album ID to prevent race conditions
- * Use this instead of updateScheduleSettings when only changing lock album
- */
suspend fun updateLockAlbumId(albumId: String?)
- /**
- * Atomically update live album ID to prevent race conditions
- * Use this instead of updateScheduleSettings when only changing live album
- */
suspend fun updateLiveAlbumId(albumId: String?)
- /**
- * Atomically clear album selections if they match the given album ID
- * Used when deleting an album to prevent race conditions
- * Returns true if any selections were cleared
- */
+ /** Clears matching selections atomically; returns whether any selection changed. */
suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean
- // ============ Atomic AppSettings Operations ============
+ suspend fun clearEmptyAlbumSelection(albumId: String, screen: ScreenType)
suspend fun updateDarkMode(enabled: Boolean)
suspend fun updateDynamicTheming(enabled: Boolean)
suspend fun updateAnimate(enabled: Boolean)
suspend fun updateFirstLaunch(isFirstLaunch: Boolean)
- // ============ Atomic ScheduleSettings Operations ============
-
- /**
- * Atomically update enableChanger to prevent race conditions
- * Use this instead of updateScheduleSettings when only toggling changer
- */
suspend fun updateEnableChanger(enabled: Boolean)
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt
index 6e17e2c..0ae2c92 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt
@@ -1,73 +1,13 @@
package com.anthonyla.paperize.domain.repository
-import android.net.Uri
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.domain.model.Wallpaper
import kotlinx.coroutines.flow.Flow
-/**
- * Repository interface for Wallpaper operations
- */
interface WallpaperRepository {
- /**
- * Get wallpapers for an album
- */
- fun getWallpapersByAlbum(albumId: String): Flow>
-
- /**
- * Get direct wallpapers for an album (not from folders)
- */
- fun getDirectWallpapersByAlbum(albumId: String): Flow>
-
- /**
- * Get wallpapers for a folder
- */
- fun getWallpapersByFolder(folderId: String): Flow>
-
- /**
- * Get wallpaper by ID
- */
suspend fun getWallpaperById(wallpaperId: String): Wallpaper?
- /**
- * Add wallpaper
- */
- suspend fun addWallpaper(wallpaper: Wallpaper): Result
-
- /**
- * Update wallpaper
- */
- suspend fun updateWallpaper(wallpaper: Wallpaper): Result
-
- /**
- * Delete wallpaper
- */
- suspend fun deleteWallpaper(wallpaperId: String): Result
-
- /**
- * Delete multiple wallpapers by IDs (batch operation)
- */
- suspend fun deleteWallpapers(wallpaperIds: List): Result
-
- /**
- * Delete all wallpapers in a folder
- */
- suspend fun deleteWallpapersByFolderId(folderId: String): Result
-
- /**
- * Update wallpaper order
- */
- suspend fun updateWallpaperOrder(wallpaperId: String, order: Int): Result
-
- /**
- * Validate wallpaper URIs and remove invalid ones
- */
- suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result
-
- /**
- * Get next wallpaper in queue
- */
suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): Wallpaper?
/**
@@ -76,9 +16,6 @@ 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,
@@ -95,9 +32,9 @@ interface WallpaperRepository {
)
/**
- * Build wallpaper queue for album
+ * Fill an empty wallpaper queue; preserve a queue already filled by another caller
*/
- suspend fun buildWallpaperQueue(
+ suspend fun ensureWallpaperQueue(
albumId: String,
screenType: ScreenType,
shuffle: Boolean = false
@@ -109,33 +46,10 @@ interface WallpaperRepository {
*/
suspend fun clearAllQueues(): Result
- /**
- * Clear all queues for a specific album
- * Used when sort order changes to force rebuild with new order
- */
- suspend fun clearQueuesForAlbum(albumId: String): Result
-
- /**
- * Get the last-applied wallpaper for a given album/screen.
- * Returns null if none has been recorded yet or if it was deleted.
- */
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
- /**
- * Reactive variant of [getCurrentWallpaper] that re-emits whenever the recorded wallpaper
- * for this album/screen changes. Used by the in-app current-wallpaper preview.
- */
fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow
- /**
- * Record the wallpaper that was just applied for a given album/screen.
- * Called by WallpaperChangeService after a successful setBitmap().
- */
suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String)
- /**
- * Scan folder for wallpapers
- */
- suspend fun scanFolderForWallpapers(folderUri: Uri): Result>
-
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt b/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt
new file mode 100644
index 0000000..18ffd83
--- /dev/null
+++ b/app/src/main/java/com/anthonyla/paperize/domain/source/DocumentSource.kt
@@ -0,0 +1,11 @@
+package com.anthonyla.paperize.domain.source
+
+data class SourceImage(val uri: String, val name: String, val modifiedAt: Long)
+data class SourceFolder(val name: String, val images: List)
+
+interface DocumentSource {
+ suspend fun retainReadPermission(uri: String)
+ suspend fun readImage(uri: String): SourceImage
+ suspend fun readFolder(uri: String, onProgress: (Int) -> Unit = {}): SourceFolder
+ suspend fun isMissing(uri: String, isTree: Boolean = false): Boolean
+}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCase.kt
index c9133aa..5477c58 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCase.kt
@@ -1,25 +1,24 @@
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.core.util.WallpaperRenderer
import com.anthonyla.paperize.domain.model.PreparedWallpaper
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.WallpaperRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
+import kotlinx.coroutines.withContext
/**
* Prepares the next wallpaper without marking it as current.
@@ -31,145 +30,38 @@ import javax.inject.Inject
class ChangeWallpaperUseCase @Inject constructor(
@param:ApplicationContext private val context: Context,
private val wallpaperRepository: WallpaperRepository,
- private val settingsRepository: SettingsRepository
+ private val settingsRepository: SettingsRepository,
+ private val renderer: WallpaperRenderer
) {
- suspend operator fun invoke(
- albumId: String,
- screenType: ScreenType
- ): Result {
- return try {
- val settings = settingsRepository.getScheduleSettings()
-
- 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))
- )
+ suspend operator fun invoke(albumId: String, screenType: ScreenType): Result = Result.runCatching {
+ val settings = settingsRepository.getScheduleSettings()
+ repeat(Constants.MAX_WALLPAPER_LOAD_RETRIES) {
+ currentCoroutineContext().ensureActive()
+ val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType) ?: run {
+ wallpaperRepository.ensureWallpaperQueue(albumId, screenType, settings.shuffleEnabled).getOrThrow()
+ wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
+ ?: throw EmptyAlbumException(context.getString(R.string.no_wallpapers_in_album))
+ }
+ try {
+ val bitmap = renderer.render(candidate, screenType, settings)
+ if (bitmap != null) {
+ return@runCatching PreparedWallpaper(bitmap, albumId, screenType, candidate.id, settings.shuffleEnabled)
}
- }
-
- val effects = when (screenType) {
- ScreenType.LIVE -> settings.liveEffects
- ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
- ScreenType.LOCK -> settings.lockEffects
- }
- val scaling = when (screenType) {
- ScreenType.LIVE -> settings.liveScalingType
- ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
- ScreenType.LOCK -> settings.lockScalingType
- }
- val preserveSourceOverflow = usesLauncherManagedScrolling(
- screenType,
- scaling,
- settings.homeScrollingEnabled
- )
- val screenSize = getWallpaperRenderSize(context, screenType, scaling)
-
- 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 > 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
- )
- if (rebuildResult is Result.Error) {
- return Result.Error(
- Exception(context.getString(R.string.error_failed_to_build_queue))
- )
- }
- continue
- }
-
- try {
- 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
- }
-
- var processedBitmap: Bitmap? = null
+ } catch (e: CancellationException) {
+ // Cancelling preparation must not consume the selected queue item.
+ withContext(NonCancellable) {
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 (processedBitmap !== bitmap) bitmap.recycle()
-
- if (settings.adaptiveBrightness) {
- val previousBitmap = processedBitmap
- processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
- if (processedBitmap !== previousBitmap) previousBitmap.recycle()
- }
-
- finalBitmap = processedBitmap
- preparedWallpaperId = candidate.id
- } catch (e: Exception) {
- if (processedBitmap != null && !processedBitmap.isRecycled) {
- processedBitmap.recycle()
- } else if (!bitmap.isRecycled) {
- bitmap.recycle()
- }
- throw e
+ wallpaperRepository.restoreWallpaperToQueueFront(albumId, screenType, candidate.id)
+ } catch (restoreError: Exception) {
+ Log.e(TAG, "Failed to restore cancelled wallpaper", restoreError)
}
- } catch (_: Exception) {
- remainingRetries--
}
+ throw e
+ } catch (_: Exception) {
+ // Unreadable images are skipped for this cycle; refresh owns permanent pruning.
}
-
- val preparedBitmap = finalBitmap
- ?: return Result.Error(
- NoValidWallpaperException(
- context.getString(R.string.error_no_valid_wallpaper_after_retries)
- )
- )
-
- Result.Success(
- PreparedWallpaper(
- bitmap = preparedBitmap,
- albumId = albumId,
- screenType = screenType,
- wallpaperId = checkNotNull(preparedWallpaperId),
- shuffle = settings.shuffleEnabled
- )
- )
- } catch (e: Exception) {
- Result.Error(e)
}
+ throw NoValidWallpaperException(context.getString(R.string.error_no_valid_wallpaper_after_retries))
}
/**
@@ -201,19 +93,15 @@ class ChangeWallpaperUseCase @Inject constructor(
screenType,
wallpaperId
)
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Log.e(TAG, "Applied wallpaper could not be recorded as current", e)
return
}
try {
- if (wallpaperRepository.getNextWallpaperInQueue(albumId, screenType) == null) {
- wallpaperRepository.buildWallpaperQueue(
- albumId,
- screenType,
- shuffle
- )
- }
+ wallpaperRepository.ensureWallpaperQueue(albumId, screenType, shuffle).getOrThrow()
// 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.
@@ -222,6 +110,8 @@ class ChangeWallpaperUseCase @Inject constructor(
screenType,
wallpaperId
)
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Log.w(TAG, "Queue sync failed; it will rebuild on the next change", e)
}
@@ -235,6 +125,8 @@ class ChangeWallpaperUseCase @Inject constructor(
prepared.screenType,
prepared.wallpaperId
)
+ } catch (e: CancellationException) {
+ throw e
} catch (e: Exception) {
Log.e(TAG, "Failed to restore rejected wallpaper to its queue", e)
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/CreateAlbumUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/CreateAlbumUseCase.kt
index 6155af9..b11b2c2 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/CreateAlbumUseCase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/CreateAlbumUseCase.kt
@@ -5,22 +5,12 @@ import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.repository.AlbumRepository
import javax.inject.Inject
-/**
- * Use case to create a new album
- */
class CreateAlbumUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
- suspend operator fun invoke(name: String, coverUri: String? = null): Result {
- if (name.isBlank()) {
- return Result.Error(IllegalArgumentException("Album name cannot be empty"))
- }
-
- val existingAlbum = albumRepository.getAlbumByName(name)
- if (existingAlbum != null) {
- return Result.Error(IllegalArgumentException("Album with this name already exists"))
- }
-
- return albumRepository.createAlbum(name, coverUri)
+ suspend operator fun invoke(name: String, coverUri: String? = null): Result = Result.runCatching {
+ require(name.isNotBlank()) { "Album name cannot be empty" }
+ require(albumRepository.getAlbumByName(name) == null) { "Album with this name already exists" }
+ albumRepository.createAlbum(name, coverUri).getOrThrow()
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/DeleteAlbumUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/DeleteAlbumUseCase.kt
index 2b4ae47..6efe5ee 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/DeleteAlbumUseCase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/DeleteAlbumUseCase.kt
@@ -1,21 +1,18 @@
package com.anthonyla.paperize.domain.usecase
import com.anthonyla.paperize.core.Result
-import com.anthonyla.paperize.data.datastore.PreferencesManager
+import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.AlbumRepository
import javax.inject.Inject
-/**
- * Use case to delete an album
- */
class DeleteAlbumUseCase @Inject constructor(
private val albumRepository: AlbumRepository,
- private val preferencesManager: PreferencesManager
+ private val settingsRepository: SettingsRepository
) {
suspend operator fun invoke(albumId: String): Result {
val result = albumRepository.deleteAlbum(albumId)
if (result is Result.Success) {
- preferencesManager.clearAlbumSelectionsIfMatches(albumId)
+ settingsRepository.clearAlbumSelectionsIfMatches(albumId)
}
return result
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/GetAlbumSummariesUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/GetAlbumSummariesUseCase.kt
deleted file mode 100644
index 6a5a30f..0000000
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/GetAlbumSummariesUseCase.kt
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.anthonyla.paperize.domain.usecase
-
-import com.anthonyla.paperize.domain.model.AlbumSummary
-import com.anthonyla.paperize.domain.repository.AlbumRepository
-import kotlinx.coroutines.flow.Flow
-import javax.inject.Inject
-
-/**
- * Use case to get all album summaries (lightweight metadata + counts)
- * Optimized for displaying lists of albums without loading full wallpaper data
- */
-class GetAlbumSummariesUseCase @Inject constructor(
- private val albumRepository: AlbumRepository
-) {
- operator fun invoke(): Flow> = albumRepository.getAlbumSummaries()
-}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/GetAlbumsUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/GetAlbumsUseCase.kt
deleted file mode 100644
index e0ad9de..0000000
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/GetAlbumsUseCase.kt
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.anthonyla.paperize.domain.usecase
-
-import com.anthonyla.paperize.domain.model.Album
-import com.anthonyla.paperize.domain.repository.AlbumRepository
-import kotlinx.coroutines.flow.Flow
-import javax.inject.Inject
-
-/**
- * Use case to get all albums
- */
-class GetAlbumsUseCase @Inject constructor(
- private val albumRepository: AlbumRepository
-) {
- operator fun invoke(): Flow> = albumRepository.getAllAlbums()
-}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCase.kt
index d7fc7ce..0497ddb 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCase.kt
@@ -1,93 +1,50 @@
package com.anthonyla.paperize.domain.usecase
-import android.content.Context
-import android.content.Intent
-import androidx.core.net.toUri
import com.anthonyla.paperize.core.WallpaperSourceType
import com.anthonyla.paperize.core.util.generateId
-import com.anthonyla.paperize.core.util.getFileName
-import com.anthonyla.paperize.core.util.scanFolderImages
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.AlbumRepository
-import dagger.hilt.android.qualifiers.ApplicationContext
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.currentCoroutineContext
-import kotlinx.coroutines.ensureActive
+import com.anthonyla.paperize.domain.source.DocumentSource
+import com.anthonyla.paperize.domain.source.SourceImage
import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.withContext
import javax.inject.Inject
-/** Prepares imports off the UI thread; the repository writes each import atomically. */
class ImportWallpapersUseCase @Inject constructor(
- @param:ApplicationContext private val context: Context,
+ private val documents: DocumentSource,
private val albumRepository: AlbumRepository
) {
- suspend fun addImages(
- albumId: String,
- uris: List,
- onSaving: (Int, Int) -> Unit
- ): Boolean = withContext(Dispatchers.IO) {
- val album = checkNotNull(albumRepository.getAlbumById(albumId).first())
- val selectedUris = uris.distinct()
- selectedUris.forEach { value ->
- currentCoroutineContext().ensureActive()
- context.contentResolver.takePersistableUriPermission(value.toUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ suspend fun addImages(albumId: String, uris: List, onSaving: (Int, Int) -> Unit): Boolean {
+ val images = uris.distinct().map { uri ->
+ documents.retainReadPermission(uri)
+ documents.readImage(uri).toWallpaper(albumId)
}
- val existingUris = album.wallpapers.map { it.uri }.toHashSet()
- val newUris = selectedUris.filterNot { it in existingUris }
- if (newUris.isEmpty()) return@withContext false
-
- onSaving(0, newUris.size)
- val nextOrder = (album.wallpapers.maxOfOrNull { it.displayOrder } ?: -1) + 1
- val wallpapers = newUris.mapIndexed { index, value ->
- currentCoroutineContext().ensureActive()
- val uri = value.toUri()
- Wallpaper(
- id = generateId(), albumId = albumId, uri = value,
- fileName = uri.getFileName(context) ?: value.substringAfterLast('/'),
- dateModified = System.currentTimeMillis(), displayOrder = nextOrder + index
- )
- }
- albumRepository.addWallpapersToAlbum(albumId, wallpapers, onSaving).onError { throw it }
- true
+ return albumRepository.addWallpapersToAlbum(albumId, images, onSaving)
+ .getOrThrow() > 0
}
suspend fun addFolder(
albumId: String,
- value: String,
+ uri: String,
onScanning: (Int) -> Unit,
onSaving: (Int, Int) -> Unit
- ): Boolean = withContext(Dispatchers.IO) {
- val album = checkNotNull(albumRepository.getAlbumById(albumId).first())
- val uri = value.toUri()
- // Re-selecting a folder also restores its read permission.
- context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
- if (album.folders.any { it.uri == value }) return@withContext false
-
- val images = uri.scanFolderImages(context, onScanning).sortedBy { it.uri.toString() }
+ ): Boolean {
+ documents.retainReadPermission(uri)
+ // Avoid rescanning an existing folder; insertion still checks duplicates atomically.
+ if (albumRepository.getAlbumById(albumId).first()?.folders.orEmpty().any { it.uri == uri }) return false
+ val source = documents.readFolder(uri, onScanning)
val folderId = generateId()
- val wallpapers = images.mapIndexed { index, image ->
- currentCoroutineContext().ensureActive()
- Wallpaper(
- id = generateId(), albumId = albumId, folderId = folderId,
- uri = image.uri.toString(), fileName = image.name,
- dateModified = image.lastModified, displayOrder = index,
- sourceType = WallpaperSourceType.FOLDER
- )
- }
- onSaving(0, wallpapers.size)
val folder = Folder(
- id = folderId, albumId = albumId, uri = value,
- name = androidx.documentfile.provider.DocumentFile.fromTreeUri(context, uri)?.name
- ?: value.substringAfterLast('/'),
- coverUri = wallpapers.firstOrNull()?.uri,
- dateModified = System.currentTimeMillis(),
- displayOrder = (album.folders.maxOfOrNull { it.displayOrder } ?: -1) + 1,
- wallpapers = wallpapers
+ id = folderId, albumId = albumId, uri = uri, name = source.name,
+ coverUri = null, dateModified = System.currentTimeMillis(),
+ wallpapers = source.images.sortedBy { it.uri }.map { it.toWallpaper(albumId, folderId) }
)
- albumRepository.addFolderToAlbum(albumId, folder, onSaving).onError { throw it }
- true
+ return albumRepository.addFolderToAlbum(albumId, folder, onSaving).getOrThrow()
}
-
}
+
+internal fun SourceImage.toWallpaper(albumId: String, folderId: String? = null) = Wallpaper(
+ id = generateId(), albumId = albumId, folderId = folderId, uri = uri,
+ fileName = name, dateModified = modifiedAt,
+ sourceType = if (folderId == null) WallpaperSourceType.DIRECT else WallpaperSourceType.FOLDER
+)
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/ReapplyEffectsUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ReapplyEffectsUseCase.kt
index 7893979..0a2b8dc 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/ReapplyEffectsUseCase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ReapplyEffectsUseCase.kt
@@ -2,113 +2,27 @@ package com.anthonyla.paperize.domain.usecase
import android.content.Context
import android.graphics.Bitmap
-import androidx.core.net.toUri
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.core.ScreenType
-import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
-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.core.util.WallpaperRenderer
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.WallpaperRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
-/**
- * Reapply current visual effects to the last-applied wallpaper without advancing the queue.
- *
- * Used when display settings (blur, darken, scaling, etc.) change and the user wants
- * to see the effect on the current wallpaper immediately rather than jumping to the next one.
- *
- * Returns Result.Error if no current wallpaper has been recorded yet — callers should
- * fall back to [ChangeWallpaperUseCase] in that case.
- */
class ReapplyEffectsUseCase @Inject constructor(
@param:ApplicationContext private val context: Context,
private val wallpaperRepository: WallpaperRepository,
- private val settingsRepository: SettingsRepository
+ private val settingsRepository: SettingsRepository,
+ private val renderer: WallpaperRenderer
) {
- suspend operator fun invoke(
- albumId: String,
- screenType: ScreenType,
- wallpaperId: String? = null
- ): Result {
- return try {
- 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 effects = when (screenType) {
- ScreenType.LIVE -> settings.liveEffects
- ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
- ScreenType.LOCK -> settings.lockEffects
- }
- val scaling = when (screenType) {
- ScreenType.LIVE -> settings.liveScalingType
- ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
- ScreenType.LOCK -> settings.lockScalingType
- }
- val preserveSourceOverflow = usesLauncherManagedScrolling(
- screenType,
- scaling,
- settings.homeScrollingEnabled
- )
- 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,
- preserveSourceOverflow
- )
- ?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
-
- var processed: Bitmap? = null
- try {
- processed = 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 (processed !== bitmap) bitmap.recycle()
-
- if (settings.adaptiveBrightness) {
- val prev = processed
- processed = adaptiveBrightnessAdjustment(context, processed)
- if (processed !== prev) prev.recycle()
- }
-
- Result.Success(processed)
- } catch (e: Exception) {
- if (processed != null && !processed.isRecycled) {
- processed.recycle()
- } else if (!bitmap.isRecycled) {
- bitmap.recycle()
- }
- throw e
- }
- } catch (e: Exception) {
- Result.Error(e)
+ suspend operator fun invoke(albumId: String, screenType: ScreenType, wallpaperId: String? = null): Result =
+ Result.runCatching {
+ val wallpaper = if (wallpaperId != null) wallpaperRepository.getWallpaperById(wallpaperId)
+ else wallpaperRepository.getCurrentWallpaper(albumId, screenType)
+ val message = context.getString(R.string.error_no_valid_wallpaper_after_retries)
+ checkNotNull(wallpaper) { message }
+ checkNotNull(renderer.render(wallpaper, screenType, settingsRepository.getScheduleSettings())) { message }
}
- }
}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshAlbumUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshAlbumUseCase.kt
deleted file mode 100644
index 11873de..0000000
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshAlbumUseCase.kt
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.anthonyla.paperize.domain.usecase
-
-import com.anthonyla.paperize.core.Result
-import com.anthonyla.paperize.domain.repository.AlbumRepository
-import com.anthonyla.paperize.domain.repository.WallpaperRepository
-import javax.inject.Inject
-
-/** Removes confirmed missing entries and returns the number of wallpapers and folders removed. */
-class RefreshAlbumUseCase @Inject constructor(
- private val wallpaperRepository: WallpaperRepository,
- private val albumRepository: AlbumRepository
-) {
- suspend operator fun invoke(albumId: String): Result {
- var totalRemoved = 0
-
- val foldersResult = albumRepository.validateAndRemoveInvalidFolders(albumId)
- if (foldersResult is Result.Success) {
- totalRemoved += foldersResult.data
- }
-
- val wallpapersResult = wallpaperRepository.validateAndRemoveInvalidWallpapers(albumId)
- if (wallpapersResult is Result.Success) {
- totalRemoved += wallpapersResult.data
- }
-
- if (totalRemoved > 0) {
- albumRepository.refreshAlbumCover(albumId)
- albumRepository.refreshFolderCovers(albumId)
- }
-
- return when {
- foldersResult is Result.Error -> foldersResult
- wallpapersResult is Result.Error -> wallpapersResult
- else -> Result.Success(totalRemoved)
- }
- }
-}
diff --git a/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCase.kt b/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCase.kt
index b1aeea6..f8519cd 100644
--- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCase.kt
+++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCase.kt
@@ -1,48 +1,20 @@
package com.anthonyla.paperize.domain.usecase
import com.anthonyla.paperize.core.Result
-import com.anthonyla.paperize.core.map
import com.anthonyla.paperize.domain.repository.AlbumRepository
-import com.anthonyla.paperize.domain.repository.WallpaperRepository
-import androidx.core.net.toUri
-import kotlinx.coroutines.CancellationException
+import com.anthonyla.paperize.domain.source.DocumentSource
import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.sync.Mutex
-import kotlinx.coroutines.sync.withLock
import javax.inject.Inject
-import javax.inject.Singleton
-@Singleton
class RefreshFolderUseCase @Inject constructor(
private val albumRepository: AlbumRepository,
- private val wallpaperRepository: WallpaperRepository
+ private val documents: DocumentSource
) {
- private val refreshMutex = Mutex()
-
- suspend operator fun invoke(folderId: String): Result {
- return try {
- val folder = albumRepository.getFolderById(folderId).first()
- ?: return Result.Success(0)
- val scan = wallpaperRepository.scanFolderForWallpapers(folder.uri.toUri())
- if (scan !is Result.Success) return scan.map { 0 }
-
- // Serialize read-and-save, but let unrelated provider scans run independently.
- refreshMutex.withLock {
- val current = albumRepository.getFolderById(folderId).first()
- ?: return@withLock Result.Success(0)
- val existingUris = current.wallpapers.map { it.uri }.toHashSet()
- val nextOrder = (current.wallpapers.maxOfOrNull { it.displayOrder } ?: -1) + 1
- val additions = scan.data.filterNot { it.uri in existingUris }
- .mapIndexed { index, wallpaper ->
- wallpaper.copy(albumId = current.albumId, folderId = folderId, displayOrder = nextOrder + index)
- }
- if (additions.isEmpty()) return@withLock Result.Success(0)
- albumRepository.addWallpapersToAlbum(current.albumId, additions).map { additions.size }
- }
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- Result.Error(e)
- }
+ suspend operator fun invoke(folderId: String): Result = Result.runCatching {
+ val folder = albumRepository.getFolderById(folderId).first() ?: return@runCatching 0
+ val source = documents.readFolder(folder.uri)
+ albumRepository.addWallpapersToAlbum(
+ folder.albumId, source.images.map { it.toWallpaper(folder.albumId, folderId) }
+ ).getOrThrow()
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt b/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt
index 1e8d355..8a6c2a7 100644
--- a/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt
+++ b/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt
@@ -4,18 +4,13 @@ import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
-import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
-import androidx.compose.runtime.saveable.rememberSaveable
-import androidx.compose.runtime.snapshotFlow
-import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
-import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.presentation.common.navigation.HomeRoute
import com.anthonyla.paperize.presentation.common.navigation.NavigationGraph
import com.anthonyla.paperize.presentation.common.navigation.StartupRoute
@@ -23,11 +18,6 @@ import com.anthonyla.paperize.presentation.common.theme.PaperizeTheme
import com.anthonyla.paperize.presentation.screens.settings.SettingsViewModel
import dagger.hilt.android.AndroidEntryPoint
-/**
- * Main activity for Paperize
- *
- * Single activity architecture with Jetpack Compose
- */
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@@ -38,30 +28,17 @@ class MainActivity : ComponentActivity() {
setContent {
val settingsViewModel: SettingsViewModel = hiltViewModel()
- // Track if DataStore has loaded at least once
- // This prevents the loading screen from showing again if the composable is recomposed
- val appSettingsState by settingsViewModel.appSettings.collectAsStateWithLifecycle()
-
- // Remember if we've ever loaded settings to prevent losing NavigationGraph during recreation
- var settingsLoadedOnce by rememberSaveable { mutableStateOf(false) }
- val currentSettings = appSettingsState
-
- if (currentSettings != null) {
- settingsLoadedOnce = true
- }
-
+ val currentSettings by settingsViewModel.appSettings.collectAsStateWithLifecycle()
PaperizeTheme(
- darkMode = currentSettings?.darkMode ?: false,
+ darkMode = currentSettings?.darkMode,
dynamicTheming = currentSettings?.dynamicTheming ?: false
) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
- // Only render navigation once DataStore has loaded
- // After first load, always show navigation even during updates
- if (settingsLoadedOnce) {
+ if (currentSettings != null) {
NavigationGraph(
startDestination = if (currentSettings?.firstLaunch != false) StartupRoute else HomeRoute,
animate = currentSettings?.animate ?: true,
@@ -69,11 +46,6 @@ class MainActivity : ComponentActivity() {
settingsViewModel.updateFirstLaunch(false)
}
)
- } else {
- // Show blank screen briefly while DataStore loads on first start (usually <100ms)
- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- // Empty - just shows background color while DataStore loads
- }
}
}
}
diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt
index 215cfbf..a90e215 100644
--- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt
+++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt
@@ -25,18 +25,6 @@ import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.res.stringResource
import com.anthonyla.paperize.R
-/**
- * Material 3 Expressive FAB Menu for adding images and folders to albums
- *
- * Migrated to use FloatingActionButtonMenu, ToggleFloatingActionButton, and
- * FloatingActionButtonMenuItem from Material 3 Expressive design system.
- *
- * Features:
- * - Physics-based animations from expressive motion scheme
- * - Staggered menu item reveal animations
- * - Smooth icon morphing between Add and Close
- * - Accessibility support with proper traversal and custom actions
- */
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun AddAlbumAnimatedFab(
@@ -47,7 +35,6 @@ fun AddAlbumAnimatedFab(
) {
var fabMenuExpanded by rememberSaveable { mutableStateOf(false) }
- // Collapse menu when back button is pressed
BackHandler(fabMenuExpanded) { fabMenuExpanded = false }
FloatingActionButtonMenu(
@@ -58,7 +45,6 @@ fun AddAlbumAnimatedFab(
checked = fabMenuExpanded,
onCheckedChange = { if (!isLoading) fabMenuExpanded = !fabMenuExpanded }
) {
- // Animate between Add and Close icons based on checked progress
val imageVector by remember {
derivedStateOf {
if (checkedProgress > 0.5f) Icons.Filled.Close else Icons.Filled.Add
@@ -76,7 +62,6 @@ fun AddAlbumAnimatedFab(
}
}
) {
- // Menu items are revealed with staggered animation when menu expands
FloatingActionButtonMenuItem(
onClick = {
onImageClick()
diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt
index 9258506..fe4f11a 100644
--- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt
+++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt
@@ -3,26 +3,24 @@ package com.anthonyla.paperize.presentation.common.components
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
+import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.R
import com.anthonyla.paperize.presentation.theme.AppSpacing
-/**
- * Dialog for adding a new album
- */
@Composable
fun AddAlbumDialog(
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
+ modifier: Modifier = Modifier,
errorMessage: String? = null,
- modifier: Modifier = Modifier
+ isSaving: Boolean = false
) {
- var albumName by remember { mutableStateOf("") }
+ var albumName by rememberSaveable { mutableStateOf("") }
AlertDialog(
- onDismissRequest = onDismiss,
+ onDismissRequest = { if (!isSaving) onDismiss() },
title = { Text(stringResource(R.string.add_album)) },
text = {
Column {
@@ -30,6 +28,7 @@ fun AddAlbumDialog(
Spacer(modifier = Modifier.height(AppSpacing.small))
OutlinedTextField(
value = albumName,
+ enabled = !isSaving,
onValueChange = { albumName = it },
label = { Text(stringResource(R.string.album_name)) },
singleLine = true,
@@ -43,95 +42,14 @@ fun AddAlbumDialog(
},
confirmButton = {
TextButton(
- onClick = {
- if (albumName.isNotBlank()) {
- onConfirm(albumName.trim())
- }
- },
- enabled = albumName.isNotBlank()
+ onClick = { onConfirm(albumName.trim()) },
+ enabled = !isSaving && albumName.isNotBlank()
) {
Text(stringResource(R.string.save))
}
},
dismissButton = {
- TextButton(onClick = onDismiss) {
- Text(stringResource(R.string.cancel))
- }
- },
- modifier = modifier
- )
-}
-
-/**
- * Dialog for editing album name
- */
-@Composable
-fun EditAlbumNameDialog(
- currentName: String,
- onDismiss: () -> Unit,
- onConfirm: (String) -> Unit,
- modifier: Modifier = Modifier
-) {
- var albumName by remember { mutableStateOf(currentName) }
-
- AlertDialog(
- onDismissRequest = onDismiss,
- title = { Text(stringResource(R.string.change_name)) },
- text = {
- OutlinedTextField(
- value = albumName,
- onValueChange = { albumName = it },
- label = { Text(stringResource(R.string.album_name)) },
- singleLine = true,
- modifier = Modifier.fillMaxWidth()
- )
- },
- confirmButton = {
- TextButton(
- onClick = {
- if (albumName.isNotBlank()) {
- onConfirm(albumName.trim())
- }
- },
- enabled = albumName.isNotBlank()
- ) {
- Text(stringResource(R.string.save))
- }
- },
- dismissButton = {
- TextButton(onClick = onDismiss) {
- Text(stringResource(R.string.cancel))
- }
- },
- modifier = modifier
- )
-}
-
-/**
- * Dialog for confirming reset
- */
-@Composable
-fun ResetDialog(
- onDismiss: () -> Unit,
- onConfirm: () -> Unit,
- modifier: Modifier = Modifier
-) {
- AlertDialog(
- onDismissRequest = onDismiss,
- title = { Text(stringResource(R.string.reset_all_data)) },
- text = { Text(stringResource(R.string.are_you_sure_you_want_to_reset_all_settings_and_data_to_default)) },
- confirmButton = {
- TextButton(
- onClick = onConfirm,
- colors = ButtonDefaults.textButtonColors(
- contentColor = MaterialTheme.colorScheme.error
- )
- ) {
- Text(stringResource(R.string.confirm))
- }
- },
- dismissButton = {
- TextButton(onClick = onDismiss) {
+ TextButton(onClick = onDismiss, enabled = !isSaving) {
Text(stringResource(R.string.cancel))
}
},
diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt
deleted file mode 100644
index ce45d7f..0000000
--- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.anthonyla.paperize.presentation.common.components
-
-import android.net.Uri
-import androidx.activity.compose.rememberLauncherForActivityResult
-import androidx.activity.result.PickVisualMediaRequest
-import androidx.activity.result.contract.ActivityResultContracts
-import androidx.compose.runtime.Composable
-
-/**
- * Media picker using Android Photo Picker
- * Supports images only
- */
-@Composable
-fun rememberImagePicker(
- onImagesSelected: (List) -> Unit
-): () -> Unit {
- val launcher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.PickMultipleVisualMedia()
- ) { uris ->
- if (uris.isNotEmpty()) {
- onImagesSelected(uris)
- }
- }
-
- return {
- // Allow images only
- launcher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
- }
-}
-
-/**
- * Folder picker using Storage Access Framework
- */
-@Composable
-fun rememberFolderPicker(
- onFolderSelected: (Uri) -> Unit
-): () -> Unit {
- val launcher = rememberLauncherForActivityResult(
- contract = ActivityResultContracts.OpenDocumentTree()
- ) { uri ->
- uri?.let { onFolderSelected(it) }
- }
-
- return { launcher.launch(null) }
-}
diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/SettingsComponents.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/SettingsComponents.kt
index 6add226..ab3cbfe 100644
--- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/SettingsComponents.kt
+++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/SettingsComponents.kt
@@ -2,7 +2,6 @@ package com.anthonyla.paperize.presentation.common.components
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.interaction.MutableInteractionSource
-import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -12,14 +11,13 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.presentation.theme.AppSpacing
-/**
- * Setting item with a switch - Enhanced with better surface layering
- */
@Composable
fun SettingSwitchItem(
title: String,
@@ -52,6 +50,7 @@ fun SettingSwitchItem(
) {
Text(
text = title,
+ fontWeight = FontWeight.SemiBold,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
maxLines = 2,
@@ -79,18 +78,6 @@ fun SettingSwitchItem(
}
}
-/**
- * Elevated interactive card with dynamic corner radius
- * Perfect for cards in lists or grids with press feedback
- *
- * @param onClick Click handler
- * @param modifier Modifier for the card
- * @param enabled Whether the card is enabled
- * @param pressedRadius Corner radius when pressed
- * @param defaultRadius Default corner radius
- * @param elevation Card elevation
- * @param content Card content
- */
@Composable
fun InteractiveCard(
onClick: () -> Unit,
@@ -109,17 +96,12 @@ fun InteractiveCard(
label = "card_corner_radius"
)
- val cardElevation by animateDpAsState(
- targetValue = if (isPressed) elevation + 2.dp else elevation,
- label = "card_elevation"
- )
-
Card(
onClick = onClick,
modifier = modifier,
enabled = enabled,
shape = RoundedCornerShape(cornerRadius),
- elevation = CardDefaults.cardElevation(defaultElevation = cardElevation),
+ elevation = CardDefaults.cardElevation(defaultElevation = elevation, pressedElevation = elevation + 2.dp),
interactionSource = interactionSource,
content = content
)
diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt
index bcb784c..c2018bc 100644
--- a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt
+++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt
@@ -26,9 +26,6 @@ import com.anthonyla.paperize.presentation.screens.sort.SortViewScreen
import com.anthonyla.paperize.presentation.screens.startup.StartupScreen
import com.anthonyla.paperize.presentation.screens.wallpaper_view.WallpaperViewScreen
-/**
- * Navigation graph for Paperize
- */
@Composable
fun NavigationGraph(
modifier: Modifier = Modifier,
@@ -37,7 +34,6 @@ fun NavigationGraph(
animate: Boolean = true,
onFirstLaunchComplete: () -> Unit = {}
) {
- // Conditional transitions based on animate setting
val enterForward: AnimatedContentTransitionScope.() -> EnterTransition =
if (animate) { { enterTransitionForward() } } else { { EnterTransition.None } }
val exitForward: AnimatedContentTransitionScope.() -> ExitTransition =
@@ -51,15 +47,13 @@ fun NavigationGraph(
NavHost(
navController = navController,
startDestination = startDestination,
- modifier = modifier
+ modifier = modifier,
+ enterTransition = enterForward,
+ exitTransition = exitForward,
+ popEnterTransition = enterBackward,
+ popExitTransition = exitBackward
) {
- // Startup screen (first launch)
- composable