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( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { + composable { StartupScreen( onAgree = { navController.navigate(WallpaperModeSelectionRoute) { @@ -72,13 +66,7 @@ fun NavigationGraph( ) } - // Wallpaper mode selection screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { + composable { com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection.WallpaperModeSelectionScreen( onModeSelected = { if (!PermissionUtil.hasNotificationPermission(context)) { @@ -95,13 +83,7 @@ fun NavigationGraph( ) } - // Notification permission screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { + composable { NotificationPermissionScreen( onContinue = { onFirstLaunchComplete() @@ -112,13 +94,7 @@ fun NavigationGraph( ) } - // Home screen (main screen with tabs) - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { + composable { HomeScreen( onNavigateToSettings = { navController.navigate(SettingsRoute) @@ -129,14 +105,7 @@ fun NavigationGraph( ) } - // Album screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { backStackEntry -> - backStackEntry.toRoute() + composable { AlbumViewScreen( onBackClick = { navController.popBackStack() }, onNavigateToFolder = { folderId -> @@ -150,28 +119,14 @@ fun NavigationGraph( ) } - // Sort screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { backStackEntry -> - backStackEntry.toRoute() + composable { SortViewScreen( onSaveClick = { navController.popBackStack() }, onBackClick = { navController.popBackStack() } ) } - // Folder screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { backStackEntry -> - backStackEntry.toRoute() + composable { FolderViewScreen( onBackClick = { navController.popBackStack() }, onNavigateToWallpaperView = { wallpaperId, wallpaperUri, wallpaperName -> @@ -182,13 +137,7 @@ fun NavigationGraph( ) } - // Wallpaper preview screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { backStackEntry -> + composable { backStackEntry -> val route = backStackEntry.toRoute() WallpaperViewScreen( wallpaperUri = route.wallpaperUri, @@ -197,26 +146,14 @@ fun NavigationGraph( ) } - // Settings screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { + composable { SettingsScreen( onNavigateBack = { navController.popBackStack() }, onNavigateToPrivacy = { navController.navigate(PrivacyRoute) } ) } - // Privacy screen - composable( - enterTransition = enterForward, - exitTransition = exitForward, - popEnterTransition = enterBackward, - popExitTransition = exitBackward - ) { + composable { PrivacyScreen( onNavigateBack = { navController.popBackStack() } ) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt index df5e119..dc51d56 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt @@ -2,10 +2,6 @@ package com.anthonyla.paperize.presentation.common.navigation import kotlinx.serialization.Serializable -/** - * Type-safe navigation routes using kotlinx.serialization - */ - @Serializable object StartupRoute diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/NavConstants.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/NavConstants.kt index 86388e4..00faec8 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/NavConstants.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/NavConstants.kt @@ -1,8 +1,5 @@ package com.anthonyla.paperize.presentation.common.navigation.util -/** - * Constants for navigation animations - */ object NavConstants { /** Duration of navigation animations in milliseconds */ const val NAVIGATION_TIME: Int = 300 diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/SharedXTransition.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/SharedXTransition.kt index 2969df2..2956a14 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/SharedXTransition.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/util/SharedXTransition.kt @@ -11,21 +11,11 @@ import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally -/** - * Shared horizontal transition for entering screens - * - * Creates a smooth slide-in animation from the specified offset with a delayed fade-in effect. - * The fade-in starts after the outgoing screen begins to fade out, creating a seamless transition. - * - * @param initial Lambda that calculates the initial horizontal offset based on screen width - * @param durationMillis Total animation duration in milliseconds (default from NavConstants) - * @return Combined enter transition with slide and fade animations - */ +/** Slides in with a delayed fade so the outgoing screen fades first. */ fun sharedXTransitionIn( initial: (fullWidth: Int) -> Int, durationMillis: Int = NavConstants.NAVIGATION_TIME, ): EnterTransition { - // Calculate timing for outgoing and incoming animations val outgoingDuration = (durationMillis * NavConstants.OFFSET_LIMIT).toInt() val incomingDuration = durationMillis - outgoingDuration @@ -44,21 +34,11 @@ fun sharedXTransitionIn( ) } -/** - * Shared horizontal transition for exiting screens - * - * Creates a smooth slide-out animation to the specified offset with an immediate fade-out effect. - * The fade-out starts immediately to make way for the incoming screen. - * - * @param target Lambda that calculates the target horizontal offset based on screen width - * @param durationMillis Total animation duration in milliseconds (default from NavConstants) - * @return Combined exit transition with slide and fade animations - */ +/** Slides out while fading immediately to make room for the incoming screen. */ fun sharedXTransitionOut( target: (fullWidth: Int) -> Int, durationMillis: Int = NavConstants.NAVIGATION_TIME, ): ExitTransition { - // Calculate timing for outgoing fade animation val outgoingDuration = (durationMillis * NavConstants.OFFSET_LIMIT).toInt() return slideOutHorizontally( diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Color.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Color.kt index a86d65d..b34fb10 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Color.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Color.kt @@ -2,82 +2,66 @@ package com.anthonyla.paperize.presentation.common.theme import androidx.compose.ui.graphics.Color -/** - * Material 3 Expressive Color Palette - * - * Enhanced vibrant palette inspired by Material 3 Expressive design - * Features richer, more saturated colors with improved contrast and visual hierarchy - * Designed for warmth, approachability, and expressive visual appeal - */ - -// Light Theme Colors - Enhanced with more vibrant, saturated tones -val md_theme_light_primary = Color(0xFFB8336A) // More vibrant rose pink +val md_theme_light_primary = Color(0xFFB8336A) val md_theme_light_onPrimary = Color(0xFFFFFFFF) -val md_theme_light_primaryContainer = Color(0xFFFFD9E4) // Softer pink container -val md_theme_light_onPrimaryContainer = Color(0xFF8C1F4C) // Deeper contrast -val md_theme_light_secondary = Color(0xFF8B5563) // Warmer, richer secondary +val md_theme_light_primaryContainer = Color(0xFFFFD9E4) +val md_theme_light_onPrimaryContainer = Color(0xFF8C1F4C) +val md_theme_light_secondary = Color(0xFF8B5563) val md_theme_light_onSecondary = Color(0xFFFFFFFF) -val md_theme_light_secondaryContainer = Color(0xFFFFDAE1) // Lighter, airier container -val md_theme_light_onSecondaryContainer = Color(0xFF6A3D49) // Better contrast -val md_theme_light_tertiary = Color(0xFFA35F35) // Richer terracotta/amber +val md_theme_light_secondaryContainer = Color(0xFFFFDAE1) +val md_theme_light_onSecondaryContainer = Color(0xFF6A3D49) +val md_theme_light_tertiary = Color(0xFFA35F35) val md_theme_light_onTertiary = Color(0xFFFFFFFF) -val md_theme_light_tertiaryContainer = Color(0xFFFFDCC2) // Warm peach container -val md_theme_light_onTertiaryContainer = Color(0xFF7A4520) // Deeper brown +val md_theme_light_tertiaryContainer = Color(0xFFFFDCC2) +val md_theme_light_onTertiaryContainer = Color(0xFF7A4520) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF93000A) -val md_theme_light_background = Color(0xFFFFFBFF) // Cleaner, brighter background -val md_theme_light_onBackground = Color(0xFF211A1C) // Slightly warmer black -val md_theme_light_surface = Color(0xFFFFFBFF) // Consistent with background +val md_theme_light_background = Color(0xFFFFFBFF) +val md_theme_light_onBackground = Color(0xFF211A1C) +val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF211A1C) -val md_theme_light_surfaceVariant = Color(0xFFF4DDE2) // Softer surface variant -val md_theme_light_onSurfaceVariant = Color(0xFF524245) // Improved readability -val md_theme_light_outline = Color(0xFF857275) // Warmer outline -val md_theme_light_inverseOnSurface = Color(0xFFFEEDF0) // Softer inverse -val md_theme_light_inverseSurface = Color(0xFF372E2F) // Richer inverse surface -val md_theme_light_inversePrimary = Color(0xFFFFB0C8) // Vibrant inverse primary -val md_theme_light_shadow = Color(0xFF000000) -val md_theme_light_surfaceTint = Color(0xFFB8336A) // Match new primary -val md_theme_light_outlineVariant = Color(0xFFD7C1C4) // Softer outline variant +val md_theme_light_surfaceVariant = Color(0xFFF4DDE2) +val md_theme_light_onSurfaceVariant = Color(0xFF524245) +val md_theme_light_outline = Color(0xFF857275) +val md_theme_light_inverseOnSurface = Color(0xFFFEEDF0) +val md_theme_light_inverseSurface = Color(0xFF372E2F) +val md_theme_light_inversePrimary = Color(0xFFFFB0C8) +val md_theme_light_surfaceTint = Color(0xFFB8336A) +val md_theme_light_outlineVariant = Color(0xFFD7C1C4) val md_theme_light_scrim = Color(0xFF000000) -// Dark Theme Colors - Enhanced with richer, more luminous tones -val md_theme_dark_primary = Color(0xFFFFB3CA) // Brighter, more luminous pink -val md_theme_dark_onPrimary = Color(0xFF650033) // Deeper contrast -val md_theme_dark_primaryContainer = Color(0xFF8F1F4F) // Richer container -val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E4) // Softer on-container -val md_theme_dark_secondary = Color(0xFFE7BFC8) // Warmer, softer secondary -val md_theme_dark_onSecondary = Color(0xFF4A2A32) // Better contrast -val md_theme_dark_secondaryContainer = Color(0xFF714551) // Richer container -val md_theme_dark_onSecondaryContainer = Color(0xFFFFDAE1) // Improved readability -val md_theme_dark_tertiary = Color(0xFFF5C098) // Warmer, richer amber -val md_theme_dark_onTertiary = Color(0xFF522A0C) // Deeper contrast -val md_theme_dark_tertiaryContainer = Color(0xFF7F4825) // Richer brown container -val md_theme_dark_onTertiaryContainer = Color(0xFFFFDCC2) // Softer peach +val md_theme_dark_primary = Color(0xFFFFB3CA) +val md_theme_dark_onPrimary = Color(0xFF650033) +val md_theme_dark_primaryContainer = Color(0xFF8F1F4F) +val md_theme_dark_onPrimaryContainer = Color(0xFFFFD9E4) +val md_theme_dark_secondary = Color(0xFFE7BFC8) +val md_theme_dark_onSecondary = Color(0xFF4A2A32) +val md_theme_dark_secondaryContainer = Color(0xFF714551) +val md_theme_dark_onSecondaryContainer = Color(0xFFFFDAE1) +val md_theme_dark_tertiary = Color(0xFFF5C098) +val md_theme_dark_onTertiary = Color(0xFF522A0C) +val md_theme_dark_tertiaryContainer = Color(0xFF7F4825) +val md_theme_dark_onTertiaryContainer = Color(0xFFFFDCC2) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) -val md_theme_dark_background = Color(0xFF1A1114) // Slightly warmer, richer black -val md_theme_dark_onBackground = Color(0xFFF0E0E2) // Softer, warmer white -val md_theme_dark_surface = Color(0xFF1A1114) // Consistent with background -val md_theme_dark_onSurface = Color(0xFFF0E0E2) // Improved readability -val md_theme_dark_surfaceVariant = Color(0xFF534244) // Warmer surface variant -val md_theme_dark_onSurfaceVariant = Color(0xFFD7C1C4) // Better contrast -val md_theme_dark_outline = Color(0xFFA08C8F) // Warmer outline -val md_theme_dark_inverseOnSurface = Color(0xFF1A1114) // Richer inverse -val md_theme_dark_inverseSurface = Color(0xFFF0E0E2) // Softer inverse surface -val md_theme_dark_inversePrimary = Color(0xFFB8336A) // Match light primary -val md_theme_dark_shadow = Color(0xFF000000) -val md_theme_dark_surfaceTint = Color(0xFFFFB3CA) // Match new primary -val md_theme_dark_outlineVariant = Color(0xFF534244) // Warmer variant +val md_theme_dark_background = Color(0xFF1A1114) +val md_theme_dark_onBackground = Color(0xFFF0E0E2) +val md_theme_dark_surface = Color(0xFF1A1114) +val md_theme_dark_onSurface = Color(0xFFF0E0E2) +val md_theme_dark_surfaceVariant = Color(0xFF534244) +val md_theme_dark_onSurfaceVariant = Color(0xFFD7C1C4) +val md_theme_dark_outline = Color(0xFFA08C8F) +val md_theme_dark_inverseOnSurface = Color(0xFF1A1114) +val md_theme_dark_inverseSurface = Color(0xFFF0E0E2) +val md_theme_dark_inversePrimary = Color(0xFFB8336A) +val md_theme_dark_surfaceTint = Color(0xFFFFB3CA) +val md_theme_dark_outlineVariant = Color(0xFF534244) val md_theme_dark_scrim = Color(0xFF000000) -// Seed color for Material Theme Builder -val seed = Color(0xFFFFB3CA) // Updated to match new vibrant primary - -// Surface container colors for enhanced layering (Material 3 Expressive) val md_theme_light_surfaceContainer = Color(0xFFF7F2F3) val md_theme_light_surfaceContainerHigh = Color(0xFFF1ECEE) val md_theme_light_surfaceContainerHighest = Color(0xFFEBE6E8) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Shape.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Shape.kt index bc8828e..1ff8b56 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Shape.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Shape.kt @@ -4,23 +4,6 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp -/** - * Material 3 Expressive Shapes - * - * Expressive uses larger, more pronounced corner radii to create softer, more approachable - * and dynamic UI elements. This follows the M3 Expressive shape system which emphasizes - * rounded corners for a friendlier, more engaging aesthetic. - * - * Key differences from baseline Material 3: - * - extraSmall: 8dp (was 4dp) - Subtle rounding for tight spaces - * - small: 12dp (was 8dp) - Cards, chips, and small containers - * - medium: 16dp (was 12dp) - Standard cards and containers - * - large: 24dp (was 16dp) - Large cards, bottom sheets - * - extraLarge: 32dp (was 28dp) - Full-screen dialogs, large surfaces - * - * These increased radii create a more modern, expressive feel while maintaining - * the established Material 3 shape token hierarchy. - */ val ExpressiveShapes = Shapes( extraSmall = RoundedCornerShape(8.dp), small = RoundedCornerShape(12.dp), diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt index 49dd3aa..77b35de 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt @@ -1,11 +1,9 @@ package com.anthonyla.paperize.presentation.common.theme import android.app.Activity -import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialExpressiveTheme -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MotionScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme @@ -13,7 +11,6 @@ import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect -import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat @@ -92,10 +89,6 @@ private val DarkColors = darkColorScheme( surfaceContainerLowest = md_theme_dark_surfaceContainerLowest, ) -/** - * App theming for dynamic theming when supported and dark mode. - * Migrated to Material 3 Expressive design system with enhanced motion, typography, and shapes. - */ @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable fun PaperizeTheme( @@ -104,21 +97,17 @@ fun PaperizeTheme( content: @Composable () -> Unit ) { val context = LocalContext.current - val isDarkMode = isDarkMode(darkMode = darkMode) - val isDynamicTheming = isDynamicTheming(dynamicTheming = dynamicTheming) + val isDarkMode = darkMode ?: isSystemInDarkTheme() - // Dynamic theming (Material You) is always supported (minSdk 31) val colors = when { - isDynamicTheming && isDarkMode -> dynamicDarkColorScheme(context) - isDynamicTheming && !isDarkMode -> dynamicLightColorScheme(context) + dynamicTheming && isDarkMode -> dynamicDarkColorScheme(context) + dynamicTheming && !isDarkMode -> dynamicLightColorScheme(context) isDarkMode -> DarkColors else -> LightColors } - // Use expressive motion scheme for enhanced animations and transitions val motionScheme = MotionScheme.expressive() - // Set the status bar color and system bar style to transparent val view = LocalView.current if (!view.isInEditMode) { SideEffect { @@ -136,18 +125,3 @@ fun PaperizeTheme( content = content ) } - -@Composable -private fun isDarkMode(darkMode: Boolean?): Boolean = - when(darkMode) { - true -> true - false -> false - else -> isSystemInDarkTheme() - } - -@Composable -private fun isDynamicTheming(dynamicTheming: Boolean): Boolean = - when(dynamicTheming) { - true -> true - false -> false - } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Type.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Type.kt index 429ac63..7557f50 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Type.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Type.kt @@ -6,27 +6,14 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp -/** - * Material 3 Expressive Typography - * - * Expressive emphasizes bolder, more impactful type styles with increased weight and tracking - * to create a more vibrant and engaging visual hierarchy. This follows the M3 Expressive - * "emphasized" type scale for heightened visual impact. - * - * Key differences from baseline: - * - Headlines use Bold (700) instead of Normal (400) weight - * - Display styles use SemiBold (600) for more presence - * - Increased letter spacing for improved readability - * - Tighter line heights for more compact, punchy text blocks - */ val ExpressiveTypography = Typography( - // Display styles - Expressive uses SemiBold for more visual weight + displayLarge = TextStyle( fontFamily = FontFamily.Default, - fontWeight = FontWeight.SemiBold, // Changed from Normal to SemiBold + fontWeight = FontWeight.SemiBold, fontSize = 57.sp, lineHeight = 64.sp, - letterSpacing = (-0.15).sp // Slightly tighter for emphasis + letterSpacing = (-0.15).sp ), displayMedium = TextStyle( fontFamily = FontFamily.Default, @@ -43,10 +30,9 @@ val ExpressiveTypography = Typography( letterSpacing = 0.sp ), - // Headline styles - Expressive uses Bold for maximum impact headlineLarge = TextStyle( fontFamily = FontFamily.Default, - fontWeight = FontWeight.Bold, // Changed from Normal to Bold + fontWeight = FontWeight.Bold, fontSize = 32.sp, lineHeight = 40.sp, letterSpacing = 0.sp @@ -66,7 +52,6 @@ val ExpressiveTypography = Typography( letterSpacing = 0.sp ), - // Title styles - Keep Medium weight but with optimized spacing titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, @@ -89,7 +74,6 @@ val ExpressiveTypography = Typography( letterSpacing = 0.1.sp ), - // Body styles - Standard weight for readability bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, @@ -112,7 +96,6 @@ val ExpressiveTypography = Typography( letterSpacing = 0.4.sp ), - // Label styles - Medium weight for UI elements labelLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/components/OnboardingLayout.kt b/app/src/main/java/com/anthonyla/paperize/presentation/components/OnboardingLayout.kt index a8d6052..7e064e3 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/components/OnboardingLayout.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/components/OnboardingLayout.kt @@ -132,7 +132,6 @@ fun OnboardingLayout( Spacer(modifier = Modifier.height(AppSpacing.extraLarge)) - // Actions now part of the scrollable content to handle small heights (landscape) AnimatedVisibility( visible = visible, enter = fadeIn(animationSpec = tween(500, delayMillis = 300)) + diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt index fb769d2..2e781d0 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt @@ -106,14 +106,7 @@ fun AlbumViewScreen( } val sortedWallpapers = remember(wallpapers, sortOption) { - when (sortOption) { - SortOption.NAME_ASC -> wallpapers.sortedBy { it.fileName.lowercase() } - SortOption.NAME_DESC -> wallpapers.sortedByDescending { it.fileName.lowercase() } - SortOption.DATE_ADDED_ASC -> wallpapers.sortedBy { it.addedAt } - SortOption.DATE_ADDED_DESC -> wallpapers.sortedByDescending { it.addedAt } - SortOption.DATE_MODIFIED_ASC -> wallpapers.sortedBy { it.dateModified } - SortOption.DATE_MODIFIED_DESC -> wallpapers.sortedByDescending { it.dateModified } - } + wallpapers.sortedWith(sortOption.wallpaperComparator) } val commonItemModifier = remember { diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt index 0df1fe1..26702cb 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt @@ -113,8 +113,8 @@ class AlbumViewViewModel @Inject constructor( viewModelScope.launch { try { deleteAlbumUseCase(albumId) - .onSuccess { _albumDeleted.value = true } - .onError { throw it } + .getOrThrow() + _albumDeleted.value = true } catch (e: CancellationException) { throw e } catch (e: Exception) { diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt index ad87d92..9484638 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/ImportProgress.kt @@ -1,16 +1,10 @@ package com.anthonyla.paperize.presentation.screens.album_view -/** - * Progress of an ongoing add-folder / add-wallpapers import, surfaced to the UI so it can - * show a live count instead of a bare spinner. - */ sealed interface ImportProgress { - /** No import running. */ data object Idle : ImportProgress /** Walking the folder tree; the total is not yet known. */ data class Scanning(val found: Int) : ImportProgress - /** Writing the discovered images to the database. */ data class Saving(val saved: Int, val total: Int) : ImportProgress } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt index f3ab1d7..4fdfeb6 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/AlbumViewTopBar.kt @@ -32,7 +32,6 @@ fun AlbumViewTopBar( onClearSelection: () -> Unit ) { if (isSelectionMode) { - // Selection mode topbar TopAppBar( title = { Text( @@ -65,7 +64,6 @@ fun AlbumViewTopBar( } ) } else { - // Normal mode topbar TopAppBar( title = { Text( diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/FolderItem.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/FolderItem.kt index 9e87eab..20047c3 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/FolderItem.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/FolderItem.kt @@ -21,11 +21,11 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.selected import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp -import com.anthonyla.paperize.R import com.anthonyla.paperize.domain.model.Folder import com.anthonyla.paperize.presentation.theme.AppSpacing @@ -39,7 +39,6 @@ fun FolderItem( onLongClick: () -> Unit, modifier: Modifier = Modifier ) { - // Animate selection state changes val transition = updateTransition(isSelected, label = "FolderItemSelection") val paddingTransition by transition.animateDp(label = "padding") { selected -> if (selected) 5.dp else 0.dp @@ -50,6 +49,7 @@ fun FolderItem( Card( modifier = modifier + .semantics { if (isSelectionMode) selected = isSelected } .padding(paddingTransition) .combinedClickable( onClick = onClick, @@ -70,7 +70,7 @@ fun FolderItem( ) { Icon( imageVector = Icons.Default.Folder, - contentDescription = folder.displayName, + contentDescription = null, modifier = Modifier.fillMaxSize(0.5f), tint = if (isSelected) { MaterialTheme.colorScheme.primary.copy(alpha = 0.7f) @@ -89,27 +89,13 @@ fun FolderItem( .padding(AppSpacing.small) ) - // Selection indicator if (isSelectionMode) { - if (isSelected) { - Icon( - imageVector = Icons.Default.CheckCircle, - contentDescription = stringResource(R.string.content_desc_selected), - tint = MaterialTheme.colorScheme.primary, - modifier = Modifier - .align(Alignment.TopEnd) - .padding(AppSpacing.small) - ) - } else { - Icon( - imageVector = Icons.Default.RadioButtonUnchecked, - contentDescription = stringResource(R.string.content_desc_not_selected), - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier - .align(Alignment.TopEnd) - .padding(AppSpacing.small) - ) - } + Icon( + imageVector = if (isSelected) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked, + contentDescription = null, + tint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.align(Alignment.TopEnd).padding(AppSpacing.small) + ) } } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt index 975522d..06624b5 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt @@ -25,6 +25,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp +import com.anthonyla.paperize.domain.model.Wallpaper import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppSpacing @@ -34,12 +35,19 @@ enum class SortOption(val labelRes: Int) { DATE_ADDED_ASC(R.string.sort_date_added_asc), DATE_ADDED_DESC(R.string.sort_date_added_desc), DATE_MODIFIED_ASC(R.string.sort_date_modified_asc), - DATE_MODIFIED_DESC(R.string.sort_date_modified_desc) + DATE_MODIFIED_DESC(R.string.sort_date_modified_desc); + + val wallpaperComparator: Comparator + get() = when (this) { + NAME_ASC -> compareBy { it.fileName.lowercase() } + NAME_DESC -> compareByDescending { it.fileName.lowercase() } + DATE_ADDED_ASC -> compareBy { it.addedAt } + DATE_ADDED_DESC -> compareByDescending { it.addedAt } + DATE_MODIFIED_ASC -> compareBy { it.dateModified } + DATE_MODIFIED_DESC -> compareByDescending { it.dateModified } + } } -/** - * Bottom sheet for sorting wallpapers and folders - */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun SortBottomSheet( @@ -91,7 +99,6 @@ fun SortBottomSheet( ) ) } - // Bottom padding androidx.compose.foundation.layout.Spacer(modifier = Modifier.padding(bottom = 16.dp)) } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt index b696f91..8db95d4 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt @@ -65,14 +65,7 @@ fun FolderViewScreen( var sortOption by rememberSaveable { mutableStateOf(SortOption.DATE_ADDED_DESC) } val sortedWallpapers = remember(wallpapers, sortOption) { - when (sortOption) { - SortOption.NAME_ASC -> wallpapers.sortedBy { it.fileName.lowercase() } - SortOption.NAME_DESC -> wallpapers.sortedByDescending { it.fileName.lowercase() } - SortOption.DATE_ADDED_ASC -> wallpapers.sortedBy { it.addedAt } - SortOption.DATE_ADDED_DESC -> wallpapers.sortedByDescending { it.addedAt } - SortOption.DATE_MODIFIED_ASC -> wallpapers.sortedBy { it.dateModified } - SortOption.DATE_MODIFIED_DESC -> wallpapers.sortedByDescending { it.dateModified } - } + wallpapers.sortedWith(sortOption.wallpaperComparator) } Scaffold( diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt index d299eeb..a71275a 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt @@ -20,12 +20,9 @@ import androidx.compose.material3.Tab import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource @@ -62,21 +59,11 @@ fun HomeScreen( libraryTitle = stringResource(R.string.library) ) - // Persist the initial tab index across navigation - val initialTab = rememberSaveable { mutableIntStateOf(0) } - val pagerState = rememberPagerState(initialTab.intValue) { tabItems.size } - - // Save current tab when it changes - LaunchedEffect(pagerState.currentPage) { - initialTab.intValue = pagerState.currentPage - } - - + val pagerState = rememberPagerState { tabItems.size } Scaffold( topBar = { HomeTopBar( - showSelectionModeAppBar = false, onSettingsClick = onNavigateToSettings ) } @@ -90,7 +77,6 @@ fun HomeScreen( Tab( selected = (index == pagerState.currentPage), onClick = { - // Animate to the selected page when tab is clicked coroutineScope.launch { pagerState.animateScrollToPage(index) } @@ -143,9 +129,7 @@ fun HomeScreen( } } - - // Live Wallpaper Selection Prompt - if (wallpaperMode != null && showLiveWallpaperPrompt && wallpaperMode == WallpaperMode.LIVE) { + if (showLiveWallpaperPrompt && wallpaperMode == WallpaperMode.LIVE) { AlertDialog( onDismissRequest = { viewModel.dismissLiveWallpaperPrompt() }, title = { @@ -171,7 +155,6 @@ fun HomeScreen( onClick = { viewModel.dismissLiveWallpaperPrompt() try { - // Open live wallpaper chooser with Paperize pre-selected val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER).apply { putExtra( WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, @@ -183,12 +166,10 @@ fun HomeScreen( } context.startActivity(intent) } catch (_: Exception) { - // Fallback: Open general wallpaper settings try { val fallbackIntent = Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER) context.startActivity(fallbackIntent) } catch (_: Exception) { - // Last resort: Open wallpaper settings val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS) context.startActivity(settingsIntent) } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt index 03e2599..4107d3b 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt @@ -5,6 +5,7 @@ import android.content.Intent import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import com.anthonyla.paperize.core.WallpaperMode import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.core.util.isPaperizeLiveWallpaperActive @@ -12,7 +13,7 @@ import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.domain.model.ScheduleSettings import com.anthonyla.paperize.domain.repository.SettingsRepository import com.anthonyla.paperize.domain.usecase.CreateAlbumUseCase -import com.anthonyla.paperize.domain.usecase.GetAlbumSummariesUseCase +import com.anthonyla.paperize.domain.repository.AlbumRepository import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService import com.anthonyla.paperize.service.worker.WallpaperScheduler import dagger.hilt.android.lifecycle.HiltViewModel @@ -24,20 +25,21 @@ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import javax.inject.Inject -/** - * ViewModel for Home screen - */ @HiltViewModel class HomeViewModel @Inject constructor( @param:ApplicationContext private val context: Context, - getAlbumSummariesUseCase: GetAlbumSummariesUseCase, + albumRepository: AlbumRepository, private val createAlbumUseCase: CreateAlbumUseCase, private val settingsRepository: SettingsRepository, private val wallpaperScheduler: WallpaperScheduler, @@ -48,12 +50,18 @@ class HomeViewModel @Inject constructor( private const val TAG = "HomeViewModel" } + private val settingsMutex = Mutex() + + // Keep settings writes and their scheduling side effects ordered during rapid UI changes. + private fun launchSettingsUpdate(action: suspend () -> Unit) = viewModelScope.launch { + settingsMutex.withLock { action() } + } + init { - // Check if Paperize live wallpaper was replaced/disabled on startup checkLiveWallpaperStatus() } - val albums: StateFlow> = getAlbumSummariesUseCase() + val albums: StateFlow> = albumRepository.getAlbumSummaries() .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), @@ -64,14 +72,14 @@ class HomeViewModel @Inject constructor( .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), - initialValue = ScheduleSettings.default() + initialValue = ScheduleSettings() ) val appSettings = settingsRepository.getAppSettingsFlow() .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), - initialValue = com.anthonyla.paperize.domain.model.AppSettings.default() + initialValue = com.anthonyla.paperize.domain.model.AppSettings() ) val wallpaperMode = settingsRepository.getWallpaperModeFlow() @@ -88,12 +96,16 @@ class HomeViewModel @Inject constructor( */ @OptIn(ExperimentalCoroutinesApi::class) val currentHomeWallpaperUri: StateFlow = scheduleSettings - .flatMapLatest { settings -> currentWallpaperUriFlow(settings.homeAlbumId, ScreenType.HOME) } + .map { it.homeAlbumId } + .distinctUntilChanged() + .flatMapLatest { albumId -> currentWallpaperUriFlow(albumId, ScreenType.HOME) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), null) @OptIn(ExperimentalCoroutinesApi::class) val currentLockWallpaperUri: StateFlow = scheduleSettings - .flatMapLatest { settings -> currentWallpaperUriFlow(settings.lockAlbumId, ScreenType.LOCK) } + .map { it.lockAlbumId } + .distinctUntilChanged() + .flatMapLatest { albumId -> currentWallpaperUriFlow(albumId, ScreenType.LOCK) } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), null) private fun currentWallpaperUriFlow(albumId: String?, screenType: ScreenType): Flow = @@ -106,7 +118,6 @@ class HomeViewModel @Inject constructor( ) { specific, both -> (specific ?: both)?.uri } } - // Show prompt to select live wallpaper when enabling changer in LIVE mode private val _showLiveWallpaperPrompt = MutableStateFlow(false) val showLiveWallpaperPrompt: StateFlow = _showLiveWallpaperPrompt @@ -114,28 +125,20 @@ class HomeViewModel @Inject constructor( _showLiveWallpaperPrompt.value = false } - /** - * Check if Paperize live wallpaper is still active on app startup. - * If the user was in LIVE mode with an album selected but Paperize is no longer - * the active live wallpaper (e.g., user switched to a different wallpaper), - * clear the live album selection and disable the changer. - */ private fun checkLiveWallpaperStatus() { - viewModelScope.launch { + launchSettingsUpdate { val mode = settingsRepository.getWallpaperMode() val settings = settingsRepository.getScheduleSettings() - - // Only check if we're in LIVE mode and have an album selected - if (mode == com.anthonyla.paperize.core.WallpaperMode.LIVE && - settings.liveAlbumId != null && + + if (mode == WallpaperMode.LIVE && + settings.liveAlbumId != null && settings.enableChanger) { - + val isActive = isPaperizeLiveWallpaperActive(context) Log.d(TAG, "Startup check: LIVE mode with album selected, isPaperizeLiveWallpaperActive=$isActive") - + if (!isActive) { Log.w(TAG, "Paperize live wallpaper was replaced/disabled - clearing live album selection") - // Clear the live album selection and disable changer settingsRepository.updateLiveAlbumId(null) settingsRepository.updateEnableChanger(false) wallpaperScheduler.cancelAllWallpaperChanges() @@ -144,224 +147,56 @@ class HomeViewModel @Inject constructor( } } - fun createAlbum(name: String) { - viewModelScope.launch { - when (val result = createAlbumUseCase(name)) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - Log.e(TAG, "Error creating album", result.exception) - } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } + suspend fun createAlbum(name: String) = createAlbumUseCase(name) + + fun selectHomeAlbum(album: AlbumSummary?) = selectAlbum(album, ScreenType.HOME, settingsRepository::updateHomeAlbumId) + + fun selectLockAlbum(album: AlbumSummary?) = selectAlbum(album, ScreenType.LOCK, settingsRepository::updateLockAlbumId) + + fun selectLiveAlbum(album: AlbumSummary?) = selectAlbum(album, ScreenType.LIVE, settingsRepository::updateLiveAlbumId) + + private fun selectAlbum( + album: AlbumSummary?, + screen: ScreenType, + updateSelection: suspend (String?) -> Unit + ) { + launchSettingsUpdate { + updateSelection(album?.id) + val mode = settingsRepository.getWallpaperMode() + var updated = settingsRepository.getScheduleSettings() + if (album == null && updated.activeScreens(mode).isEmpty()) { + settingsRepository.updateEnableChanger(false) + updated = updated.copy(enableChanger = false) } - } - } - - fun selectHomeAlbum(album: AlbumSummary?) { - viewModelScope.launch { - // Use atomic update to prevent race conditions with selectLockAlbum() - settingsRepository.updateHomeAlbumId(album?.id) - - // Read updated settings after atomic write - val updated = settingsRepository.getScheduleSettings() - - // If unselecting and no albums left, disable changer and cancel alarms - if (album == null && updated.lockAlbumId == null) { - toggleWallpaperChanger(false) - } else if (album != null && updated.enableChanger) { - // Check if we have all required albums before triggering wallpaper change - val homeActive = updated.homeEnabled && updated.homeAlbumId != null - val lockActive = updated.lockEnabled && updated.lockAlbumId != null - val hasRequiredAlbums = when { - updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive - updated.homeEnabled -> homeActive - updated.lockEnabled -> lockActive - else -> false - } - - // Only change wallpaper and schedule if all required albums are selected - if (hasRequiredAlbums) { - // In LIVE mode, don't trigger immediate wallpaper change - the live wallpaper service handles it - // In STATIC mode, trigger immediate change to update the wallpaper - if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) { - val screenType = if ( - updated.homeAlbumId == updated.lockAlbumId && - updated.homeAlbumId != null && - !updated.separateSchedules && - updated.homeEnabled && - updated.lockEnabled - ) { - // Same album for both screens and not separately scheduled - use BOTH - ScreenType.BOTH - } else { - ScreenType.HOME - } - changeWallpaperNow(screenType) - } - scheduleAlarms(updated) - } else { - // Not all required albums selected - cancel any existing schedules - wallpaperScheduler.cancelAllWallpaperChanges() - } - } else if (updated.enableChanger) { - // Album was unselected - check if we still have all required albums - val homeActive = updated.homeEnabled && updated.homeAlbumId != null - val lockActive = updated.lockEnabled && updated.lockAlbumId != null - val hasRequiredAlbums = when { - updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive - updated.homeEnabled -> homeActive - updated.lockEnabled -> lockActive - else -> false - } - - if (hasRequiredAlbums) { - scheduleAlarms(updated) - } else { - wallpaperScheduler.cancelAllWallpaperChanges() - } - } - } - } - - fun selectLockAlbum(album: AlbumSummary?) { - viewModelScope.launch { - // Use atomic update to prevent race conditions with selectHomeAlbum() - settingsRepository.updateLockAlbumId(album?.id) - - // Read updated settings after atomic write - val updated = settingsRepository.getScheduleSettings() - - // If unselecting and no albums left, disable changer and cancel alarms - if (album == null && updated.homeAlbumId == null) { - toggleWallpaperChanger(false) - } else if (album != null && updated.enableChanger) { - // Check if we have all required albums before triggering wallpaper change - val homeActive = updated.homeEnabled && updated.homeAlbumId != null - val lockActive = updated.lockEnabled && updated.lockAlbumId != null - val hasRequiredAlbums = when { - updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive - updated.homeEnabled -> homeActive - updated.lockEnabled -> lockActive - else -> false - } - - // Only change wallpaper and schedule if all required albums are selected - if (hasRequiredAlbums) { - // In LIVE mode, don't trigger immediate wallpaper change - the live wallpaper service handles it - // In STATIC mode, trigger immediate change to update the wallpaper - if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) { - val screenType = if ( - updated.homeAlbumId == updated.lockAlbumId && - updated.lockAlbumId != null && - !updated.separateSchedules && - updated.homeEnabled && - updated.lockEnabled - ) { - // Same album for both screens and not separately scheduled - use BOTH - ScreenType.BOTH - } else { - ScreenType.LOCK - } - changeWallpaperNow(screenType) - } - scheduleAlarms(updated) - } else { - // Not all required albums selected - cancel any existing schedules - wallpaperScheduler.cancelAllWallpaperChanges() - } - } else if (updated.enableChanger) { - // Album was unselected - check if we still have all required albums - val homeActive = updated.homeEnabled && updated.homeAlbumId != null - val lockActive = updated.lockEnabled && updated.lockAlbumId != null - val hasRequiredAlbums = when { - updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive - updated.homeEnabled -> homeActive - updated.lockEnabled -> lockActive - else -> false - } - - if (hasRequiredAlbums) { - scheduleAlarms(updated) - } else { - wallpaperScheduler.cancelAllWallpaperChanges() - } - } - } - } - - fun selectLiveAlbum(album: AlbumSummary?) { - viewModelScope.launch { - settingsRepository.updateLiveAlbumId(album?.id) - - val updated = settingsRepository.getScheduleSettings() - - // If unselecting, disable changer - if (album == null) { - toggleWallpaperChanger(false) - } else if (updated.enableChanger) { - // Album selected and changer is enabled - schedule alarms - scheduleAlarms(updated) + wallpaperScheduler.updateSchedules(updated, mode) + if (album != null && updated.enableChanger && updated.hasRequiredAlbums(mode) && mode == WallpaperMode.STATIC) { + val target = if (ScreenType.BOTH in updated.activeScreens(mode)) ScreenType.BOTH else screen + changeWallpaperNow(target) } } } fun toggleWallpaperChanger(enabled: Boolean, onlyIfNotScheduled: Boolean = false) { - viewModelScope.launch { - // Use atomic update to prevent race conditions with album selection updates + launchSettingsUpdate { settingsRepository.updateEnableChanger(enabled) - - // Read updated settings after atomic write val updated = settingsRepository.getScheduleSettings() - - if (enabled) { - // Check if we have all required albums before changing wallpaper - val homeActive = updated.homeEnabled && updated.homeAlbumId != null - val lockActive = updated.lockEnabled && updated.lockAlbumId != null - val hasRequiredAlbums = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) { - when { - updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive - updated.homeEnabled -> homeActive - updated.lockEnabled -> lockActive - else -> false - } - } else { - updated.liveAlbumId != null + val mode = settingsRepository.getWallpaperMode() + wallpaperScheduler.updateSchedules(updated, mode, onlyIfNotScheduled) + if (enabled && updated.hasRequiredAlbums(mode)) { + if (!onlyIfNotScheduled && mode == WallpaperMode.STATIC) { + updated.activeScreens(mode).forEach(::changeWallpaperNow) } - - // Only change wallpaper and schedule if all required albums are selected - if (hasRequiredAlbums) { - // Only change wallpaper now if this is not a "check if scheduled" call - // In LIVE mode, skip immediate wallpaper changes - the live wallpaper service handles it - if (!onlyIfNotScheduled && wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) { - val isSynced = homeActive && lockActive && - updated.homeAlbumId == updated.lockAlbumId && - !updated.separateSchedules - if (isSynced) { - changeWallpaperNow(ScreenType.BOTH) - } else { - if (homeActive) changeWallpaperNow(ScreenType.HOME) - if (lockActive) changeWallpaperNow(ScreenType.LOCK) - } - } - scheduleAlarms(updated, onlyIfNotScheduled) - - // Show live wallpaper selection prompt if in LIVE mode and Paperize is NOT already active - if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) { - val isActive = isPaperizeLiveWallpaperActive(context) - Log.d(TAG, "toggleWallpaperChanger: LIVE mode, isPaperizeLiveWallpaperActive=$isActive") - if (!isActive) { - _showLiveWallpaperPrompt.value = true - } - } - } else { - // Not all required albums selected - cancel any existing schedules - wallpaperScheduler.cancelAllWallpaperChanges() - } - } else { - wallpaperScheduler.cancelAllWallpaperChanges() + promptForLiveWallpaper(mode) } } } + private fun promptForLiveWallpaper(mode: WallpaperMode) { + if (mode == WallpaperMode.LIVE && !isPaperizeLiveWallpaperActive(context)) { + _showLiveWallpaperPrompt.value = true + } + } + fun updateScheduleSettings(settings: ScheduleSettings) { pendingSettingsJob?.cancel() pendingSettingsJob = null @@ -369,86 +204,33 @@ class HomeViewModel @Inject constructor( } private fun applyScheduleSettings(settings: ScheduleSettings) { - viewModelScope.launch { - // Check if settings have changed before validation - val currentSettings = settingsRepository.getScheduleSettings() - val shuffleChanged = currentSettings.shuffleEnabled != settings.shuffleEnabled - - // Check if screen toggles (homeEnabled/lockEnabled) have changed - val screenToggleChanged = currentSettings.homeEnabled != settings.homeEnabled || - currentSettings.lockEnabled != settings.lockEnabled - - // If a screen was disabled, clear only that screen's album selection. - // Clearing both when only one changes would lose the other screen's selection. - val settingsWithClearedAlbums = if (screenToggleChanged) { + launchSettingsUpdate { + lateinit var currentSettings: ScheduleSettings + val validated = settingsRepository.updateScheduleSettings { current -> + currentSettings = current + // Album selection and pause/resume have their own actions. A delayed effect edit + // must not overwrite changes those actions made after this draft was captured. settings.copy( - homeAlbumId = if (!settings.homeEnabled) null else settings.homeAlbumId, - lockAlbumId = if (!settings.lockEnabled) null else settings.lockAlbumId - ) - } else { - settings + enableChanger = current.enableChanger, + homeAlbumId = if (settings.homeEnabled) current.homeAlbumId else null, + lockAlbumId = if (settings.lockEnabled) current.lockAlbumId else null, + liveAlbumId = current.liveAlbumId + ).validate() } - - val validated = settingsWithClearedAlbums.validate() - - // Check what changed + val shuffleChanged = currentSettings.shuffleEnabled != validated.shuffleEnabled val schedulingChanged = validated.hasSchedulingChanges(currentSettings) val displayChanged = validated.hasDisplayChanges(currentSettings) - settingsRepository.updateScheduleSettings(validated) - - // If shuffle setting changed, clear all queues to force rebuild with new mode if (shuffleChanged) { wallpaperRepository.clearAllQueues() } - val homeActive = validated.homeEnabled && validated.homeAlbumId != null - val lockActive = validated.lockEnabled && validated.lockAlbumId != null - - // Determine if we have the required albums selected - val hasRequiredAlbums = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) { - when { - validated.homeEnabled && validated.lockEnabled -> homeActive && lockActive - validated.homeEnabled -> homeActive - validated.lockEnabled -> lockActive - else -> false - } - } else { - validated.liveAlbumId != null + val mode = settingsRepository.getWallpaperMode() + if (schedulingChanged) { + wallpaperScheduler.updateSchedules(validated, mode) } - - // Handle scheduling changes (interval, screen enable/disable, etc.) - if (validated.enableChanger && hasRequiredAlbums && schedulingChanged) { - scheduleAlarms(validated) - - // Show live wallpaper selection prompt if in LIVE mode, changer was just enabled, and Paperize is NOT already active - if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE && - !currentSettings.enableChanger && validated.enableChanger) { - val isActive = isPaperizeLiveWallpaperActive(context) - Log.d(TAG, "updateScheduleSettings: LIVE mode, changer just enabled, isPaperizeLiveWallpaperActive=$isActive") - if (!isActive) { - _showLiveWallpaperPrompt.value = true - } - } - } else if (validated.enableChanger && !hasRequiredAlbums) { - // Changer enabled but required albums not selected - cancel existing schedules - wallpaperScheduler.cancelAllWallpaperChanges() - } - - // Handle display changes (scaling, effects, adaptive brightness) - // Reapply current wallpaper immediately to show the effect - // In LIVE mode, skip immediate wallpaper changes - the live wallpaper service handles it - if (validated.enableChanger && hasRequiredAlbums && displayChanged && - wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) { - val isSynced = homeActive && lockActive && - validated.homeAlbumId == validated.lockAlbumId && - !validated.separateSchedules - if (isSynced) { - reapplyEffectsNow(ScreenType.BOTH) - } else { - if (homeActive) reapplyEffectsNow(ScreenType.HOME) - if (lockActive) reapplyEffectsNow(ScreenType.LOCK) - } + if (validated.enableChanger && validated.hasRequiredAlbums(mode) && displayChanged && mode == WallpaperMode.STATIC) { + validated.activeScreens(mode).forEach(::reapplyEffectsNow) } } } @@ -479,24 +261,8 @@ class HomeViewModel @Inject constructor( * changed separately. LIVE is routed through the service to reload the renderer. */ fun changeWallpaperNowForActiveScreens() { - val settings = scheduleSettings.value - if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) { - changeWallpaperNow(ScreenType.LIVE) - return - } - - val homeActive = settings.homeEnabled && settings.homeAlbumId != null - val lockActive = settings.lockEnabled && settings.lockAlbumId != null - val synchronized = homeActive && lockActive && - settings.homeAlbumId == settings.lockAlbumId && - !settings.separateSchedules - - if (synchronized) { - changeWallpaperNow(ScreenType.BOTH) - } else { - if (homeActive) changeWallpaperNow(ScreenType.HOME) - if (lockActive) changeWallpaperNow(ScreenType.LOCK) - } + val mode = wallpaperMode.value ?: return + scheduleSettings.value.activeScreens(mode).forEach(::changeWallpaperNow) } fun reapplyEffectsNow(screenType: ScreenType) { @@ -507,72 +273,4 @@ class HomeViewModel @Inject constructor( context.startForegroundService(intent) } - private suspend fun scheduleAlarms(settings: ScheduleSettings, onlyIfNotScheduled: Boolean = false) { - // Check if we're in LIVE mode - if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) { - // LIVE mode: schedule live wallpaper changes - if (settings.liveAlbumId != null && settings.liveIntervalMinutes > 0) { - if (settings.liveIntervalMinutes >= Constants.MIN_INTERVAL_MINUTES) { - wallpaperScheduler.scheduleWallpaperChange( - ScreenType.LIVE, - settings.liveIntervalMinutes - ) - } else { - // The visible live-wallpaper engine owns sub-15-minute intervals. - wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE) - } - wallpaperScheduler.scheduleAlbumRefresh() - } else { - wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE) - wallpaperScheduler.cancelAlbumRefresh() - } - return - } - - // STATIC mode: existing logic - val homeActive = settings.homeEnabled && settings.homeAlbumId != null - val lockActive = settings.lockEnabled && settings.lockAlbumId != null - - // Determine intervals based on active screens and schedule settings - val homeInterval: Int - val lockInterval: Int - - if (settings.homeEnabled && settings.lockEnabled) { - // Both screens enabled - require both albums selected before scheduling - if (homeActive && lockActive) { - if (settings.separateSchedules) { - // Separate intervals for each screen - homeInterval = settings.homeIntervalMinutes - lockInterval = settings.lockIntervalMinutes - } else { - // Same interval for both screens - homeInterval = settings.homeIntervalMinutes - lockInterval = settings.homeIntervalMinutes - } - } else { - // Both enabled but not both selected - don't schedule anything - homeInterval = 0 - lockInterval = 0 - } - } else { - // Only one screen enabled - schedule only if that screen has an album - homeInterval = if (homeActive) settings.homeIntervalMinutes else 0 - lockInterval = if (lockActive) settings.lockIntervalMinutes else 0 - } - - // Determine if screens should be synchronized (same wallpaper) - // This happens when: both enabled, same album, not separate schedules - val shouldSync = settings.homeEnabled && settings.lockEnabled && - settings.homeAlbumId != null && - settings.homeAlbumId == settings.lockAlbumId && - !settings.separateSchedules - - // Schedule using WorkManager (handles cancellation automatically) - wallpaperScheduler.scheduleWallpaperChanges( - homeIntervalMinutes = homeInterval, - lockIntervalMinutes = lockInterval, - synchronized = shouldSync, - onlyIfNotScheduled = onlyIfNotScheduled - ) - } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt index fd13cd0..4798aa5 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt @@ -14,20 +14,17 @@ import com.anthonyla.paperize.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeTopBar( - showSelectionModeAppBar: Boolean, onSettingsClick: () -> Unit ) { - if (!showSelectionModeAppBar) { - CenterAlignedTopAppBar( - title = { Text(stringResource(R.string.app_name)) }, - actions = { - IconButton(onClick = onSettingsClick) { - Icon( - imageVector = Icons.Default.Settings, - contentDescription = stringResource(R.string.settings_screen) - ) - } + CenterAlignedTopAppBar( + title = { Text(stringResource(R.string.app_name)) }, + actions = { + IconButton(onClick = onSettingsClick) { + Icon( + imageVector = Icons.Default.Settings, + contentDescription = stringResource(R.string.settings_screen) + ) } - ) - } + } + ) } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/LibraryScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/LibraryScreen.kt index 4b79097..c0626fd 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/LibraryScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/LibraryScreen.kt @@ -23,6 +23,8 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -30,23 +32,27 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import com.anthonyla.paperize.R +import com.anthonyla.paperize.core.Result +import com.anthonyla.paperize.domain.model.Album import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.presentation.common.components.AddAlbumDialog import com.anthonyla.paperize.presentation.screens.library.components.AlbumItem import com.anthonyla.paperize.presentation.theme.AppGrid import com.anthonyla.paperize.presentation.theme.AppSpacing +import kotlinx.coroutines.launch @Composable fun LibraryScreen( albums: List, onViewAlbum: (String) -> Unit, - onCreateAlbum: (String) -> Unit, + onCreateAlbum: suspend (String) -> Result, modifier: Modifier = Modifier ) { val lazyListState = rememberLazyGridState() var showAddAlbumDialog by rememberSaveable { mutableStateOf(false) } - var albumNameError by rememberSaveable { mutableStateOf(null) } - val albumNameExistsError = stringResource(R.string.album_name_exists_error) + var albumNameError by rememberSaveable { mutableStateOf(null) } + var isSaving by remember { mutableStateOf(false) } + val scope = rememberCoroutineScope() Scaffold( modifier = modifier.fillMaxSize(), @@ -126,17 +132,25 @@ fun LibraryScreen( albumNameError = null }, onConfirm = { name -> - // Check if album with this name already exists - val isDuplicate = albums.any { it.name.equals(name, ignoreCase = true) } - if (isDuplicate) { - albumNameError = albumNameExistsError + if (albums.any { it.name.equals(name, ignoreCase = true) }) { + albumNameError = R.string.album_name_exists_error } else { - onCreateAlbum(name) - showAddAlbumDialog = false + isSaving = true albumNameError = null + scope.launch { + try { + when (onCreateAlbum(name)) { + is Result.Success -> showAddAlbumDialog = false + is Result.Error -> albumNameError = R.string.album_create_failed + } + } finally { + isSaving = false + } + } } }, - errorMessage = albumNameError + errorMessage = albumNameError?.let { stringResource(it) }, + isSaving = isSaving ) } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/components/AlbumItem.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/components/AlbumItem.kt index 41ecc22..518554d 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/components/AlbumItem.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/library/components/AlbumItem.kt @@ -1,10 +1,6 @@ package com.anthonyla.paperize.presentation.screens.library.components -import com.anthonyla.paperize.presentation.theme.AppRadii -import com.anthonyla.paperize.presentation.theme.AppElevation -import com.anthonyla.paperize.presentation.theme.AppShapes -import com.anthonyla.paperize.presentation.theme.AppBorderWidths -import android.content.Context +import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement @@ -23,13 +19,8 @@ import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -38,17 +29,18 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp -import androidx.core.net.toUri -import coil3.compose.AsyncImage +import coil3.compose.AsyncImagePainter +import coil3.compose.rememberAsyncImagePainter import coil3.request.ImageRequest import coil3.size.Size import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.presentation.common.components.InteractiveCard +import com.anthonyla.paperize.presentation.theme.AppBorderWidths +import com.anthonyla.paperize.presentation.theme.AppElevation +import com.anthonyla.paperize.presentation.theme.AppRadii +import com.anthonyla.paperize.presentation.theme.AppShapes import com.anthonyla.paperize.presentation.theme.AppSpacing -/** - * Album item card with cover art display - Enhanced with interactive design - */ @Composable fun AlbumItem( album: AlbumSummary, @@ -56,12 +48,11 @@ fun AlbumItem( modifier: Modifier = Modifier ) { val context = LocalContext.current - var showCoverUri by remember(album.coverUri) { mutableStateOf(false) } - LaunchedEffect(album.coverUri) { - showCoverUri = withContext(Dispatchers.IO) { - !album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri) - } - } + val cover = rememberAsyncImagePainter( + ImageRequest.Builder(context).data(album.coverUri).size(Size(400, 400)).build(), + contentScale = ContentScale.Crop + ) + val coverState by cover.state.collectAsState() InteractiveCard( onClick = onAlbumViewClick, @@ -75,7 +66,6 @@ fun AlbumItem( verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.Start ) { - // Album cover image box with enhanced styling Box( modifier = Modifier .fillMaxWidth() @@ -89,18 +79,14 @@ fun AlbumItem( ), contentAlignment = Alignment.Center ) { - if (showCoverUri) { - AsyncImage( - model = ImageRequest.Builder(context) - .data(album.coverUri!!.toUri()) - .size(Size(400, 400)) // Limit size for performance - .build(), + if (coverState is AsyncImagePainter.State.Success) { + Image( + painter = cover, contentDescription = album.name, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize() ) } else { - // Fallback icon with enhanced styling Icon( imageVector = Icons.Filled.PhotoAlbum, contentDescription = album.name, @@ -112,7 +98,6 @@ fun AlbumItem( Spacer(modifier = Modifier.height(AppSpacing.medium)) - // Album name with enhanced typography Text( text = album.name, style = MaterialTheme.typography.titleMedium, @@ -124,16 +109,3 @@ fun AlbumItem( } } } - -/** - * Check if URI is valid and accessible - */ -private fun isValidUri(context: Context, uriString: String?): Boolean { - if (uriString.isNullOrEmpty()) return false - return try { - val uri = uriString.toUri() - context.contentResolver.openInputStream(uri)?.use { true } ?: false - } catch (_: Exception) { - false - } -} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt index a6c1de0..5201a6c 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt @@ -4,13 +4,10 @@ import com.anthonyla.paperize.presentation.components.OnboardingLayout import com.anthonyla.paperize.core.util.PermissionUtil import android.Manifest -import android.content.pm.PackageManager import android.os.Build import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.* -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Notifications import androidx.compose.material3.* @@ -20,17 +17,10 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.unit.dp -import androidx.core.content.ContextCompat import com.anthonyla.paperize.R -import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.presentation.theme.AppSpacing -/** - * Screen to request notification permission (Android 13+) - * Shows explanation and allows user to grant or skip - */ @Composable fun NotificationPermissionScreen( onContinue: () -> Unit, @@ -67,7 +57,6 @@ fun NotificationPermissionScreen( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(AppSpacing.medium) ) { - // Cleaner explanation card Card( modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.large, @@ -94,7 +83,6 @@ fun NotificationPermissionScreen( } }, actions = { - // Allow button Button( onClick = { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { @@ -119,7 +107,6 @@ fun NotificationPermissionScreen( ) } - // Skip button FilledTonalButton( onClick = onContinue, modifier = Modifier.fillMaxWidth(), diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/privacy/PrivacyScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/privacy/PrivacyScreen.kt index f662d1e..c3d4e19 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/privacy/PrivacyScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/privacy/PrivacyScreen.kt @@ -13,9 +13,6 @@ import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppSpacing -/** - * Privacy policy screen - */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun PrivacyScreen( diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt index c510f64..346baa6 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt @@ -1,5 +1,6 @@ package com.anthonyla.paperize.presentation.screens.settings +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -16,10 +17,9 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext -import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.LifecycleEventEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp @@ -31,9 +31,6 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing import com.anthonyla.paperize.core.util.BatteryOptimizationUtil.isIgnoringBatteryOptimizations import com.anthonyla.paperize.core.util.BatteryOptimizationUtil.requestIgnoreBatteryOptimizations -/** - * Settings screen with Material 3 Expressive design - */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( @@ -43,9 +40,10 @@ fun SettingsScreen( viewModel: SettingsViewModel = hiltViewModel() ) { val appSettings by viewModel.appSettings.collectAsStateWithLifecycle() + val isResetting by viewModel.isResetting.collectAsStateWithLifecycle() + val resetFailed by viewModel.resetFailed.collectAsStateWithLifecycle() val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle() var showResetDialog by remember { mutableStateOf(false) } - var showModeChangeDialog by remember { mutableStateOf(false) } var pendingMode by remember { mutableStateOf(null) } val context = LocalContext.current @@ -53,18 +51,8 @@ fun SettingsScreen( mutableStateOf(isIgnoringBatteryOptimizations(context)) } - // Refresh battery optimization status when returning to the screen - val lifecycleOwner = LocalLifecycleOwner.current - DisposableEffect(lifecycleOwner) { - val observer = LifecycleEventObserver { _, event -> - if (event == Lifecycle.Event.ON_RESUME) { - isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations(context) - } - } - lifecycleOwner.lifecycle.addObserver(observer) - onDispose { - lifecycleOwner.lifecycle.removeObserver(observer) - } + LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { + isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations(context) } Scaffold( @@ -89,9 +77,10 @@ fun SettingsScreen( .verticalScroll(rememberScrollState()) .padding(horizontal = AppSpacing.large) ) { + if (resetFailed) Text(stringResource(R.string.reset_failed), color = MaterialTheme.colorScheme.error) + if (isResetting) LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) Spacer(modifier = Modifier.height(AppSpacing.large)) - // Wallpaper Mode Section SectionHeader( icon = Icons.Filled.Wallpaper, title = stringResource(R.string.wallpaper_mode_setting) @@ -134,12 +123,12 @@ fun SettingsScreen( } FilledTonalButton( + enabled = !isResetting, onClick = { pendingMode = when (wallpaperMode) { com.anthonyla.paperize.core.WallpaperMode.STATIC -> com.anthonyla.paperize.core.WallpaperMode.LIVE com.anthonyla.paperize.core.WallpaperMode.LIVE -> com.anthonyla.paperize.core.WallpaperMode.STATIC } - showModeChangeDialog = true } ) { Text(stringResource(R.string.switch_button)) @@ -158,7 +147,6 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(AppSpacing.extraLarge)) - // Appearance Section SectionHeader( icon = Icons.Filled.Palette, title = stringResource(R.string.appearance) @@ -169,7 +157,7 @@ fun SettingsScreen( SettingSwitchItem( title = stringResource(R.string.dark_mode), description = stringResource(R.string.easier_on_the_eyes), - checked = appSettings?.darkMode ?: false, + checked = appSettings?.darkMode ?: isSystemInDarkTheme(), onCheckedChange = { viewModel.updateDarkMode(it) } ) @@ -193,7 +181,6 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(AppSpacing.extraLarge)) - // Reliability Section SectionHeader( icon = Icons.Default.Build, title = stringResource(R.string.reliability) @@ -271,7 +258,6 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(AppSpacing.extraLarge)) - // About Section SectionHeader( icon = Icons.Filled.Info, title = stringResource(R.string.about) @@ -279,7 +265,6 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(AppSpacing.medium)) - // Privacy Policy Card with enhanced styling Card( onClick = onNavigateToPrivacy, modifier = Modifier.fillMaxWidth(), @@ -312,8 +297,8 @@ fun SettingsScreen( Spacer(modifier = Modifier.height(AppSpacing.large)) - // Reset Data Button with enhanced styling FilledTonalButton( + enabled = !isResetting, onClick = { showResetDialog = true }, modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.filledTonalButtonColors( @@ -353,10 +338,10 @@ fun SettingsScreen( ) } - if (showModeChangeDialog && pendingMode != null) { + if (pendingMode != null) { AlertDialog( onDismissRequest = { - showModeChangeDialog = false + pendingMode = null }, title = { @@ -373,7 +358,7 @@ fun SettingsScreen( TextButton( onClick = { pendingMode?.let { viewModel.switchWallpaperMode(it) } - showModeChangeDialog = false + pendingMode = null }, colors = ButtonDefaults.textButtonColors( @@ -385,7 +370,7 @@ fun SettingsScreen( }, dismissButton = { TextButton(onClick = { - showModeChangeDialog = false + pendingMode = null }) { Text(stringResource(R.string.cancel)) @@ -396,9 +381,6 @@ fun SettingsScreen( } } -/** - * Section header with icon and title for better visual hierarchy - */ @Composable private fun SectionHeader( icon: androidx.compose.ui.graphics.vector.ImageVector, diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt index d51a9cf..9634afa 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt @@ -10,16 +10,15 @@ import com.anthonyla.paperize.domain.repository.AlbumRepository import com.anthonyla.paperize.domain.repository.SettingsRepository import com.anthonyla.paperize.service.worker.WallpaperScheduler import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject -/** - * ViewModel for Settings screen - */ @HiltViewModel class SettingsViewModel @Inject constructor( private val settingsRepository: SettingsRepository, @@ -47,80 +46,63 @@ class SettingsViewModel @Inject constructor( fun updateDarkMode(enabled: Boolean) { viewModelScope.launch { - // Use atomic update to prevent race conditions settingsRepository.updateDarkMode(enabled) } } fun updateDynamicTheming(enabled: Boolean) { viewModelScope.launch { - // Use atomic update to prevent race conditions settingsRepository.updateDynamicTheming(enabled) } } fun updateAnimate(enabled: Boolean) { viewModelScope.launch { - // Use atomic update to prevent race conditions settingsRepository.updateAnimate(enabled) } } fun updateFirstLaunch(isFirstLaunch: Boolean) { viewModelScope.launch { - // Use atomic update to prevent race conditions settingsRepository.updateFirstLaunch(isFirstLaunch) } } - /** - * Switch wallpaper mode and reset all data - * This is required because STATIC and LIVE modes have different capabilities - * and incompatible wallpaper types - */ - fun switchWallpaperMode(newMode: WallpaperMode) { + private val _isResetting = MutableStateFlow(false) + val isResetting = _isResetting.asStateFlow() + private val _resetFailed = MutableStateFlow(false) + val resetFailed = _resetFailed.asStateFlow() + + fun switchWallpaperMode(newMode: WallpaperMode, onSuccess: () -> Unit = {}) = + resetData(newMode, onSuccess) + + fun resetAllData() = resetData(mode = null) + + private fun resetData(mode: WallpaperMode?, onSuccess: () -> Unit = {}) { + if (_isResetting.value) return + _isResetting.value = true + _resetFailed.value = false viewModelScope.launch { - // Cancel all scheduled wallpaper changes first - wallpaperScheduler.cancelAllWallpaperChanges() - - // Delete all albums (cascades to delete all wallpapers, folders, and queues) - when (val result = albumRepository.deleteAllAlbums()) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - Log.e(TAG, "Error deleting albums during mode switch", result.exception) + try { + // Stop both the visible live timer and background jobs before deleting their source. + settingsRepository.updateEnableChanger(false) + wallpaperScheduler.cancelAllWallpaperChanges() + albumRepository.deleteAllAlbums().getOrThrow() + if (mode == null) { + settingsRepository.clearAllSettings() + } else { + settingsRepository.clearScheduleSettings() + settingsRepository.updateWallpaperMode(mode) } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } + onSuccess() + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.e(TAG, "Could not reset app data", e) + _resetFailed.value = true + } finally { + _isResetting.value = false } - - // Reset schedule settings to default (clears effects, intervals, etc.) - settingsRepository.clearScheduleSettings() - - // Set new wallpaper mode - settingsRepository.setWallpaperMode(newMode) - } - } - - /** - * Reset all app data - settings, albums, wallpapers, folders, queues, and alarms - * This completely resets the app to initial state as if just installed - */ - fun resetAllData() { - viewModelScope.launch { - // Cancel all scheduled wallpaper changes first - wallpaperScheduler.cancelAllWallpaperChanges() - - // Delete all albums (cascades to delete all wallpapers, folders, and queues) - when (val result = albumRepository.deleteAllAlbums()) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - Log.e(TAG, "Error deleting albums during reset", result.exception) - } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } - } - - // Clear all settings (DataStore) - resets to default values - // This includes setting firstLaunch back to true for onboarding - settingsRepository.clearAllSettings() } } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortEvent.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortEvent.kt index 86d3573..b8bccc5 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortEvent.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortEvent.kt @@ -1,17 +1,8 @@ package com.anthonyla.paperize.presentation.screens.sort import androidx.compose.foundation.lazy.LazyListItemInfo -import com.anthonyla.paperize.domain.model.Folder -import com.anthonyla.paperize.domain.model.Wallpaper sealed class SortEvent { - data object Reset : SortEvent() - - data class LoadSortView( - val folders: List, - val wallpapers: List - ) : SortEvent() - data class ShiftFolder( val from: LazyListItemInfo, val to: LazyListItemInfo diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortState.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortState.kt index b00ee52..360bdda 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortState.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortState.kt @@ -5,5 +5,9 @@ import com.anthonyla.paperize.domain.model.Wallpaper data class SortState( val folders: List = emptyList(), - val wallpapers: List = emptyList() + val wallpapers: List = emptyList(), + val isLoading: Boolean = true, + val isSaving: Boolean = false, + val saved: Boolean = false, + val error: Int? = null ) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModel.kt index a194bfd..16c2169 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModel.kt @@ -1,45 +1,36 @@ package com.anthonyla.paperize.presentation.screens.sort -import com.anthonyla.paperize.core.constants.Constants import android.util.Log import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.toRoute +import com.anthonyla.paperize.R +import com.anthonyla.paperize.core.util.WallpaperSorter import com.anthonyla.paperize.domain.repository.AlbumRepository -import com.anthonyla.paperize.domain.repository.WallpaperRepository import com.anthonyla.paperize.presentation.common.navigation.SortRoute import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.SharingStarted -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.flow.stateIn -import kotlinx.coroutines.launch import javax.inject.Inject +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch -/** - * ViewModel for the sort view screen to hold the folders and wallpapers - */ @HiltViewModel class SortViewModel @Inject constructor( savedStateHandle: SavedStateHandle, - private val albumRepository: AlbumRepository, - private val wallpaperRepository: WallpaperRepository + private val albumRepository: AlbumRepository ) : ViewModel() { companion object { private const val TAG = "SortViewModel" } - private val sortRoute = savedStateHandle.toRoute() - private val albumId: String = sortRoute.albumId + private val albumId = savedStateHandle.toRoute().albumId private val _state = MutableStateFlow(SortState()) - val state = _state.stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), - initialValue = SortState() - ) + val state = _state.asStateFlow() init { loadAlbumData() @@ -47,65 +38,53 @@ class SortViewModel @Inject constructor( private fun loadAlbumData() { viewModelScope.launch { - val album = albumRepository.getAlbumById(albumId).first() - val wallpapers = wallpaperRepository.getDirectWallpapersByAlbum(albumId).first() - - _state.value = _state.value.copy( - folders = album?.folders ?: emptyList(), - wallpapers = wallpapers - ) + try { + val album = checkNotNull(albumRepository.getAlbumById(albumId).first()) + _state.value = _state.value.copy( + folders = album.folders.sortedBy { it.displayOrder }.map { folder -> + folder.copy(wallpapers = folder.wallpapers.sortedBy { it.displayOrder }) + }, + wallpapers = album.wallpapers.sortedBy { it.displayOrder }, + isLoading = false + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.e(TAG, "Error loading sort data", e) + _state.value = _state.value.copy(error = R.string.sort_load_failed) + } } } + fun dismissError() { _state.value = _state.value.copy(error = null) } + fun saveChanges() { + val snapshot = _state.value + if (snapshot.isLoading || snapshot.isSaving || snapshot.saved) return + _state.value = snapshot.copy(isSaving = true, error = null) viewModelScope.launch { - var hasError = false - - // Update folders with new display orders - _state.value.folders.forEach { folder -> - when (val result = albumRepository.updateFolder(folder)) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - hasError = true - Log.e(TAG, "Error updating folder", result.exception) - } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } - } - } - - // Update wallpapers with new display orders - _state.value.wallpapers.forEach { wallpaper -> - when (val result = wallpaperRepository.updateWallpaper(wallpaper)) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - hasError = true - Log.e(TAG, "Error updating wallpaper", result.exception) - } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } - } - } - - // Clear queues for this album to force rebuild with new sort order - // This ensures the wallpaper changer respects the new order immediately - if (!hasError) { - wallpaperRepository.clearQueuesForAlbum(albumId) + try { + albumRepository.reorderAlbum(albumId, snapshot.folders, snapshot.wallpapers) + .getOrThrow() + _state.value = _state.value.copy(saved = true) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.e(TAG, "Error saving order", e) + _state.value = _state.value.copy(error = R.string.sort_save_failed) + } finally { + _state.value = _state.value.copy(isSaving = false) } } } fun onEvent(event: SortEvent) { + if (_state.value.isLoading || _state.value.isSaving || _state.value.saved) return when (event) { - is SortEvent.LoadSortView -> { - _state.value = _state.value.copy( - folders = event.folders, - wallpapers = event.wallpapers - ) - } - is SortEvent.ShiftFolder -> { val fromUri = event.from.key as? String ?: return val toUri = event.to.key as? String ?: return - val updatedFolders = com.anthonyla.paperize.core.util.WallpaperSorter.shiftFolder( + val updatedFolders = WallpaperSorter.shiftFolder( folders = state.value.folders, fromUri = fromUri, toUri = toUri @@ -116,7 +95,7 @@ class SortViewModel @Inject constructor( is SortEvent.ShiftFolderWallpaper -> { val fromUri = event.from.key as? String ?: return val toUri = event.to.key as? String ?: return - val updatedFolders = com.anthonyla.paperize.core.util.WallpaperSorter.shiftWallpaperInFolder( + val updatedFolders = WallpaperSorter.shiftWallpaperInFolder( folders = state.value.folders, folderId = event.folderId, fromUri = fromUri, @@ -128,7 +107,7 @@ class SortViewModel @Inject constructor( is SortEvent.ShiftWallpaper -> { val fromUri = event.from.key as? String ?: return val toUri = event.to.key as? String ?: return - val updatedWallpapers = com.anthonyla.paperize.core.util.WallpaperSorter.shiftWallpaper( + val updatedWallpapers = WallpaperSorter.shiftWallpaper( wallpapers = state.value.wallpapers, fromUri = fromUri, toUri = toUri @@ -136,12 +115,8 @@ class SortViewModel @Inject constructor( _state.value = _state.value.copy(wallpapers = updatedWallpapers) } - is SortEvent.Reset -> { - _state.value = SortState() - } - is SortEvent.SortAlphabetically -> { - val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllAlphabetically( + val (sortedFolders, sortedWallpapers) = WallpaperSorter.sortAllAlphabetically( folders = state.value.folders, wallpapers = state.value.wallpapers, ascending = true @@ -153,7 +128,7 @@ class SortViewModel @Inject constructor( } is SortEvent.SortAlphabeticallyReverse -> { - val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllAlphabetically( + val (sortedFolders, sortedWallpapers) = WallpaperSorter.sortAllAlphabetically( folders = state.value.folders, wallpapers = state.value.wallpapers, ascending = false @@ -165,7 +140,7 @@ class SortViewModel @Inject constructor( } is SortEvent.SortByLastModified -> { - val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllByDateModified( + val (sortedFolders, sortedWallpapers) = WallpaperSorter.sortAllByDateModified( folders = state.value.folders, wallpapers = state.value.wallpapers, ascending = true @@ -177,7 +152,7 @@ class SortViewModel @Inject constructor( } is SortEvent.SortByLastModifiedReverse -> { - val (sortedFolders, sortedWallpapers) = com.anthonyla.paperize.core.util.WallpaperSorter.sortAllByDateModified( + val (sortedFolders, sortedWallpapers) = WallpaperSorter.sortAllByDateModified( folders = state.value.folders, wallpapers = state.value.wallpapers, ascending = false diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt index 17eebd4..c72c4e1 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt @@ -1,14 +1,8 @@ package com.anthonyla.paperize.presentation.screens.sort -import com.anthonyla.paperize.presentation.theme.AppIconSizes -import android.os.Build -import android.view.HapticFeedbackConstants import androidx.compose.animation.AnimatedContent -import androidx.compose.animation.ExperimentalSharedTransitionApi -import androidx.compose.animation.SharedTransitionLayout import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border -import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row @@ -26,24 +20,28 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Close import androidx.compose.material3.Card -import androidx.compose.material3.CardColors +import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight @@ -55,14 +53,15 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil3.compose.AsyncImage import coil3.request.ImageRequest import coil3.size.Size +import com.anthonyla.paperize.domain.model.Wallpaper import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.screens.sort.components.SortViewTopBar +import com.anthonyla.paperize.presentation.theme.AppIconSizes import com.anthonyla.paperize.presentation.theme.AppShapes import com.anthonyla.paperize.presentation.theme.AppSpacing import sh.calvin.reorderable.ReorderableItem import sh.calvin.reorderable.rememberReorderableLazyListState -@OptIn(ExperimentalSharedTransitionApi::class) @Composable fun SortViewScreen( onSaveClick: () -> Unit, @@ -70,8 +69,19 @@ fun SortViewScreen( modifier: Modifier = Modifier, sortViewModel: SortViewModel = hiltViewModel() ) { - val view = LocalView.current + val haptics = LocalHapticFeedback.current val state by sortViewModel.state.collectAsStateWithLifecycle() + val snackbarHost = remember { SnackbarHostState() } + val errorText = state.error?.let { stringResource(it) } + LaunchedEffect(errorText) { + errorText?.let { + snackbarHost.showSnackbar(it) + sortViewModel.dismissError() + } + } + LaunchedEffect(state.saved) { + if (state.saved) onSaveClick() + } val lazyListState = rememberLazyListState() var expandedFolderId by remember { mutableStateOf(null) } @@ -83,19 +93,8 @@ fun SortViewScreen( } } - val onTopBarSaveClick: () -> Unit = { - sortViewModel.saveChanges() - onSaveClick() - } - - // Logic to determine the title for the top bar val topBarTitle = remember(expandedFolderId, state.folders) { - val currentFolderId = expandedFolderId - if (!currentFolderId.isNullOrEmpty()) { - state.folders.find { it.id == currentFolderId }?.name ?: "" - } else { - "" - } + state.folders.find { it.id == expandedFolderId }?.name.orEmpty() } val reorderableLazyListStateFolder = rememberReorderableLazyListState(lazyListState) { from, to -> @@ -112,12 +111,14 @@ fun SortViewScreen( } Scaffold( + snackbarHost = { SnackbarHost(snackbarHost) }, modifier = modifier.fillMaxSize(), topBar = { SortViewTopBar( title = topBarTitle, + enabled = !state.isLoading && !state.isSaving, onBackClick = onTopBarBackClick, - onSaveClick = onTopBarSaveClick, + onSaveClick = sortViewModel::saveChanges, onSortAlphabetically = { sortViewModel.onEvent(SortEvent.SortAlphabetically) }, onSortAlphabeticallyReverse = { sortViewModel.onEvent(SortEvent.SortAlphabeticallyReverse) }, onSortByLastModified = { sortViewModel.onEvent(SortEvent.SortByLastModified) }, @@ -125,308 +126,158 @@ fun SortViewScreen( ) } ) { paddingValues -> - SharedTransitionLayout(modifier = Modifier.fillMaxSize()) { - AnimatedContent( - modifier = Modifier.fillMaxSize(), - targetState = !expandedFolderId.isNullOrEmpty(), - label = "sort_view_content", - ) { targetState -> - with(this@SharedTransitionLayout) { - if (!targetState) { - LazyColumn( - modifier = Modifier - .fillMaxSize() - .padding(paddingValues), - state = lazyListState, - contentPadding = PaddingValues(AppSpacing.small), - verticalArrangement = Arrangement.spacedBy(AppSpacing.small), - ) { - if (state.folders.isNotEmpty()) { - item { + AnimatedContent( + modifier = Modifier.fillMaxSize(), + targetState = expandedFolderId, + label = "sort_view_content", + ) { targetState -> + if (targetState == null) { + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues), + state = lazyListState, + contentPadding = PaddingValues(AppSpacing.small), + verticalArrangement = Arrangement.spacedBy(AppSpacing.small), + ) { + if (state.folders.isNotEmpty()) { + item { + Text( + text = stringResource(R.string.folders), + modifier = Modifier.padding(AppSpacing.small), + fontWeight = FontWeight.Bold + ) + } + } + items(state.folders, key = { it.uri }) { folder -> + ReorderableItem( + state = reorderableLazyListStateFolder, + key = folder.uri + ) { _ -> + Card( + modifier = Modifier + .fillMaxWidth() + .longPressDraggableHandle( + onDragStarted = { haptics.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate) }, + onDragStopped = { haptics.performHapticFeedback(HapticFeedbackType.GestureEnd) }, + ), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + ), + onClick = { expandedFolderId = folder.id } + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(AppSpacing.large), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { Text( - text = stringResource(R.string.folders), - modifier = Modifier.padding(AppSpacing.small), - fontWeight = FontWeight.Bold + text = folder.displayName, + maxLines = 2, + overflow = TextOverflow.Ellipsis ) - } - } - items(state.folders, key = { it.uri }) { folder -> - ReorderableItem( - state = reorderableLazyListStateFolder, - key = folder.uri - ) { _ -> - val interactionSource = remember { MutableInteractionSource() } - Card( - modifier = Modifier - .fillMaxWidth() - .longPressDraggableHandle( - onDragStarted = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - view.performHapticFeedback( - HapticFeedbackConstants.DRAG_START - ) - } else { - view.performHapticFeedback( - HapticFeedbackConstants.GESTURE_START - ) - } - }, - onDragStopped = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - view.performHapticFeedback( - HapticFeedbackConstants.GESTURE_END - ) - } else { - view.performHapticFeedback( - HapticFeedbackConstants.LONG_PRESS - ) - } - }, - interactionSource = interactionSource, - ), - colors = CardColors( - containerColor = MaterialTheme.colorScheme.secondaryContainer, - contentColor = MaterialTheme.colorScheme.onSecondaryContainer, - disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer, - disabledContentColor = MaterialTheme.colorScheme.onSecondaryContainer, - ), - onClick = { expandedFolderId = folder.id } - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = folder.displayName, - modifier = Modifier.sharedElement( - rememberSharedContentState(folder.name), - animatedVisibilityScope = this@AnimatedContent, - ), - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - IconButton(onClick = { - expandedFolderId = folder.id - }) { - Icon( - Icons.Default.Add, - contentDescription = stringResource(R.string.content_desc_expand) - ) - } - } - } - } - } - if (state.wallpapers.isNotEmpty()) { - item { - Text( - text = stringResource(R.string.wallpapers_sort), - modifier = Modifier.padding(AppSpacing.small), - fontWeight = FontWeight.Bold - ) - } - } - items(state.wallpapers, key = { it.uri }) { wallpaper -> - ReorderableItem( - reorderableLazyListStateWallpaper, - key = wallpaper.uri - ) { _ -> - val interactionSource = remember { MutableInteractionSource() } - Card( - modifier = Modifier - .fillMaxWidth() - .longPressDraggableHandle( - onDragStarted = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - view.performHapticFeedback( - HapticFeedbackConstants.DRAG_START - ) - } else { - view.performHapticFeedback( - HapticFeedbackConstants.GESTURE_START - ) - } - }, - onDragStopped = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - view.performHapticFeedback( - HapticFeedbackConstants.GESTURE_END - ) - } else { - view.performHapticFeedback( - HapticFeedbackConstants.LONG_PRESS - ) - } - }, - interactionSource = interactionSource, - ), - onClick = {}, - colors = CardColors( - containerColor = MaterialTheme.colorScheme.secondaryContainer, - contentColor = MaterialTheme.colorScheme.onSecondaryContainer, - disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer, - disabledContentColor = MaterialTheme.colorScheme.onSecondaryContainer, - ), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - modifier = Modifier.padding(AppSpacing.large) - ) { - Text( - text = wallpaper.displayFileName, - modifier = Modifier.weight(1f), - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Spacer(modifier = Modifier.width(AppSpacing.small)) - AsyncImage( - model = ImageRequest.Builder(LocalContext.current) - .data(wallpaper.uri.toUri()) - .size(Size(100, 100)) - .build(), - contentDescription = wallpaper.displayFileName, - contentScale = ContentScale.Crop, - modifier = Modifier - .size(AppIconSizes.large) - .border( - BorderStroke( - 1.dp, - MaterialTheme.colorScheme.onSecondaryContainer - ), CircleShape - ) - .clip(CircleShape) - ) - } + IconButton(onClick = { + expandedFolderId = folder.id + }) { + Icon( + Icons.Default.Add, + contentDescription = stringResource(R.string.content_desc_expand) + ) } } } } - } else { - LazyColumn( - modifier = Modifier - .fillMaxSize() - .padding(paddingValues), - state = folderWallpapersListState, - contentPadding = PaddingValues(AppSpacing.small), - verticalArrangement = Arrangement.spacedBy(AppSpacing.small), - ) { - val currentFolder = state.folders.find { it.id == expandedFolderId } - if (currentFolder != null) { - item { - ListItem( - modifier = Modifier.fillMaxWidth(), - leadingContent = { - AsyncImage( - model = ImageRequest.Builder(LocalContext.current) - .data(currentFolder.coverUri?.toUri()) - .size(Size(100, 100)) - .build(), - contentDescription = currentFolder.name, - contentScale = ContentScale.Crop, - modifier = Modifier - .size(AppIconSizes.large) - .clip(AppShapes.imageShape) - ) - }, - content = { - Text( - text = currentFolder.name, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - }, - supportingContent = { - Text(text = pluralStringResource(R.plurals.wallpaper_count, currentFolder.wallpapers.size, currentFolder.wallpapers.size)) - }, - trailingContent = { - IconButton(onClick = { expandedFolderId = null }) { - Icon( - Icons.Default.Close, - contentDescription = stringResource(R.string.close) - ) - } - } + } + if (state.wallpapers.isNotEmpty()) { + item { + Text( + text = stringResource(R.string.wallpapers_sort), + modifier = Modifier.padding(AppSpacing.small), + fontWeight = FontWeight.Bold + ) + } + } + items(state.wallpapers, key = { it.uri }) { wallpaper -> + ReorderableItem( + reorderableLazyListStateWallpaper, + key = wallpaper.uri + ) { _ -> + WallpaperSortCard( + wallpaper = wallpaper, + modifier = Modifier + .fillMaxWidth() + .longPressDraggableHandle( + onDragStarted = { haptics.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate) }, + onDragStopped = { haptics.performHapticFeedback(HapticFeedbackType.GestureEnd) }, + ), + ) + } + } + } + } else { + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues), + state = folderWallpapersListState, + contentPadding = PaddingValues(AppSpacing.small), + verticalArrangement = Arrangement.spacedBy(AppSpacing.small), + ) { + val currentFolder = state.folders.find { it.id == targetState } + if (currentFolder != null) { + item { + ListItem( + modifier = Modifier.fillMaxWidth(), + leadingContent = { + AsyncImage( + model = ImageRequest.Builder(LocalContext.current) + .data(currentFolder.coverUri?.toUri()) + .size(Size(100, 100)) + .build(), + contentDescription = currentFolder.name, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(AppIconSizes.large) + .clip(AppShapes.imageShape) ) - } - items(currentFolder.wallpapers, key = { it.uri }) { wallpaper -> - ReorderableItem( - reorderableFolderWallpapersState, - key = wallpaper.uri - ) { _ -> - val interactionSource = remember { MutableInteractionSource() } - Card( - modifier = Modifier - .fillMaxWidth() - .longPressDraggableHandle( - onDragStarted = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - view.performHapticFeedback( - HapticFeedbackConstants.DRAG_START - ) - } else { - view.performHapticFeedback( - HapticFeedbackConstants.GESTURE_START - ) - } - }, - onDragStopped = { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - view.performHapticFeedback( - HapticFeedbackConstants.GESTURE_END - ) - } else { - view.performHapticFeedback( - HapticFeedbackConstants.LONG_PRESS - ) - } - }, - interactionSource = interactionSource, - ), - onClick = {}, - colors = CardColors( - containerColor = MaterialTheme.colorScheme.secondaryContainer, - contentColor = MaterialTheme.colorScheme.onSecondaryContainer, - disabledContainerColor = MaterialTheme.colorScheme.secondaryContainer, - disabledContentColor = MaterialTheme.colorScheme.onSecondaryContainer, - ), - ) { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween, - modifier = Modifier.padding(AppSpacing.large) - ) { - Text( - text = wallpaper.displayFileName, - modifier = Modifier.weight(1f), - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Spacer(modifier = Modifier.width(AppSpacing.small)) - AsyncImage( - model = ImageRequest.Builder(LocalContext.current) - .data(wallpaper.uri.toUri()) - .size(Size(100, 100)) - .build(), - contentDescription = wallpaper.displayFileName, - contentScale = ContentScale.Crop, - modifier = Modifier - .size(AppIconSizes.large) - .clip(CircleShape) - .border( - BorderStroke( - 1.dp, - MaterialTheme.colorScheme.onSecondaryContainer - ), CircleShape - ) - ) - } - } + }, + content = { + Text( + text = currentFolder.name, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + }, + supportingContent = { + Text(text = pluralStringResource(R.plurals.wallpaper_count, currentFolder.wallpapers.size, currentFolder.wallpapers.size)) + }, + trailingContent = { + IconButton(onClick = { expandedFolderId = null }) { + Icon( + Icons.Default.Close, + contentDescription = stringResource(R.string.close) + ) } } + ) + } + items(currentFolder.wallpapers, key = { it.uri }) { wallpaper -> + ReorderableItem( + reorderableFolderWallpapersState, + key = wallpaper.uri + ) { _ -> + WallpaperSortCard( + wallpaper = wallpaper, + modifier = Modifier + .fillMaxWidth() + .longPressDraggableHandle( + onDragStarted = { haptics.performHapticFeedback(HapticFeedbackType.GestureThresholdActivate) }, + onDragStopped = { haptics.performHapticFeedback(HapticFeedbackType.GestureEnd) }, + ), + ) } } } @@ -435,3 +286,38 @@ fun SortViewScreen( } } } + +@Composable +private fun WallpaperSortCard(wallpaper: Wallpaper, modifier: Modifier = Modifier) { + Card( + modifier = modifier, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer + ) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(AppSpacing.large) + ) { + Text( + text = wallpaper.displayFileName, + modifier = Modifier.weight(1f), + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Spacer(Modifier.width(AppSpacing.small)) + AsyncImage( + model = ImageRequest.Builder(LocalContext.current) + .data(wallpaper.uri) + .size(Size(100, 100)) + .build(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.size(AppIconSizes.large) + .border(BorderStroke(1.dp, MaterialTheme.colorScheme.onSecondaryContainer), CircleShape) + .clip(CircleShape) + ) + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/components/SortViewTopBar.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/components/SortViewTopBar.kt index 5fa4b18..24b93e0 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/components/SortViewTopBar.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/components/SortViewTopBar.kt @@ -29,13 +29,11 @@ import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppSpacing -/** - * Top bar for the sort view screen - */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun SortViewTopBar( title: String, + enabled: Boolean = true, onBackClick: () -> Unit, onSaveClick: () -> Unit, onSortAlphabetically: () -> Unit, @@ -64,6 +62,7 @@ fun SortViewTopBar( actions = { Row { IconButton( + enabled = enabled, onClick = { showSortMenu = true }, modifier = Modifier .padding(AppSpacing.large) @@ -113,6 +112,7 @@ fun SortViewTopBar( } } IconButton( + enabled = enabled, onClick = onSaveClick, modifier = Modifier .padding(AppSpacing.large) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/startup/StartupScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/startup/StartupScreen.kt index 9cd63c8..ade0e1a 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/startup/StartupScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/startup/StartupScreen.kt @@ -1,12 +1,10 @@ package com.anthonyla.paperize.presentation.screens.startup -import android.graphics.Canvas -import androidx.core.graphics.createBitmap +import androidx.core.graphics.drawable.toBitmap import androidx.appcompat.content.res.AppCompatResources import com.anthonyla.paperize.presentation.components.OnboardingLayout import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Column @@ -36,10 +34,6 @@ import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppSpacing -/** - * Startup screen shown on first launch - Enhanced with Material 3 Expressive design - * Displays privacy policy and asks for agreement - */ @Composable fun StartupScreen( onAgree: () -> Unit, @@ -47,18 +41,12 @@ fun StartupScreen( modifier: Modifier = Modifier ) { val context = LocalContext.current - val appIcon = remember { - val drawable = AppCompatResources.getDrawable(context, R.mipmap.ic_launcher_round) - if (drawable != null) { - val size = 192 // Use a fixed high resolution size - val bitmap = createBitmap(size, size) - val canvas = Canvas(bitmap) - drawable.setBounds(0, 0, size, size) - drawable.draw(canvas) - bitmap.asImageBitmap() - } else null + val appIcon = remember(context) { + AppCompatResources.getDrawable(context, R.mipmap.ic_launcher_round) + ?.toBitmap(width = 192, height = 192) + ?.asImageBitmap() } - + OnboardingLayout( title = stringResource(R.string.app_name), modifier = modifier, @@ -86,11 +74,9 @@ fun StartupScreen( Spacer(modifier = Modifier.height(AppSpacing.small)) - // Cleaner privacy notice Card( - modifier = Modifier - .fillMaxWidth() - .clickable { onPrivacyClick() }, + onClick = onPrivacyClick, + modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.large, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt index 30d9ad7..e7bb16b 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt @@ -1,5 +1,4 @@ package com.anthonyla.paperize.presentation.screens.wallpaper -import com.anthonyla.paperize.core.constants.Constants import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -24,14 +23,11 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SegmentedButton import androidx.compose.material3.SegmentedButtonDefaults import androidx.compose.material3.SingleChoiceSegmentedButtonRow -import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable @@ -41,22 +37,23 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow +import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.R import com.anthonyla.paperize.core.ScalingType import com.anthonyla.paperize.core.WallpaperMode import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.domain.model.AppSettings +import com.anthonyla.paperize.domain.model.WallpaperEffects import com.anthonyla.paperize.domain.model.ScheduleSettings import com.anthonyla.paperize.presentation.common.components.SettingSwitchItem import com.anthonyla.paperize.presentation.screens.wallpaper.components.AlbumSelectionBottomSheet import com.anthonyla.paperize.presentation.screens.wallpaper.components.CurrentWallpaperPreview -import com.anthonyla.paperize.presentation.screens.wallpaper.components.SettingSwitch import com.anthonyla.paperize.presentation.screens.wallpaper.components.SettingSwitchWithSlider import com.anthonyla.paperize.presentation.screens.wallpaper.components.TimeIntervalPicker import com.anthonyla.paperize.presentation.theme.AppSpacing -enum class AlbumSelectionContext { - HOME, LOCK, BOTH, LIVE +private enum class AlbumSelectionContext { + HOME, LOCK, LIVE } @Composable @@ -76,8 +73,7 @@ fun WallpaperScreen( lockWallpaperUri: String?, modifier: Modifier = Modifier ) { - var showAlbumSelectionSheet by rememberSaveable { mutableStateOf(false) } - var albumSelectionContext by rememberSaveable { mutableStateOf(AlbumSelectionContext.BOTH) } + var albumSelectionContext by rememberSaveable { mutableStateOf(null) } var showEmptyAlbumWarning by rememberSaveable { mutableStateOf(false) } var scheduleSettings by remember { mutableStateOf(persistedScheduleSettings) } @@ -100,41 +96,36 @@ fun WallpaperScreen( val homeEnabled = scheduleSettings.homeEnabled val lockEnabled = scheduleSettings.lockEnabled - // Get currently selected albums by ID - val homeAlbum by remember(albums, scheduleSettings.homeAlbumId) { - derivedStateOf { - scheduleSettings.homeAlbumId?.let { id -> albums.find { it.id == id } } - } + val primaryEffects = when { + wallpaperMode == WallpaperMode.LIVE -> scheduleSettings.liveEffects + homeEnabled -> scheduleSettings.homeEffects + else -> scheduleSettings.lockEffects } - val lockAlbum by remember(albums, scheduleSettings.lockAlbumId) { - derivedStateOf { - scheduleSettings.lockAlbumId?.let { id -> albums.find { it.id == id } } - } - } - val liveAlbum by remember(albums, scheduleSettings.liveAlbumId) { - derivedStateOf { - scheduleSettings.liveAlbumId?.let { id -> albums.find { it.id == id } } + val bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled + + fun updateEffects( + home: (WallpaperEffects) -> WallpaperEffects, + lock: (WallpaperEffects) -> WallpaperEffects = home, + debounced: Boolean = false + ) { + val updated = if (wallpaperMode == WallpaperMode.LIVE) { + scheduleSettings.copy(liveEffects = home(scheduleSettings.liveEffects)) + } else { + scheduleSettings.copy( + homeEffects = if (homeEnabled) home(scheduleSettings.homeEffects) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) lock(scheduleSettings.lockEffects) else scheduleSettings.lockEffects + ) } + if (debounced) updateSettingsDebounced(updated) else updateSettingsImmediate(updated) } val scalingOptions = listOf( - stringResource(R.string.fill), - stringResource(R.string.fit), - stringResource(R.string.stretch), - stringResource(R.string.none) + ScalingType.FILL to stringResource(R.string.fill), + ScalingType.FIT to stringResource(R.string.fit), + ScalingType.STRETCH to stringResource(R.string.stretch), + ScalingType.NONE to stringResource(R.string.none) ) - - val scalingTypeFromSettings = if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType - var selectedScalingIndex by remember(scalingTypeFromSettings) { - mutableIntStateOf( - when (scalingTypeFromSettings) { - ScalingType.FILL -> 0 - ScalingType.FIT -> 1 - ScalingType.STRETCH -> 2 - ScalingType.NONE -> 3 - } - ) - } + val selectedScaling = if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType Column( modifier = modifier @@ -143,318 +134,39 @@ fun WallpaperScreen( .padding(start = AppSpacing.small, end = AppSpacing.small, bottom = AppSpacing.small), verticalArrangement = Arrangement.spacedBy(AppSpacing.small) ) { - // Home and Lock Screen Toggles - Enhanced with better styling - // Only show in Static Mode if (wallpaperMode == WallpaperMode.STATIC) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall), + modifier = Modifier.fillMaxWidth().padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall), horizontalArrangement = Arrangement.spacedBy(AppSpacing.small) ) { - Card( - modifier = Modifier.weight(1f), - onClick = { - updateSettingsImmediate(scheduleSettings.copy(lockEnabled = !lockEnabled)) - }, - shape = MaterialTheme.shapes.large, - colors = CardDefaults.cardColors( - containerColor = if (lockEnabled) - MaterialTheme.colorScheme.primaryContainer - else - MaterialTheme.colorScheme.surfaceContainerHigh - ) - ) { - Column( - modifier = Modifier.padding(AppSpacing.large), - verticalArrangement = Arrangement.spacedBy(AppSpacing.small) - ) { - Icon( - Icons.Default.Lock, - contentDescription = null, - tint = if (lockEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - text = stringResource(R.string.lock), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = if (lockEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - Text( - text = if (lockEnabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), - style = MaterialTheme.typography.bodySmall, - color = if (lockEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - } - - Card( - modifier = Modifier.weight(1f), - onClick = { - updateSettingsImmediate(scheduleSettings.copy(homeEnabled = !homeEnabled)) - }, - shape = MaterialTheme.shapes.large, - colors = CardDefaults.cardColors( - containerColor = if (homeEnabled) - MaterialTheme.colorScheme.primaryContainer - else - MaterialTheme.colorScheme.surfaceContainerHigh - ) - ) { - Column( - modifier = Modifier.padding(AppSpacing.large), - verticalArrangement = Arrangement.spacedBy(AppSpacing.small) - ) { - Icon( - Icons.Default.Home, - contentDescription = null, - tint = if (homeEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - text = stringResource(R.string.home), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = if (homeEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - Text( - text = if (homeEnabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), - style = MaterialTheme.typography.bodySmall, - color = if (homeEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - } + ScreenToggleCard( + title = stringResource(R.string.lock), icon = Icons.Default.Lock, enabled = lockEnabled, + onClick = { updateSettingsImmediate(scheduleSettings.copy(lockEnabled = !lockEnabled)) }, + modifier = Modifier.weight(1f) + ) + ScreenToggleCard( + title = stringResource(R.string.home), icon = Icons.Default.Home, enabled = homeEnabled, + onClick = { updateSettingsImmediate(scheduleSettings.copy(homeEnabled = !homeEnabled)) }, + modifier = Modifier.weight(1f) + ) } + if (lockEnabled) AlbumSelector( + albumId = scheduleSettings.lockAlbumId, albums = albums, + label = stringResource(R.string.lock_album_label), + onClick = { albumSelectionContext = AlbumSelectionContext.LOCK } + ) + if (homeEnabled) AlbumSelector( + albumId = scheduleSettings.homeAlbumId, albums = albums, + label = stringResource(R.string.home_album_label), + onClick = { albumSelectionContext = AlbumSelectionContext.HOME } + ) + } else { + AlbumSelector( + albumId = scheduleSettings.liveAlbumId, albums = albums, + label = stringResource(R.string.currently_selected_album), + onClick = { albumSelectionContext = AlbumSelectionContext.LIVE } + ) } - - // Album Selection - Enhanced with better card styling - // Only show album selection when at least one screen is enabled - if (wallpaperMode == WallpaperMode.STATIC && (homeEnabled || lockEnabled)) { - if (homeEnabled && lockEnabled) { - // Lock Screen Album - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small), - onClick = { - albumSelectionContext = AlbumSelectionContext.LOCK - showAlbumSelectionSheet = true - }, - shape = MaterialTheme.shapes.medium, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ) - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = lockAlbum?.name ?: if (scheduleSettings.lockAlbumId != null) { - stringResource(R.string.loading_placeholder) - } else { - stringResource(R.string.no_album_selected) - }, - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Text( - text = stringResource(R.string.lock_album_label), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary - ) - } - } - - // Home Screen Album - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small), - onClick = { - albumSelectionContext = AlbumSelectionContext.HOME - showAlbumSelectionSheet = true - }, - shape = MaterialTheme.shapes.medium, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ) - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = homeAlbum?.name ?: if (scheduleSettings.homeAlbumId != null) { - stringResource(R.string.loading_placeholder) - } else { - stringResource(R.string.no_album_selected) - }, - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Text( - text = stringResource(R.string.home_album_label), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary - ) - } - } - } else { - // Single album selector when only one screen enabled - Surface( - color = MaterialTheme.colorScheme.surfaceContainerLow, - shape = MaterialTheme.shapes.medium, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small), - onClick = { - albumSelectionContext = AlbumSelectionContext.BOTH - showAlbumSelectionSheet = true - } - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween - ) { - Column(modifier = Modifier.weight(1f)) { - val currentAlbum = if (homeEnabled) homeAlbum else lockAlbum - val currentAlbumId = if (homeEnabled) scheduleSettings.homeAlbumId else scheduleSettings.lockAlbumId - Text( - text = currentAlbum?.name ?: if (currentAlbumId != null) { - stringResource(R.string.loading_placeholder) - } else { - stringResource(R.string.no_album_selected) - }, - style = MaterialTheme.typography.titleMedium, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Text( - text = when { - homeEnabled && !lockEnabled -> stringResource(R.string.home) + stringResource(R.string.album_suffix) - !homeEnabled && lockEnabled -> stringResource(R.string.lock) + stringResource(R.string.album_suffix) - else -> stringResource(R.string.currently_selected_album) - }, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - } - } else if (wallpaperMode == WallpaperMode.LIVE) { - // Live Mode: Single Album Selector - Surface( - color = MaterialTheme.colorScheme.surfaceContainerLow, - shape = MaterialTheme.shapes.medium, - modifier = Modifier - .fillMaxWidth() - .padding(top = AppSpacing.small, start = AppSpacing.small, end = AppSpacing.small), - onClick = { - albumSelectionContext = AlbumSelectionContext.LIVE - showAlbumSelectionSheet = true - } - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = liveAlbum?.name ?: if (scheduleSettings.liveAlbumId != null) { - stringResource(R.string.loading_placeholder) - } else { - stringResource(R.string.no_album_selected) - }, - style = MaterialTheme.typography.titleMedium, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Text( - text = stringResource(R.string.currently_selected_album), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - } - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) - } - } - } - - // Individual scheduling (only show if both screens enabled and changer is enabled) if (wallpaperMode == WallpaperMode.STATIC && scheduleSettings.enableChanger && homeEnabled && lockEnabled) { SettingSwitchItem( title = stringResource(R.string.individual_scheduling), @@ -466,25 +178,8 @@ fun WallpaperScreen( ) } - // Check if an album is selected (at least one screen enabled with album ID set) - val hasAlbumSelected = if (wallpaperMode == WallpaperMode.STATIC) { - (homeEnabled && scheduleSettings.homeAlbumId != null) || - (lockEnabled && scheduleSettings.lockAlbumId != null) - } else { - scheduleSettings.liveAlbumId != null - } - - val allRequiredAlbumsSelected = if (wallpaperMode == WallpaperMode.STATIC) { - when { - homeEnabled && lockEnabled -> - scheduleSettings.homeAlbumId != null && scheduleSettings.lockAlbumId != null - homeEnabled -> scheduleSettings.homeAlbumId != null - lockEnabled -> scheduleSettings.lockAlbumId != null - else -> false - } - } else { - scheduleSettings.liveAlbumId != null - } + val hasAlbumSelected = scheduleSettings.activeScreens(wallpaperMode).isNotEmpty() + val allRequiredAlbumsSelected = scheduleSettings.hasRequiredAlbums(wallpaperMode) if (allRequiredAlbumsSelected) { SettingSwitchItem( @@ -494,8 +189,6 @@ fun WallpaperScreen( onCheckedChange = onToggleChanger ) } - - // Time interval pickers (only show if album is selected) if (hasAlbumSelected) { if (wallpaperMode == WallpaperMode.STATIC) { if (!scheduleSettings.separateSchedules || !homeEnabled || !lockEnabled) { @@ -512,39 +205,32 @@ fun WallpaperScreen( } ) } else { - // Lock screen interval picker first (when individual scheduling is enabled) - if (lockEnabled) { - TimeIntervalPicker( - title = stringResource(R.string.lock_screen_btn), - minutes = scheduleSettings.lockIntervalMinutes, - onMinutesChange = { minutes -> - onUpdateScheduleSettings( - scheduleSettings.copy(lockIntervalMinutes = minutes) - ) - } - ) - } - // Home screen interval picker second - if (homeEnabled) { - TimeIntervalPicker( - title = stringResource(R.string.home_screen_btn), - minutes = scheduleSettings.homeIntervalMinutes, - onMinutesChange = { minutes -> - onUpdateScheduleSettings( - scheduleSettings.copy(homeIntervalMinutes = minutes) - ) - } - ) - } + TimeIntervalPicker( + title = stringResource(R.string.lock_screen_btn), + minutes = scheduleSettings.lockIntervalMinutes, + onMinutesChange = { minutes -> + updateSettingsImmediate( + scheduleSettings.copy(lockIntervalMinutes = minutes) + ) + } + ) + TimeIntervalPicker( + title = stringResource(R.string.home_screen_btn), + minutes = scheduleSettings.homeIntervalMinutes, + onMinutesChange = { minutes -> + updateSettingsImmediate( + scheduleSettings.copy(homeIntervalMinutes = minutes) + ) + } + ) } } else { - // Live Mode: Single Interval Picker TimeIntervalPicker( title = stringResource(R.string.interval_text), minutes = scheduleSettings.liveIntervalMinutes, minimumMinutes = Constants.MIN_LIVE_INTERVAL_MINUTES, onMinutesChange = { minutes -> - onUpdateScheduleSettings( + updateSettingsImmediate( scheduleSettings.copy(liveIntervalMinutes = minutes) ) } @@ -559,8 +245,6 @@ fun WallpaperScreen( } HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small)) - - // Current Wallpaper Preview (Static Mode Only) if (wallpaperMode == WallpaperMode.STATIC) { SettingSwitchItem( title = stringResource(R.string.horizontal_wallpaper_scrolling), @@ -582,8 +266,6 @@ fun WallpaperScreen( ) HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small)) } - - // Effects Section Header Text( text = stringResource(R.string.wallpaper_effects_title), style = MaterialTheme.typography.titleLarge, @@ -592,8 +274,6 @@ fun WallpaperScreen( maxLines = 2, overflow = TextOverflow.Ellipsis ) - - // Scaling Options Card Card( shape = MaterialTheme.shapes.medium, colors = CardDefaults.cardColors( @@ -615,21 +295,14 @@ fun WallpaperScreen( overflow = TextOverflow.Ellipsis ) SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { - scalingOptions.forEachIndexed { index, label -> + scalingOptions.forEachIndexed { index, (scalingType, label) -> SegmentedButton( shape = SegmentedButtonDefaults.itemShape( index = index, count = scalingOptions.size ), onClick = { - selectedScalingIndex = index - val scalingType = when (index) { - 0 -> ScalingType.FILL - 1 -> ScalingType.FIT - 2 -> ScalingType.STRETCH - else -> ScalingType.NONE - } - onUpdateScheduleSettings( + updateSettingsImmediate( if (wallpaperMode == WallpaperMode.LIVE) { scheduleSettings.copy(liveScalingType = scalingType) } else { @@ -640,7 +313,7 @@ fun WallpaperScreen( } ) }, - selected = index == selectedScalingIndex + selected = scalingType == selectedScaling ) { Text( text = label, @@ -668,33 +341,15 @@ fun WallpaperScreen( Text(text = stringResource(R.string.change_wallpaper_now)) } } - - // Shuffle Card - Card( - shape = MaterialTheme.shapes.medium, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ), - modifier = Modifier - .fillMaxWidth() - .padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)) - ) { - Column( - modifier = Modifier.padding(AppSpacing.large), - verticalArrangement = Arrangement.spacedBy(AppSpacing.medium) - ) { - SettingSwitch( - title = R.string.shuffle, - description = if (scheduleSettings.shuffleEnabled && !scheduleSettings.separateSchedules) null else R.string.randomly_shuffle_the_wallpapers, - checked = scheduleSettings.shuffleEnabled, - onCheckedChange = { enabled -> - updateSettingsImmediate(scheduleSettings.copy(shuffleEnabled = enabled)) - } - ) + SettingSwitchItem( + title = stringResource(R.string.shuffle), + description = if (scheduleSettings.shuffleEnabled && !scheduleSettings.separateSchedules) null else stringResource(R.string.randomly_shuffle_the_wallpapers), + checked = scheduleSettings.shuffleEnabled, + onCheckedChange = { enabled -> + updateSettingsImmediate(scheduleSettings.copy(shuffleEnabled = enabled)) } - } + ) - // Visual Effects Group Card( shape = MaterialTheme.shapes.medium, colors = CardDefaults.cardColors( @@ -717,306 +372,92 @@ fun WallpaperScreen( overflow = TextOverflow.Ellipsis ) - // Darken/Brightness SettingSwitchWithSlider( title = R.string.change_brightness, description = R.string.change_the_image_brightness, - checked = if (wallpaperMode == WallpaperMode.STATIC) { - when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableDarken && scheduleSettings.lockEffects.enableDarken - homeEnabled -> scheduleSettings.homeEffects.enableDarken - else -> scheduleSettings.lockEffects.enableDarken - } - } else { - scheduleSettings.liveEffects.enableDarken - }, - onCheckedChange = { enabled -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableDarken = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableDarken = enabled) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsImmediate( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(enableDarken = enabled) - ) - ) - } - }, + checked = primaryEffects.enableDarken, + onCheckedChange = { enabled -> updateEffects({ it.copy(enableDarken = enabled) }) }, homeChecked = scheduleSettings.homeEffects.enableDarken, lockChecked = scheduleSettings.lockEffects.enableDarken, onHomeCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = scheduleSettings.homeEffects.copy( - enableDarken = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(homeEffects = scheduleSettings.homeEffects.copy(enableDarken = enabled))) }, onLockCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - lockEffects = scheduleSettings.lockEffects.copy( - enableDarken = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(lockEffects = scheduleSettings.lockEffects.copy(enableDarken = enabled))) }, - bothEnabled = wallpaperMode == WallpaperMode.STATIC && - homeEnabled && lockEnabled, - homePercentage = if (wallpaperMode == WallpaperMode.STATIC) { - if (homeEnabled) scheduleSettings.homeEffects.darkenPercentage - else scheduleSettings.lockEffects.darkenPercentage - } else scheduleSettings.liveEffects.darkenPercentage, + bothEnabled = bothEnabled, + homePercentage = primaryEffects.darkenPercentage, lockPercentage = scheduleSettings.lockEffects.darkenPercentage, - onPercentageChange = { homePercent, lockPercent -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(darkenPercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(darkenPercentage = lockPercent) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsDebounced( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(darkenPercentage = homePercent) - ) - ) - } + onPercentageChange = { home, lock -> + updateEffects({ it.copy(darkenPercentage = home) }, { it.copy(darkenPercentage = lock) }, debounced = true) } ) - // Blur SettingSwitchWithSlider( title = R.string.change_blur, description = R.string.add_blur_to_the_image, - checked = if (wallpaperMode == WallpaperMode.STATIC) { - when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableBlur && scheduleSettings.lockEffects.enableBlur - homeEnabled -> scheduleSettings.homeEffects.enableBlur - else -> scheduleSettings.lockEffects.enableBlur - } - } else { - scheduleSettings.liveEffects.enableBlur - }, - onCheckedChange = { enabled -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableBlur = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableBlur = enabled) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsImmediate( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(enableBlur = enabled) - ) - ) - } - }, + checked = primaryEffects.enableBlur, + onCheckedChange = { enabled -> updateEffects({ it.copy(enableBlur = enabled) }) }, homeChecked = scheduleSettings.homeEffects.enableBlur, lockChecked = scheduleSettings.lockEffects.enableBlur, onHomeCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = scheduleSettings.homeEffects.copy( - enableBlur = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(homeEffects = scheduleSettings.homeEffects.copy(enableBlur = enabled))) }, onLockCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - lockEffects = scheduleSettings.lockEffects.copy( - enableBlur = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(lockEffects = scheduleSettings.lockEffects.copy(enableBlur = enabled))) }, - bothEnabled = wallpaperMode == WallpaperMode.STATIC && - homeEnabled && lockEnabled, - homePercentage = if (wallpaperMode == WallpaperMode.STATIC) { - if (homeEnabled) scheduleSettings.homeEffects.blurPercentage - else scheduleSettings.lockEffects.blurPercentage - } else scheduleSettings.liveEffects.blurPercentage, + bothEnabled = bothEnabled, + homePercentage = primaryEffects.blurPercentage, lockPercentage = scheduleSettings.lockEffects.blurPercentage, - onPercentageChange = { homePercent, lockPercent -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(blurPercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(blurPercentage = lockPercent) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsDebounced( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(blurPercentage = homePercent) - ) - ) - } + onPercentageChange = { home, lock -> + updateEffects({ it.copy(blurPercentage = home) }, { it.copy(blurPercentage = lock) }, debounced = true) } ) - // Vignette SettingSwitchWithSlider( title = R.string.change_vignette, description = R.string.darken_the_edges_of_the_image, - checked = if (wallpaperMode == WallpaperMode.STATIC) { - when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableVignette && scheduleSettings.lockEffects.enableVignette - homeEnabled -> scheduleSettings.homeEffects.enableVignette - else -> scheduleSettings.lockEffects.enableVignette - } - } else { - scheduleSettings.liveEffects.enableVignette - }, - onCheckedChange = { enabled -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableVignette = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableVignette = enabled) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsImmediate( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(enableVignette = enabled) - ) - ) - } - }, + checked = primaryEffects.enableVignette, + onCheckedChange = { enabled -> updateEffects({ it.copy(enableVignette = enabled) }) }, homeChecked = scheduleSettings.homeEffects.enableVignette, lockChecked = scheduleSettings.lockEffects.enableVignette, onHomeCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = scheduleSettings.homeEffects.copy( - enableVignette = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(homeEffects = scheduleSettings.homeEffects.copy(enableVignette = enabled))) }, onLockCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - lockEffects = scheduleSettings.lockEffects.copy( - enableVignette = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(lockEffects = scheduleSettings.lockEffects.copy(enableVignette = enabled))) }, - bothEnabled = wallpaperMode == WallpaperMode.STATIC && - homeEnabled && lockEnabled, - homePercentage = if (wallpaperMode == WallpaperMode.STATIC) { - if (homeEnabled) scheduleSettings.homeEffects.vignettePercentage - else scheduleSettings.lockEffects.vignettePercentage - } else scheduleSettings.liveEffects.vignettePercentage, + bothEnabled = bothEnabled, + homePercentage = primaryEffects.vignettePercentage, lockPercentage = scheduleSettings.lockEffects.vignettePercentage, - onPercentageChange = { homePercent, lockPercent -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(vignettePercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(vignettePercentage = lockPercent) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsDebounced( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(vignettePercentage = homePercent) - ) - ) - } + onPercentageChange = { home, lock -> + updateEffects({ it.copy(vignettePercentage = home) }, { it.copy(vignettePercentage = lock) }, debounced = true) } ) - // Grayscale SettingSwitchWithSlider( title = R.string.gray_filter, description = R.string.make_the_colors_grayscale, - checked = if (wallpaperMode == WallpaperMode.STATIC) { - when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale - homeEnabled -> scheduleSettings.homeEffects.enableGrayscale - else -> scheduleSettings.lockEffects.enableGrayscale - } - } else { - scheduleSettings.liveEffects.enableGrayscale - }, - onCheckedChange = { enabled -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableGrayscale = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableGrayscale = enabled) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsImmediate( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(enableGrayscale = enabled) - ) - ) - } - }, + checked = primaryEffects.enableGrayscale, + onCheckedChange = { enabled -> updateEffects({ it.copy(enableGrayscale = enabled) }) }, homeChecked = scheduleSettings.homeEffects.enableGrayscale, lockChecked = scheduleSettings.lockEffects.enableGrayscale, onHomeCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - homeEffects = scheduleSettings.homeEffects.copy( - enableGrayscale = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(homeEffects = scheduleSettings.homeEffects.copy(enableGrayscale = enabled))) }, onLockCheckedChange = { enabled -> - updateSettingsImmediate( - scheduleSettings.copy( - lockEffects = scheduleSettings.lockEffects.copy( - enableGrayscale = enabled - ) - ) - ) + updateSettingsImmediate(scheduleSettings.copy(lockEffects = scheduleSettings.lockEffects.copy(enableGrayscale = enabled))) }, - bothEnabled = wallpaperMode == WallpaperMode.STATIC && - homeEnabled && lockEnabled, - homePercentage = if (wallpaperMode == WallpaperMode.STATIC) { - if (homeEnabled) scheduleSettings.homeEffects.grayscalePercentage - else scheduleSettings.lockEffects.grayscalePercentage - } else scheduleSettings.liveEffects.grayscalePercentage, + bothEnabled = bothEnabled, + homePercentage = primaryEffects.grayscalePercentage, lockPercentage = scheduleSettings.lockEffects.grayscalePercentage, - onPercentageChange = { homePercent, lockPercent -> - if (wallpaperMode == WallpaperMode.STATIC) { - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(grayscalePercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(grayscalePercentage = lockPercent) else scheduleSettings.lockEffects - ) - ) - } else { - updateSettingsDebounced( - scheduleSettings.copy( - liveEffects = scheduleSettings.liveEffects.copy(grayscalePercentage = homePercent) - ) - ) - } + onPercentageChange = { home, lock -> + updateEffects({ it.copy(grayscalePercentage = home) }, { it.copy(grayscalePercentage = lock) }, debounced = true) } ) - - // Adaptive Brightness - SettingSwitch( - title = R.string.adaptive_brightness, - description = if (scheduleSettings.adaptiveBrightness && !scheduleSettings.separateSchedules) null else R.string.adjust_brightness_based_on_mode, + SettingSwitchItem( + title = stringResource(R.string.adaptive_brightness), + description = if (scheduleSettings.adaptiveBrightness && !scheduleSettings.separateSchedules) null else stringResource(R.string.adjust_brightness_based_on_mode), checked = scheduleSettings.adaptiveBrightness, onCheckedChange = { enabled -> updateSettingsImmediate(scheduleSettings.copy(adaptiveBrightness = enabled)) @@ -1024,8 +465,6 @@ fun WallpaperScreen( ) } } - - // Interactive Effects Group (Live Wallpaper Mode Only) if (wallpaperMode == WallpaperMode.LIVE) { Card( shape = MaterialTheme.shapes.medium, @@ -1048,11 +487,9 @@ fun WallpaperScreen( maxLines = 1, overflow = TextOverflow.Ellipsis ) - - // Double-tap to change wallpaper - SettingSwitch( - title = R.string.double_tap_to_change, - description = if (scheduleSettings.liveEffects.enableDoubleTap) null else R.string.double_tap_wallpaper_to_change_it, + SettingSwitchItem( + title = stringResource(R.string.double_tap_to_change), + description = if (scheduleSettings.liveEffects.enableDoubleTap) null else stringResource(R.string.double_tap_wallpaper_to_change_it), checked = scheduleSettings.liveEffects.enableDoubleTap, onCheckedChange = { enabled -> updateSettingsImmediate( @@ -1062,11 +499,9 @@ fun WallpaperScreen( ) } ) - - // Change wallpaper on screen off - SettingSwitch( - title = R.string.change_on_screen_off, - description = if (scheduleSettings.liveEffects.enableChangeOnScreenOff) null else R.string.change_wallpaper_when_screen_turns_off, + SettingSwitchItem( + title = stringResource(R.string.change_on_screen_off), + description = if (scheduleSettings.liveEffects.enableChangeOnScreenOff) null else stringResource(R.string.change_wallpaper_when_screen_turns_off), checked = scheduleSettings.liveEffects.enableChangeOnScreenOff, onCheckedChange = { enabled -> updateSettingsImmediate( @@ -1076,8 +511,6 @@ fun WallpaperScreen( ) } ) - - // Parallax effect SettingSwitchWithSlider( title = R.string.parallax_effect, description = R.string.wallpaper_moves_with_screen_scroll, @@ -1105,102 +538,28 @@ fun WallpaperScreen( } } - if (showAlbumSelectionSheet) { + albumSelectionContext?.let { selection -> + val selectedId = when (selection) { + AlbumSelectionContext.HOME -> scheduleSettings.homeAlbumId + AlbumSelectionContext.LOCK -> scheduleSettings.lockAlbumId + AlbumSelectionContext.LIVE -> scheduleSettings.liveAlbumId + } + val selectAlbum = when (selection) { + AlbumSelectionContext.HOME -> onSelectHomeAlbum + AlbumSelectionContext.LOCK -> onSelectLockAlbum + AlbumSelectionContext.LIVE -> onSelectLiveAlbum + } AlbumSelectionBottomSheet( albums = albums, - selectedAlbums = when (albumSelectionContext) { - AlbumSelectionContext.LIVE -> { - // Use ID as source of truth - if ID is set, ensure we mark it as selected - scheduleSettings.liveAlbumId?.let { id -> - // Try to find full album, or create stub with ID for selection marking - albums.find { it.id == id }?.let { listOf(it) } - ?: listOf(AlbumSummary.empty(id = id)) - } ?: emptyList() - } - AlbumSelectionContext.HOME -> { - // Use ID as source of truth - if ID is set, ensure we mark it as selected - scheduleSettings.homeAlbumId?.let { id -> - // Try to find full album, or create stub with ID for selection marking - albums.find { it.id == id }?.let { listOf(it) } - ?: listOf(AlbumSummary.empty(id = id)) - } ?: emptyList() - } - AlbumSelectionContext.LOCK -> { - // Use ID as source of truth - if ID is set, ensure we mark it as selected - scheduleSettings.lockAlbumId?.let { id -> - // Try to find full album, or create stub with ID for selection marking - albums.find { it.id == id }?.let { listOf(it) } - ?: listOf(AlbumSummary.empty(id = id)) - } ?: emptyList() - } - AlbumSelectionContext.BOTH -> { - // When only one screen enabled, show that screen's selected album - when { - homeEnabled -> { - scheduleSettings.homeAlbumId?.let { id -> - albums.find { it.id == id }?.let { listOf(it) } - ?: listOf(AlbumSummary.empty(id = id)) - } ?: emptyList() - } - lockEnabled -> { - scheduleSettings.lockAlbumId?.let { id -> - albums.find { it.id == id }?.let { listOf(it) } - ?: listOf(AlbumSummary.empty(id = id)) - } ?: emptyList() - } - else -> emptyList() - } - } - }, + selectedAlbumId = selectedId, onAlbumSelect = { album -> - // Check if album is empty (has 0 wallpapers) - if (album.wallpaperCount == 0) { - showEmptyAlbumWarning = true - } else { - when (albumSelectionContext) { - AlbumSelectionContext.LIVE -> { - // Toggle selection using ID as source of truth - val isCurrentlySelected = scheduleSettings.liveAlbumId == album.id - if (isCurrentlySelected) { - onSelectLiveAlbum(null) - } else { - onSelectLiveAlbum(album) - } - } - AlbumSelectionContext.HOME -> { - // Toggle selection using ID as source of truth - val isCurrentlySelected = scheduleSettings.homeAlbumId == album.id - if (isCurrentlySelected) { - onSelectHomeAlbum(null) - } else { - onSelectHomeAlbum(album) - } - } - AlbumSelectionContext.LOCK -> { - // Toggle selection using ID as source of truth - val isCurrentlySelected = scheduleSettings.lockAlbumId == album.id - if (isCurrentlySelected) { - onSelectLockAlbum(null) - } else { - onSelectLockAlbum(album) - } - } - AlbumSelectionContext.BOTH -> { - // Toggle selection for the enabled screen(s) using IDs as source of truth - val isCurrentlySelected = (homeEnabled && scheduleSettings.homeAlbumId == album.id) || - (lockEnabled && scheduleSettings.lockAlbumId == album.id) - if (isCurrentlySelected) { - if (homeEnabled) onSelectHomeAlbum(null) - if (lockEnabled) onSelectLockAlbum(null) - } else { - if (homeEnabled) onSelectHomeAlbum(album) - if (lockEnabled) onSelectLockAlbum(album) - } - } - } + when { + album.id == selectedId -> selectAlbum(null) + album.wallpaperCount == 0 -> showEmptyAlbumWarning = true + else -> selectAlbum(album) } }, - onDismiss = { showAlbumSelectionSheet = false } + onDismiss = { albumSelectionContext = null } ) } @@ -1233,3 +592,54 @@ fun WallpaperScreen( ) } } + +@Composable +private fun ScreenToggleCard( + title: String, + icon: androidx.compose.ui.graphics.vector.ImageVector, + enabled: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier, + onClick = onClick, + shape = MaterialTheme.shapes.large, + colors = CardDefaults.cardColors( + containerColor = if (enabled) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh + ) + ) { + Column(Modifier.padding(AppSpacing.large), verticalArrangement = Arrangement.spacedBy(AppSpacing.small)) { + val contentColor = if (enabled) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurfaceVariant + Icon(icon, contentDescription = null, tint = contentColor) + Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, + color = if (enabled) contentColor else MaterialTheme.colorScheme.onSurface, + maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(stringResource(if (enabled) R.string.enabled else R.string.disabled), + style = MaterialTheme.typography.bodySmall, color = contentColor, + maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } +} + +@Composable +private fun AlbumSelector(albumId: String?, albums: List, label: String, onClick: () -> Unit) { + val album = albums.find { it.id == albumId } + Card( + modifier = Modifier.fillMaxWidth().padding(horizontal = AppSpacing.small), + onClick = onClick, + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerLow) + ) { + Row(Modifier.fillMaxWidth().padding(AppSpacing.large), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(album?.name ?: stringResource(if (albumId == null) R.string.no_album_selected else R.string.loading_placeholder), + style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, + maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, overflow = TextOverflow.Ellipsis) + } + Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null, tint = MaterialTheme.colorScheme.primary) + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/AlbumSelectionBottomSheet.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/AlbumSelectionBottomSheet.kt index f4120ea..b49992d 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/AlbumSelectionBottomSheet.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/AlbumSelectionBottomSheet.kt @@ -1,9 +1,6 @@ package com.anthonyla.paperize.presentation.screens.wallpaper.components -import com.anthonyla.paperize.presentation.theme.AppIconSizes -import com.anthonyla.paperize.presentation.theme.AppBorderWidths -import com.anthonyla.paperize.core.constants.Constants -import android.content.Context +import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement @@ -32,13 +29,8 @@ import androidx.compose.material3.SheetValue import androidx.compose.material3.Text import androidx.compose.material3.rememberBottomSheetState import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -47,12 +39,15 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow -import androidx.core.net.toUri -import coil3.compose.AsyncImage +import coil3.compose.AsyncImagePainter +import coil3.compose.rememberAsyncImagePainter import coil3.request.ImageRequest import coil3.size.Size import com.anthonyla.paperize.R +import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.domain.model.AlbumSummary +import com.anthonyla.paperize.presentation.theme.AppBorderWidths +import com.anthonyla.paperize.presentation.theme.AppIconSizes import com.anthonyla.paperize.presentation.theme.AppShapes import com.anthonyla.paperize.presentation.theme.AppSpacing @@ -60,7 +55,7 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing @Composable fun AlbumSelectionBottomSheet( albums: List, - selectedAlbums: List, + selectedAlbumId: String?, onAlbumSelect: (AlbumSummary) -> Unit, onDismiss: () -> Unit ) { @@ -85,7 +80,7 @@ fun AlbumSelectionBottomSheet( LazyColumn { items(albums, key = { it.id }) { album -> - val isSelected = selectedAlbums.any { it.id == album.id } + val isSelected = selectedAlbumId == album.id AlbumSelectionItem( album = album, isSelected = isSelected, @@ -121,12 +116,11 @@ private fun AlbumSelectionItem( modifier: Modifier = Modifier ) { val context = LocalContext.current - var showCoverUri by remember(album.coverUri) { mutableStateOf(false) } - LaunchedEffect(album.coverUri) { - showCoverUri = withContext(Dispatchers.IO) { - !album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri) - } - } + val cover = rememberAsyncImagePainter( + ImageRequest.Builder(context).data(album.coverUri).size(Size(Constants.LIST_THUMBNAIL_SIZE, Constants.LIST_THUMBNAIL_SIZE)).build(), + contentScale = ContentScale.Crop + ) + val coverState by cover.state.collectAsState() Row( modifier = modifier @@ -136,7 +130,6 @@ private fun AlbumSelectionItem( horizontalArrangement = Arrangement.Start, verticalAlignment = Alignment.CenterVertically ) { - // Album cover thumbnail Box( modifier = Modifier .size(AppIconSizes.extraLarge) @@ -149,13 +142,10 @@ private fun AlbumSelectionItem( .clip(AppShapes.imageShape), contentAlignment = Alignment.Center ) { - if (showCoverUri) { - AsyncImage( - model = ImageRequest.Builder(context) - .data(album.coverUri!!.toUri()) - .size(Size(Constants.LIST_THUMBNAIL_SIZE, Constants.LIST_THUMBNAIL_SIZE)) // Small thumbnail for list item - .build(), - contentDescription = album.name, + if (coverState is AsyncImagePainter.State.Success) { + Image( + painter = cover, + contentDescription = album.name, contentScale = ContentScale.Crop, modifier = Modifier.size(AppIconSizes.extraLarge) ) @@ -171,7 +161,6 @@ private fun AlbumSelectionItem( Spacer(modifier = Modifier.width(AppSpacing.large)) - // Album info Column(modifier = Modifier.weight(1f)) { Text( text = album.name, @@ -188,7 +177,6 @@ private fun AlbumSelectionItem( ) } - // Selection indicator Icon( imageVector = if (isSelected) Icons.Filled.CheckCircle else Icons.Outlined.Circle, contentDescription = if (isSelected) stringResource(R.string.currently_selected_album) else null, @@ -196,16 +184,3 @@ private fun AlbumSelectionItem( ) } } - -/** - * Check if URI is valid and accessible - */ -private fun isValidUri(context: Context, uriString: String?): Boolean { - if (uriString.isNullOrEmpty()) return false - return try { - val uri = uriString.toUri() - context.contentResolver.openInputStream(uri)?.use { true } ?: false - } catch (_: Exception) { - false - } -} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt index ab17079..f80ac3d 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/CurrentWallpaperPreview.kt @@ -3,10 +3,6 @@ import com.anthonyla.paperize.presentation.theme.AppMaxWidths import com.anthonyla.paperize.presentation.theme.AppBorderWidths import com.anthonyla.paperize.core.constants.Constants -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.core.tween -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement @@ -42,25 +38,15 @@ import coil3.size.Size import kotlin.math.max import kotlin.math.min -/** - * Displays the home and lock wallpapers Paperize last applied. - * - * The images are loaded from the recorded source URIs ([homeWallpaperUri]/[lockWallpaperUri]) via - * Coil, rather than read back from WallpaperManager.getDrawable(): the latter is privacy-restricted - * on modern Android and returns null without the optional all-files-access permission, which left - * the preview blank. The URIs already carry the album's persisted read access, so no extra - * permission is needed. They update reactively whenever Paperize changes the wallpaper. - * - * Note: this shows the source image, not the exact cropped/scaled/effected on-screen result. - * - * Adapts to the device screen aspect ratio and respects the app's animate setting. +/** Shows the last applied source URIs; WallpaperManager readback is restricted on modern Android. + * Cropping and effects applied to the actual wallpaper are not included in this preview. */ @Composable fun CurrentWallpaperPreview( homeWallpaperUri: String?, lockWallpaperUri: String?, - animate: Boolean = true, - modifier: Modifier = Modifier + modifier: Modifier = Modifier, + animate: Boolean = true ) { val configuration = LocalConfiguration.current @@ -99,7 +85,6 @@ fun CurrentWallpaperPreview( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(AppSpacing.medium) ) { - // Lock wallpaper preview (on the left) WallpaperPreviewBox( wallpaperUri = lockWallpaperUri, aspectRatio = screenAspectRatio, @@ -108,7 +93,6 @@ fun CurrentWallpaperPreview( modifier = Modifier.weight(1f) ) - // Home wallpaper preview (on the right) WallpaperPreviewBox( wallpaperUri = homeWallpaperUri, aspectRatio = screenAspectRatio, @@ -121,10 +105,6 @@ fun CurrentWallpaperPreview( } } -/** - * A single wallpaper preview. Shows a placeholder background until [wallpaperUri] is non-null, - * then fades in the image. Uses the device screen aspect ratio to avoid layout jumps. - */ @Composable private fun WallpaperPreviewBox( wallpaperUri: String?, @@ -146,23 +126,15 @@ private fun WallpaperPreviewBox( .clip(AppShapes.imageShape) .background(MaterialTheme.colorScheme.surfaceContainerHighest) ) { - AnimatedVisibility( - visible = wallpaperUri != null, - enter = fadeIn(animationSpec = tween(if (animate) Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt() else 0)), - exit = fadeOut(animationSpec = tween(if (animate) Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt() else 0)) - ) { - wallpaperUri?.let { uri -> - AsyncImage( - model = ImageRequest.Builder(context) - .data(uri) - .size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT)) - .crossfade(true) - .build(), - contentDescription = contentDescription, - contentScale = ContentScale.Crop, - modifier = Modifier.matchParentSize() - ) - } - } + AsyncImage( + model = ImageRequest.Builder(context) + .data(wallpaperUri) + .size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT)) + .crossfade(animate) + .build(), + contentDescription = contentDescription, + contentScale = ContentScale.Crop, + modifier = Modifier.matchParentSize() + ) } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitch.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitch.kt deleted file mode 100644 index 780d110..0000000 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitch.kt +++ /dev/null @@ -1,84 +0,0 @@ -package com.anthonyla.paperize.presentation.screens.wallpaper.components - -import androidx.annotation.StringRes -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.style.TextOverflow -import com.anthonyla.paperize.presentation.theme.AppSpacing - -/** - * Simple setting switch without sliders - Enhanced with Material 3 Expressive design - */ -@Composable -fun SettingSwitch( - @StringRes title: Int, - @StringRes description: Int?, - checked: Boolean, - onCheckedChange: (Boolean) -> Unit, - modifier: Modifier = Modifier -) { - Card( - modifier = modifier - .fillMaxWidth() - .padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)), - shape = MaterialTheme.shapes.medium, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ) - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large) - .semantics(mergeDescendants = true) {}, - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column( - modifier = Modifier.weight(1f) - ) { - Text( - text = stringResource(title), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - description?.let { - Spacer(modifier = Modifier.height(AppSpacing.extraSmall)) - Text( - text = stringResource(it), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - } - Spacer(modifier = Modifier.width(AppSpacing.large)) - Switch( - checked = checked, - onCheckedChange = onCheckedChange - ) - } - } -} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/TimeIntervalPicker.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/TimeIntervalPicker.kt index 55429bb..5457912 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/TimeIntervalPicker.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/TimeIntervalPicker.kt @@ -13,10 +13,9 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -29,12 +28,7 @@ import com.anthonyla.paperize.R import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.presentation.theme.AppSpacing import kotlinx.coroutines.delay -import kotlin.math.max -import kotlin.math.min -/** - * Time interval picker with separate inputs for days, hours, and minutes - */ @Composable fun TimeIntervalPicker( title: String, @@ -43,39 +37,26 @@ fun TimeIntervalPicker( modifier: Modifier = Modifier, minimumMinutes: Int = Constants.MIN_INTERVAL_MINUTES ) { - // Decompose incoming minutes value into days, hours, minutes val initialDays = minutes / Constants.MINUTES_PER_DAY val remainingAfterDays = minutes % Constants.MINUTES_PER_DAY val initialHours = remainingAfterDays / Constants.MINUTES_PER_HOUR val initialMins = remainingAfterDays % Constants.MINUTES_PER_HOUR - // State for user input - var dayValue by remember(minutes) { mutableIntStateOf(initialDays) } - var hourValue by remember(minutes) { mutableIntStateOf(initialHours) } - var minuteValue by remember(minutes) { mutableIntStateOf(initialMins) } - var dayInput by remember(minutes) { mutableStateOf(initialDays.toString()) } var hourInput by remember(minutes) { mutableStateOf(initialHours.toString()) } var minuteInput by remember(minutes) { mutableStateOf(initialMins.toString()) } - // Debounce state - tracks when user last made a change; reset when external `minutes` prop changes - var lastChangeTimestamp by remember(minutes) { mutableLongStateOf(0L) } - - // Debounced update - only fires after user stops typing - LaunchedEffect(dayValue, hourValue, minuteValue, lastChangeTimestamp) { - if (lastChangeTimestamp > 0) { + var edited by remember(minutes) { mutableStateOf(false) } + val onChange by rememberUpdatedState(onMinutesChange) + LaunchedEffect(dayInput, hourInput, minuteInput, edited, minimumMinutes) { + if (edited) { delay(Constants.DEBOUNCE_DELAY_MS) - val total = (dayValue * Constants.MINUTES_PER_DAY) + (hourValue * Constants.MINUTES_PER_HOUR) + minuteValue - // Clamp between minimum and maximum interval - val clamped = min(max(total, minimumMinutes), Constants.MAX_INTERVAL_MINUTES) - onMinutesChange(clamped) + val total = (dayInput.toIntOrNull() ?: 0) * Constants.MINUTES_PER_DAY + + (hourInput.toIntOrNull() ?: 0) * Constants.MINUTES_PER_HOUR + (minuteInput.toIntOrNull() ?: 0) + onChange(total.coerceIn(minimumMinutes, Constants.MAX_INTERVAL_MINUTES)) } } - fun notifyChange() { - lastChangeTimestamp = System.currentTimeMillis() - } - androidx.compose.material3.Card( shape = MaterialTheme.shapes.medium, colors = androidx.compose.material3.CardDefaults.cardColors( @@ -102,14 +83,12 @@ fun TimeIntervalPicker( horizontalArrangement = Arrangement.spacedBy(AppSpacing.small), verticalAlignment = Alignment.CenterVertically ) { - // Days input OutlinedTextField( value = dayInput, onValueChange = { newValue -> - if (newValue.isEmpty() || (newValue.all { it.isDigit() } && newValue.length <= Constants.MAX_DAYS_INPUT_LENGTH)) { + if (newValue.all { it.isDigit() } && newValue.length <= Constants.MAX_DAYS_INPUT_LENGTH) { dayInput = newValue - dayValue = newValue.toIntOrNull() ?: 0 - notifyChange() + edited = true } }, label = { Text(stringResource(R.string.days_txt)) }, @@ -119,14 +98,12 @@ fun TimeIntervalPicker( textStyle = MaterialTheme.typography.bodyLarge ) - // Hours input OutlinedTextField( value = hourInput, onValueChange = { newValue -> - if (newValue.isEmpty() || (newValue.all { it.isDigit() } && newValue.length <= Constants.MAX_HOURS_MINUTES_INPUT_LENGTH)) { + if (newValue.all { it.isDigit() } && newValue.length <= Constants.MAX_HOURS_MINUTES_INPUT_LENGTH) { hourInput = newValue - hourValue = newValue.toIntOrNull() ?: 0 - notifyChange() + edited = true } }, label = { Text(stringResource(R.string.hours_txt)) }, @@ -136,14 +113,12 @@ fun TimeIntervalPicker( textStyle = MaterialTheme.typography.bodyLarge ) - // Minutes input OutlinedTextField( value = minuteInput, onValueChange = { newValue -> - if (newValue.isEmpty() || (newValue.all { it.isDigit() } && newValue.length <= Constants.MAX_HOURS_MINUTES_INPUT_LENGTH)) { + if (newValue.all { it.isDigit() } && newValue.length <= Constants.MAX_HOURS_MINUTES_INPUT_LENGTH) { minuteInput = newValue - minuteValue = newValue.toIntOrNull() ?: 0 - notifyChange() + edited = true } }, label = { Text(stringResource(R.string.mins)) }, diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt index 026c86f..2e499d7 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt @@ -4,8 +4,6 @@ import com.anthonyla.paperize.presentation.components.OnboardingLayout import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.layout.* -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.LiveTv import androidx.compose.material.icons.filled.Wallpaper @@ -16,23 +14,22 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.graphics.vector.rememberVectorPainter import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.anthonyla.paperize.presentation.screens.settings.SettingsViewModel import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import com.anthonyla.paperize.R import com.anthonyla.paperize.core.WallpaperMode import com.anthonyla.paperize.presentation.theme.AppSpacing -/** - * Wallpaper mode selection screen shown during onboarding - * Allows user to choose between STATIC and LIVE wallpaper modes - */ @Composable fun WallpaperModeSelectionScreen( onModeSelected: () -> Unit, modifier: Modifier = Modifier, - viewModel: WallpaperModeSelectionViewModel = hiltViewModel() + viewModel: SettingsViewModel = hiltViewModel() ) { + val isResetting by viewModel.isResetting.collectAsStateWithLifecycle() + val resetFailed by viewModel.resetFailed.collectAsStateWithLifecycle() var selectedMode by remember { mutableStateOf(null) } OnboardingLayout( @@ -60,7 +57,6 @@ fun WallpaperModeSelectionScreen( Spacer(modifier = Modifier.height(AppSpacing.small)) - // Static Mode Card ModeSelectionCard( title = stringResource(R.string.static_mode), description = stringResource(R.string.static_mode_description), @@ -69,7 +65,6 @@ fun WallpaperModeSelectionScreen( onClick = { selectedMode = WallpaperMode.STATIC } ) - // Live Mode Card ModeSelectionCard( title = stringResource(R.string.live_wallpaper_mode), description = stringResource(R.string.live_wallpaper_mode_description), @@ -80,16 +75,17 @@ fun WallpaperModeSelectionScreen( } }, actions = { + if (resetFailed) Text(stringResource(R.string.reset_failed), color = MaterialTheme.colorScheme.error) + if (isResetting) LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) Button( onClick = { selectedMode?.let { mode -> - viewModel.setWallpaperMode(mode) - onModeSelected() + viewModel.switchWallpaperMode(mode, onModeSelected) } }, modifier = Modifier.fillMaxWidth(), shape = MaterialTheme.shapes.large, - enabled = selectedMode != null + enabled = selectedMode != null && !isResetting ) { Text( text = stringResource(R.string.continue_button), @@ -173,7 +169,7 @@ private fun ModeSelectionCard( Spacer(modifier = Modifier.width(AppSpacing.small)) RadioButton( selected = true, - onClick = onClick + onClick = null ) } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt deleted file mode 100644 index e0e7389..0000000 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt +++ /dev/null @@ -1,47 +0,0 @@ -package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection -import com.anthonyla.paperize.core.constants.Constants - -import android.util.Log -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.anthonyla.paperize.core.WallpaperMode -import com.anthonyla.paperize.domain.repository.SettingsRepository -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.launch -import javax.inject.Inject - -@HiltViewModel -class WallpaperModeSelectionViewModel @Inject constructor( - private val settingsRepository: SettingsRepository, - private val albumRepository: com.anthonyla.paperize.domain.repository.AlbumRepository, - private val wallpaperScheduler: com.anthonyla.paperize.service.worker.WallpaperScheduler -) : ViewModel() { - - companion object { - private const val TAG = "WModeSelectionViewModel" - } - - /** - * Set wallpaper mode (STATIC or LIVE) - */ - fun setWallpaperMode(mode: WallpaperMode) { - viewModelScope.launch { - // Cancel all scheduled wallpaper changes first - wallpaperScheduler.cancelAllWallpaperChanges() - - // Delete all albums (cascades to delete all wallpapers, folders, and queues) - when (val result = albumRepository.deleteAllAlbums()) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - Log.e(TAG, "Error deleting albums during mode selection", result.exception) - } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } - } - - // Reset schedule settings to default (clears effects, intervals, etc.) - settingsRepository.clearScheduleSettings() - - settingsRepository.setWallpaperMode(mode) - } - } -} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/theme/DesignTokens.kt b/app/src/main/java/com/anthonyla/paperize/presentation/theme/DesignTokens.kt index 76751bf..103655a 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/theme/DesignTokens.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/theme/DesignTokens.kt @@ -3,396 +3,48 @@ package com.anthonyla.paperize.presentation.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.unit.dp -/** - * Material 3 Expressive Design Tokens - * - * Spacing, shapes, and layout constants following Material 3 Expressive guidelines. - * Expressive design emphasizes generous spacing, larger corner radii, and comfortable - * layouts that feel open and inviting. - * - * All spacing values use a 4dp base unit for consistency and visual harmony. - */ object AppSpacing { - /** - * Extra small spacing (6.dp) - * Increased from 4dp for better breathing room - * Used for: Text line gaps, tight groupings within components - */ val extraSmall = 6.dp - - /** - * Small spacing (12.dp) - * Increased from 8dp for expressive comfort - * Used for: Form fields, list items, content within cards, component internal padding - */ val small = 12.dp - - /** - * Medium spacing (16.dp) - * Increased from 12dp for clear visual separation - * Used for: Section breaks, moderate content separation, card internal padding - */ val medium = 16.dp - - /** - * Large spacing (20.dp) - * Increased from 16dp for prominent separation - * Used for: Screen edges, card padding, major section separation - */ val large = 20.dp - - /** - * Extra large spacing (28.dp) - * Increased from 24dp for expressive hierarchy - * Used for: Screen-level separation, major feature divisions, section headers - */ val extraLarge = 28.dp - - /** - * Huge spacing (36.dp) - * New addition for expressive design - * Used for: Major screen divisions, empty state spacing, hero sections - */ - val huge = 36.dp - - // Grid-specific spacing - /** - * Grid spacing (8.dp) - * Increased from 4dp for better grid item separation - * Used for: Spacing between grid items in LazyGrids - */ val gridSpacing = 8.dp - - /** - * Grid padding (12.dp) - * Increased from 4dp for comfortable grid container padding - * Used for: Content padding around grid containers - */ val gridPadding = 12.dp } -/** - * Material 3 Expressive Shape Tokens - * - * Larger corner radii create softer, more approachable UI elements. - * These values align with the ExpressiveShapes used in the theme. - */ object AppShapes { - /** - * Primary card shape (20.dp corners) - * Increased from 16dp for expressive softness - * Used for: Main content cards, feature cards, dialog containers - */ val cardShape = RoundedCornerShape(20.dp) - - /** - * Medium card shape (16.dp corners) - * Replaces smallCardShape with more generous rounding - * Used for: Secondary cards, nested cards, list items with rounded corners - */ - val mediumCardShape = RoundedCornerShape(16.dp) - - /** - * Small card shape (12.dp corners) - * Used for: Compact cards, chips, small UI elements - */ val smallCardShape = RoundedCornerShape(12.dp) - - /** - * Image shape (12.dp corners) - * Increased from 8dp for softer image presentation - * Used for: Images within cards, thumbnails, media elements - */ val imageShape = RoundedCornerShape(12.dp) - - /** - * Extra large shape (24.dp corners) - * For large, prominent UI elements - * Used for: Full-width cards, bottom sheets, large dialogs - */ - val extraLargeShape = RoundedCornerShape(24.dp) } -/** - * Grid layout constants for responsive, comfortable layouts - */ object AppGrid { - /** - * Minimum size for grid items (160.dp) - * Increased from 150dp for more comfortable touch targets - * Used with GridCells.Adaptive for responsive grid layouts - */ val itemMinSize = 160.dp - - /** - * Preferred aspect ratio for grid items (1f for square) - * Maintains consistent proportions across different screen sizes - */ - const val itemAspectRatio = 1f } -/** - * Elevation tokens for layering and depth - * Material 3 Expressive uses subtle elevation for visual hierarchy - */ object AppElevation { - /** - * Level 0 (0.dp) - No elevation - * Used for: Background surfaces, base layer - */ - val level0 = 0.dp - - /** - * Level 1 (1.dp) - Minimal elevation - * Used for: Cards at rest, subtle layering - */ val level1 = 1.dp - - /** - * Level 2 (3.dp) - Low elevation - * Used for: Cards with interaction, FABs at rest - */ - val level2 = 3.dp - - /** - * Level 3 (6.dp) - Medium elevation - * Used for: Elevated cards, FABs on hover/press, dialogs - */ - val level3 = 6.dp - - /** - * Level 4 (8.dp) - High elevation - * Used for: Navigation drawer, menus, prominent dialogs - */ - val level4 = 8.dp - - /** - * Level 5 (12.dp) - Very high elevation - * Used for: Modal bottom sheets, tooltips - */ - val level5 = 12.dp - - /** - * Component Elevation (10.dp) - Custom elevation for interactive components - * Used for: Settings switches, interactive cards with tonal elevation - * Note: Custom value chosen for Material 3 Expressive design to provide - * stronger visual distinction while maintaining accessibility - */ - val componentElevation = 10.dp - - /** - * Selection elevation (5.dp) - Elevation for selected items - * Used for: Selected folders, wallpapers, and other selectable items - */ - val selectionElevation = 5.dp } -/** - * Icon size tokens for consistent icon sizing throughout the app - */ object AppIconSizes { - /** - * Small icon (24.dp) - * Used for: Toolbar icons, inline icons, compact UI elements - */ - val small = 24.dp - - /** - * Medium icon (32.dp) - * Used for: List item icons, secondary actions - */ val medium = 32.dp - - /** - * Large icon (48.dp) - * Used for: Primary action buttons, prominent icons - */ val large = 48.dp - - /** - * Extra large icon (56.dp) - * Used for: Album covers, feature icons - */ val extraLarge = 56.dp - - /** - * Huge icon (64.dp) - * Used for: Empty state icons, onboarding icons - */ val huge = 64.dp - - /** - * Massive icon (80.dp) - * Used for: Large empty state icons, hero icons - */ - val massive = 80.dp } -/** - * Border width tokens for consistent borders - */ object AppBorderWidths { - /** - * Thin border (1.dp) - * Used for: Subtle dividers, secondary borders - */ val thin = 1.dp - - /** - * Medium border (2.dp) - * Used for: Default borders, card outlines - */ val medium = 2.dp - - /** - * Thick border (3.dp) - * Used for: Selection indicators, prominent borders - */ val thick = 3.dp } -/** - * Corner radius tokens for consistent rounded corners - */ object AppRadii { - /** - * Tiny radius (4.dp) - * Used for: Small UI elements, middle items in lists - */ - val tiny = 4.dp - - /** - * Small radius (12.dp) - * Used for: Compact cards, chips, images - */ - val small = 12.dp - - /** - * Medium radius (16.dp) - * Used for: Standard cards, dialogs, buttons - */ - val medium = 16.dp - - /** - * Large radius (20.dp) - * Used for: Primary cards, prominent UI elements - */ val large = 20.dp - - /** - * Extra large radius (32.dp) - * Used for: Pressed states, prominent buttons - */ - val extraLarge = 32.dp - - /** - * Huge radius (36.dp) - * Used for: Large pressed states, hero cards - */ val huge = 36.dp - - /** - * Massive radius (40.dp) - * Used for: Maximum rounding, special effects - */ - val massive = 40.dp } -/** - * Alpha/opacity tokens for consistent transparency - */ -object AppAlpha { - /** - * Very subtle opacity (0.1f) - * Used for: Very light overlays, subtle backgrounds - */ - const val verySubtle = 0.1f - - /** - * Subtle opacity (0.15f) - * Used for: Light borders, faint overlays - */ - const val subtle = 0.15f - - /** - * Light opacity (0.25f) - * Used for: Disabled states, subtle icons - */ - const val light = 0.25f - - /** - * Medium opacity (0.3f) - * Used for: Secondary icons, medium overlays - */ - const val medium = 0.3f - - /** - * Semi-medium opacity (0.4f) - * Used for: Empty state icons, inactive elements - */ - const val semiMedium = 0.4f - - /** - * Selected opacity (0.7f) - * Used for: Selected items, active indicators - */ - const val selected = 0.7f - - /** - * Prominent opacity (0.8f) - * Used for: Important text, primary overlays - */ - const val prominent = 0.8f - - /** - * Full opacity (1.0f) - * Used for: Fully visible elements - */ - const val full = 1.0f -} - -/** - * Elevation delta tokens for animated elevation changes - */ -object AppElevationDeltas { - /** - * Pressed elevation increase (2.dp) - * Amount to increase elevation when an element is pressed - */ - val pressedIncrease = 2.dp -} - -/** - * Maximum width constraints for responsive layouts - */ object AppMaxWidths { - /** - * Maximum content width (600.dp) - * Material 3 guideline for optimal reading width - * Used for: Content containers on large screens - */ val contentMaxWidth = 600.dp } - -/** - * Scale factor tokens for sizing elements relative to containers - */ -object AppScaleFactor { - /** - * Medium icon scale (0.45f) - * Used for: Icons that take 45% of container size - */ - const val iconMedium = 0.45f - - /** - * Large icon scale (0.5f) - * Used for: Icons that take 50% of container size - */ - const val iconLarge = 0.5f - - /** - * Threshold (0.5f) - * Used for: Conditional logic based on 50% threshold - */ - const val threshold = 0.5f -} diff --git a/app/src/main/java/com/anthonyla/paperize/service/WallpaperChangeLock.kt b/app/src/main/java/com/anthonyla/paperize/service/WallpaperChangeLock.kt index 73ce280..3b0c1d3 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/WallpaperChangeLock.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/WallpaperChangeLock.kt @@ -4,14 +4,7 @@ import kotlinx.coroutines.sync.Mutex import javax.inject.Inject import javax.inject.Singleton -/** - * Shared mutex for wallpaper change operations. - * - * Both [WallpaperChangeService] and [WallpaperChangeWorker] can trigger wallpaper - * changes simultaneously (e.g. a manual change fires the service while a scheduled - * WorkManager job fires the worker). This singleton ensures only one change runs - * at a time across both entry points. - */ +/** Serializes manual and scheduled wallpaper changes across both entry points. */ @Singleton class WallpaperChangeLock @Inject constructor() { val mutex = Mutex() diff --git a/app/src/main/java/com/anthonyla/paperize/service/alarm/BootReceiver.kt b/app/src/main/java/com/anthonyla/paperize/service/alarm/BootReceiver.kt index 6587517..b919782 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/alarm/BootReceiver.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/alarm/BootReceiver.kt @@ -4,8 +4,6 @@ import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log -import com.anthonyla.paperize.core.ScreenType -import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.domain.repository.SettingsRepository import com.anthonyla.paperize.service.worker.WallpaperScheduler import dagger.hilt.android.AndroidEntryPoint @@ -15,12 +13,6 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import javax.inject.Inject -/** - * Broadcast receiver to reschedule wallpaper changes on device boot - * - * Uses WorkManager for scheduling instead of AlarmManager - * Uses goAsync() to ensure coroutine completes before receiver is destroyed - */ @AndroidEntryPoint class BootReceiver : BroadcastReceiver() { @@ -40,91 +32,18 @@ class BootReceiver : BroadcastReceiver() { ) { Log.d(TAG, "Boot completed, rescheduling wallpaper changes") - // Use goAsync() to extend receiver lifecycle for async work - // This prevents the system from killing the receiver before coroutine completes val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try { - val settings = settingsRepository.getScheduleSettings() - - if (settings.enableChanger) { - // Get wallpaper mode to determine scheduling type - val wallpaperMode = settingsRepository.getWallpaperMode() - - if (wallpaperMode == com.anthonyla.paperize.core.WallpaperMode.LIVE) { - // LIVE mode: schedule live wallpaper changes - if (settings.liveAlbumId != null && settings.liveIntervalMinutes > 0) { - if (settings.liveIntervalMinutes >= Constants.MIN_INTERVAL_MINUTES) { - wallpaperScheduler.scheduleWallpaperChange( - ScreenType.LIVE, - settings.liveIntervalMinutes - ) - } else { - wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE) - } - wallpaperScheduler.scheduleAlbumRefresh() - Log.d(TAG, "Live wallpaper changes scheduled on boot") - } else { - wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE) - wallpaperScheduler.cancelAlbumRefresh() - Log.d(TAG, "Live mode but no album or interval, not scheduling") - } - } else { - // STATIC mode: existing logic - // Check if we have all required albums before scheduling - val homeActive = settings.homeEnabled && settings.homeAlbumId != null - val lockActive = settings.lockEnabled && settings.lockAlbumId != null - val hasRequiredAlbums = when { - settings.homeEnabled && settings.lockEnabled -> homeActive && lockActive - settings.homeEnabled -> homeActive - settings.lockEnabled -> lockActive - else -> false - } - - if (hasRequiredAlbums) { - // Reschedule wallpaper changes with WorkManager - val homeInterval: Int - val lockInterval: Int - - if (settings.separateSchedules) { - // Separate schedules for home and lock - homeInterval = if (settings.homeEnabled) settings.homeIntervalMinutes else 0 - lockInterval = if (settings.lockEnabled) settings.lockIntervalMinutes else 0 - } else { - // Same interval for both (enabled screens) - val interval = settings.homeIntervalMinutes - homeInterval = if (settings.homeEnabled) interval else 0 - lockInterval = if (settings.lockEnabled) interval else 0 - } - - // Determine if screens should be synchronized - val shouldSync = settings.homeEnabled && settings.lockEnabled && - settings.homeAlbumId != null && - settings.homeAlbumId == settings.lockAlbumId && - !settings.separateSchedules - - wallpaperScheduler.scheduleWallpaperChanges( - homeIntervalMinutes = homeInterval, - lockIntervalMinutes = lockInterval, - synchronized = shouldSync, - onlyIfNotScheduled = true // Don't reschedule if already scheduled - ) - - Log.d(TAG, "Wallpaper changes rescheduled successfully") - } else { - wallpaperScheduler.cancelAllWallpaperChanges() - Log.d(TAG, "Wallpaper changer enabled but required albums not selected, not scheduling") - } - } - } else { - wallpaperScheduler.cancelAllWallpaperChanges() - Log.d(TAG, "Wallpaper changer disabled, not scheduling") - } + wallpaperScheduler.updateSchedules( + settingsRepository.getScheduleSettings(), + settingsRepository.getWallpaperMode(), + onlyIfNotScheduled = true + ) } catch (e: Exception) { Log.e(TAG, "Error rescheduling wallpaper changes", e) } finally { - // Must call finish() to release the async operation pendingResult.finish() } } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt index 5ec63b6..071743a 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt @@ -4,12 +4,6 @@ import android.util.Log import android.view.GestureDetector import android.view.MotionEvent import android.view.SurfaceHolder -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleOwner -import androidx.lifecycle.LifecycleRegistry -import androidx.savedstate.SavedStateRegistry -import androidx.savedstate.SavedStateRegistryController -import androidx.savedstate.SavedStateRegistryOwner import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.ScalingType import com.anthonyla.paperize.core.WallpaperMode @@ -20,14 +14,10 @@ import com.anthonyla.paperize.domain.repository.WallpaperRepository import com.anthonyla.paperize.service.livewallpaper.gl.GLWallpaperService import com.anthonyla.paperize.service.livewallpaper.renderer.ContentUriImageLoader import com.anthonyla.paperize.service.livewallpaper.renderer.EmptyImageLoader -import com.anthonyla.paperize.service.livewallpaper.renderer.ImageLoader import com.anthonyla.paperize.service.livewallpaper.renderer.PaperizeWallpaperRenderer import com.anthonyla.paperize.service.livewallpaper.renderer.PaperizeRenderController -import dagger.hilt.EntryPoint -import dagger.hilt.InstallIn import dagger.hilt.android.AndroidEntryPoint -import dagger.hilt.android.EntryPointAccessors -import dagger.hilt.components.SingletonComponent +import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -49,62 +39,26 @@ import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.core.util.isValid import com.anthonyla.paperize.domain.model.Wallpaper import com.anthonyla.paperize.service.livewallpaper.gl.GLCompatibility -import android.os.Handler -import android.os.Looper import android.widget.Toast import com.anthonyla.paperize.R -@EntryPoint -@InstallIn(SingletonComponent::class) -interface PaperizeLiveWallpaperEntryPoint { - fun settingsRepository(): SettingsRepository - fun wallpaperRepository(): WallpaperRepository -} - @AndroidEntryPoint -class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { +class PaperizeLiveWallpaperService : GLWallpaperService() { + + @Inject lateinit var settingsRepository: SettingsRepository + @Inject lateinit var wallpaperRepository: WallpaperRepository companion object { private const val TAG = "PaperizeLiveWallpaper" } - private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this) - - override val lifecycle: Lifecycle - get() = lifecycleRegistry - - override fun onCreate() { - super.onCreate() - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) - } - - override fun onDestroy() { - super.onDestroy() - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) - } - override fun onCreateEngine(): Engine { return PaperizeLiveWallpaperEngine() } inner class PaperizeLiveWallpaperEngine : GLEngine(), - LifecycleOwner, - SavedStateRegistryOwner, - PaperizeRenderController.Callbacks, PaperizeWallpaperRenderer.Callbacks { - private lateinit var settingsRepository: SettingsRepository - private lateinit var wallpaperRepository: WallpaperRepository - - private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this) - private val savedStateRegistryController = SavedStateRegistryController.create(this) - - override val lifecycle: Lifecycle - get() = lifecycleRegistry - - override val savedStateRegistry: SavedStateRegistry - get() = savedStateRegistryController.savedStateRegistry - private lateinit var renderer: PaperizeWallpaperRenderer private lateinit var renderController: PaperizeRenderController private val engineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) @@ -113,7 +67,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { private var observedScalingType: ScalingType? = null private var hasShownParallaxWarning = false private var engineVisible = false - private var latestSettings = ScheduleSettings.default() + private var latestSettings = ScheduleSettings() private var latestWallpaperMode = WallpaperMode.STATIC private var liveIntervalJob: Job? = null @@ -131,7 +85,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == Constants.ACTION_RELOAD_WALLPAPER) { Log.d(TAG, "Received reload broadcast") - renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate) + renderController.reloadCurrentArtwork(immediate = true) restartLiveIntervalTimer() } } @@ -149,25 +103,13 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { super.onCreate(surfaceHolder) Log.d(TAG, "Engine created") - // Enable offset notifications to receive scroll events setOffsetNotificationsEnabled(true) - // Enable touch events for double-tap gesture detection setTouchEventsEnabled(true) - savedStateRegistryController.performRestore(null) - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) - - val entryPoint = EntryPointAccessors.fromApplication( - applicationContext, - PaperizeLiveWallpaperEntryPoint::class.java - ) - settingsRepository = entryPoint.settingsRepository() - wallpaperRepository = entryPoint.wallpaperRepository() - renderer = PaperizeWallpaperRenderer(applicationContext, this) - renderController = object : PaperizeRenderController(renderer, this@PaperizeLiveWallpaperEngine, engineScope) { - override suspend fun openDownloadedCurrentArtwork(): ImageLoader = withContext(Dispatchers.IO) { + renderController = PaperizeRenderController(renderer::queueWallpaper, engineScope) { + withContext(Dispatchers.IO) { val mode = settingsRepository.getWallpaperMode() val settings = settingsRepository.getScheduleSettings() @@ -185,10 +127,9 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { return@withContext EmptyImageLoader } - // Check if queue exists, build it if empty val queueCheck = wallpaperRepository.getNextWallpaperInQueue(albumId, ScreenType.LIVE) if (queueCheck == null) { - wallpaperRepository.buildWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled) + wallpaperRepository.ensureWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled) } var wallpaper: Wallpaper? = null @@ -196,7 +137,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { var queueRebuildAttempts = 0 while (wallpaper == null && maxRetries > 0) { - // Atomically get and remove from queue val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, ScreenType.LIVE) if (candidate == null) { @@ -206,12 +146,10 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { return@withContext EmptyImageLoader } - // Rebuild queue - wallpaperRepository.buildWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled) + wallpaperRepository.ensureWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled) continue } - // Validate URI val uri = candidate.uri.toUri() if (uri.isValid(contentResolver)) { wallpaper = candidate @@ -230,39 +168,22 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { currentWallpaper = wallpaper - // Peek at queue to see if it needs refilling (not dequeuing, just checking) val nextInQueue = wallpaperRepository.getNextWallpaperInQueue(albumId, ScreenType.LIVE) if (nextInQueue == null) { - wallpaperRepository.buildWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled) + wallpaperRepository.ensureWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled) } - try { - val uri = wallpaper.uri.toUri() - ContentUriImageLoader(contentResolver, uri, settings.liveScalingType) - } catch (e: Exception) { - Log.e(TAG, "Error creating image loader", e) - EmptyImageLoader - } + ContentUriImageLoader(contentResolver, wallpaper.uri.toUri(), settings.liveScalingType) } } - lifecycle.addObserver(renderController) - setEGLContextClientVersion(Constants.GL_ES_VERSION) - setEGLConfigChooser(8, 8, 8, 0, 0, 0) setRenderer(renderer) - setRenderMode(RENDERMODE_WHEN_DIRTY) requestRender() - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) + renderController.reloadCurrentArtwork(immediate = true) - // Trigger initial load - renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate) - - // Observe settings changes observeSettings() - // Register broadcast receiver for reload val filter = IntentFilter(Constants.ACTION_RELOAD_WALLPAPER) ContextCompat.registerReceiver( applicationContext, @@ -271,7 +192,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { ContextCompat.RECEIVER_NOT_EXPORTED ) - // Register screen-off receiver for wallpaper change on screen off val screenOffFilter = IntentFilter(Intent.ACTION_SCREEN_OFF) ContextCompat.registerReceiver( applicationContext, @@ -300,8 +220,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { latestWallpaperMode = mode if (timerConfigurationChanged) restartLiveIntervalTimer() - // Only process settings in LIVE mode - // In STATIC mode, the static wallpaper worker handles HOME/LOCK screens if (mode != com.anthonyla.paperize.core.WallpaperMode.LIVE) { return@collect } @@ -336,19 +254,15 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { } } - // Show Toast warning if parallax is enabled but device has offset issues if (effects.enableParallax && !hasShownParallaxWarning && GLCompatibility.shouldWarnAboutParallax()) { hasShownParallaxWarning = true - Handler(Looper.getMainLooper()).post { - Toast.makeText( - applicationContext, - R.string.parallax_may_not_work, - Toast.LENGTH_LONG - ).show() - } + Toast.makeText( + applicationContext, + R.string.parallax_may_not_work, + Toast.LENGTH_LONG + ).show() } - // Reload if album changed if (albumChanged) { Log.d(TAG, "Album changed from $currentAlbumId to $albumId, reloading") currentAlbumId = albumId @@ -358,11 +272,6 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { } } - - override fun onSurfaceCreated(holder: SurfaceHolder) { - super.onSurfaceCreated(holder) - } - override fun onVisibilityChanged(visible: Boolean) { engineVisible = visible renderController.visible = visible @@ -409,31 +318,26 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { Log.e(TAG, "Error unregistering screen-off receiver", e) } - // Cleanup renderer resources on GL thread + renderer.cancelLoading() + queueEvent { renderer.destroy() } - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP) - lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) engineScope.cancel() super.onDestroy() } - override fun queueEventOnGlThread(event: () -> Unit) { - queueEvent(event) - } + override fun queueEventOnGlThread(event: () -> Unit): Boolean = queueEvent(event) private fun handleDoubleTap() { engineScope.launch { val settings = settingsRepository.getScheduleSettings() - // Always check liveEffects since double-tap is only available in live wallpaper mode val doubleTapEnabled = settings.liveEffects.enableDoubleTap if (doubleTapEnabled) { - renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate) + renderController.reloadCurrentArtwork(immediate = true) restartLiveIntervalTimer() } } @@ -470,7 +374,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner { delay(intervalMillis) Log.d(TAG, "Visible live interval elapsed; changing wallpaper") renderController.reloadCurrentArtwork( - com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate + immediate = true ) } } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLCompatibility.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLCompatibility.kt index cc8fc09..b9614d1 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLCompatibility.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLCompatibility.kt @@ -9,14 +9,12 @@ import kotlin.math.min * * Provides OEM-specific workarounds for: * - Texture size limits (some OEMs misreport GL_MAX_TEXTURE_SIZE) - * - EGL configuration fallbacks (different GPUs need different configs) * - Parallax support detection (some launchers don't report offsets) */ object GLCompatibility { private const val TAG = "GLCompatibility" - // Known problematic manufacturers for various GL issues private val LOW_END_GPU_MANUFACTURERS = setOf( "MEDIATEK", // Mali-T/G series often have texture issues "ALLWINNER", // Low-end tablets @@ -24,7 +22,6 @@ object GLCompatibility { "SPREADTRUM" // Budget phones ) - // Manufacturers with known parallax/offset issues private val PARALLAX_ISSUE_MANUFACTURERS = setOf( "SAMSUNG", // One UI often doesn't report offsets properly "XIAOMI", // MIUI Launcher has inconsistent offset reporting @@ -35,49 +32,26 @@ object GLCompatibility { "ONEPLUS" // OxygenOS (older versions) ) - // Texture size limits by device tier private const val TEXTURE_SIZE_LOW_END = 2048 private const val TEXTURE_SIZE_MID_RANGE = 4096 - /** - * Get the device manufacturer in uppercase for comparison. - */ - fun getManufacturer(): String = Build.MANUFACTURER.uppercase() + private fun getManufacturer(): String = Build.MANUFACTURER.uppercase() - - /** - * Check if the device likely has a low-end GPU that may have texture issues. - */ - fun isLowEndGPU(): Boolean { + private fun isLowEndGPU(): Boolean { val manufacturer = getManufacturer() - val isLowEnd = LOW_END_GPU_MANUFACTURERS.any { manufacturer.contains(it) } - - // Also check for low RAM as a heuristic for low-end devices - // Note: This is a simple heuristic; actual RAM check would require context - - return isLowEnd + return LOW_END_GPU_MANUFACTURERS.any { manufacturer.contains(it) } } - /** - * Get a safe maximum texture size based on device capabilities. - * This is more conservative than the GL-reported value to avoid OOM on problematic devices. - * - * @param glReportedMax The maximum texture size reported by GL_MAX_TEXTURE_SIZE - * @return A safe texture size to use - */ fun getSafeMaxTextureSize(glReportedMax: Int = 0): Int { val manufacturer = getManufacturer() - // Use conservative limits for known problematic manufacturers - val safeLimit = when { - isLowEndGPU() -> { - Log.d(TAG, "Low-end GPU detected ($manufacturer), using conservative texture size") - TEXTURE_SIZE_LOW_END - } - else -> TEXTURE_SIZE_MID_RANGE + val safeLimit = if (isLowEndGPU()) { + Log.d(TAG, "Low-end GPU detected ($manufacturer), using conservative texture size") + TEXTURE_SIZE_LOW_END + } else { + TEXTURE_SIZE_MID_RANGE } - // If we have a GL-reported max, cap at that value return if (glReportedMax > 0) { min(safeLimit, glReportedMax) } else { @@ -85,16 +59,7 @@ object GLCompatibility { } } - /** - * Check if the device's default launcher likely supports reliable offset notifications - * for parallax scrolling. - * - * Many OEM launchers don't properly call onOffsetsChanged(), making parallax - * scrolling impossible or erratic. - * - * @return true if offsets are likely to work reliably - */ - fun supportsReliableOffsets(): Boolean { + fun shouldWarnAboutParallax(): Boolean { val manufacturer = getManufacturer() val hasIssues = PARALLAX_ISSUE_MANUFACTURERS.any { manufacturer.contains(it) } @@ -102,29 +67,7 @@ object GLCompatibility { Log.d(TAG, "Manufacturer $manufacturer may have parallax/offset issues with stock launcher") } - // Return true anyway - we don't disable parallax outright, but we detect it - // The caller can use this to show a toast or fallback gracefully - return !hasIssues - } - - /** - * Check if we should warn the user about potential parallax issues. - * Only returns true if parallax would likely not work on this device. - */ - fun shouldWarnAboutParallax(): Boolean { - return !supportsReliableOffsets() - } - - - /** - * Log device information for debugging. - */ - fun logDeviceInfo() { - Log.i(TAG, "Device: ${Build.MANUFACTURER} ${Build.MODEL}") - Log.i(TAG, "Android: ${Build.VERSION.SDK_INT} (${Build.VERSION.RELEASE})") - Log.i(TAG, "Board: ${Build.BOARD}, Hardware: ${Build.HARDWARE}") - Log.i(TAG, "Low-end GPU: ${isLowEndGPU()}") - Log.i(TAG, "Supports reliable offsets: ${supportsReliableOffsets()}") + return hasIssues } } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt index 5cb4445..19ed174 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt @@ -4,20 +4,12 @@ import android.graphics.Bitmap import android.opengl.GLES20 import android.opengl.GLUtils import android.util.Log -import java.nio.ByteBuffer -import java.nio.ByteOrder +import com.anthonyla.paperize.service.livewallpaper.renderer.GLGeometry import java.nio.FloatBuffer import kotlin.math.ceil import kotlin.math.min -/** - * Represents a picture as a collection of OpenGL textures (tiles). - * Large images are subdivided into tiles to avoid texture size limits. - * Optimized for modern devices (API 31+) with larger tile sizes and pre-allocated buffers. - * - * @property width Original bitmap width - * @property height Original bitmap height - */ +/** Splits large images into textures within the device limit. Geometry is allocated once per tile. */ class GLPicture( bitmap: Bitmap, /** @@ -30,20 +22,7 @@ class GLPicture( companion object { private const val TAG = "GLPicture" - // Use larger tiles for modern devices - reduces draw calls significantly - private const val PREFERRED_TILE_SIZE = 4096 - // Cache max texture size to avoid repeated GL queries - @Volatile - private var cachedMaxTextureSize = 0 - - private fun getOptimalTileSize(): Int { - if (cachedMaxTextureSize == 0) { - cachedMaxTextureSize = GLUtil.getMaxTextureSize() - } - // Use up to 4096 for good memory/performance balance - return min(cachedMaxTextureSize, PREFERRED_TILE_SIZE) - } } val width = bitmap.width @@ -54,14 +33,8 @@ class GLPicture( private val rows: Int init { - // Validate bitmap before processing require(!bitmap.isRecycled) { "Cannot create GLPicture from recycled bitmap" } - require(bitmap.width > 0 && bitmap.height > 0) { - "Cannot create GLPicture from bitmap with invalid dimensions: ${bitmap.width}x${bitmap.height}" - } - - val maxTextureSize = GLCompatibility.getSafeMaxTextureSize(getOptimalTileSize()) - val tileSize = maxTextureSize + val tileSize = GLCompatibility.getSafeMaxTextureSize(GLUtil.getMaxTextureSize()) cols = ceil(width.toFloat() / tileSize).toInt() rows = ceil(height.toFloat() / tileSize).toInt() @@ -79,7 +52,6 @@ class GLPicture( val tileWidth = min(tileSize, width - tileX) val tileHeight = min(tileSize, height - tileY) - // Calculate geometry once at creation time (not per-frame) val left = -1f + (tileX.toFloat() / width) * 2f val right = -1f + ((tileX + tileWidth).toFloat() / width) * 2f val bottom = 1f - ((tileY + tileHeight).toFloat() / height) * 2f @@ -92,34 +64,23 @@ class GLPicture( right, top // Top-right ) - val texCoords = floatArrayOf( - 0f, 1f, // Bottom-left - 1f, 1f, // Bottom-right - 0f, 0f, // Top-left - 1f, 0f // Top-right - ) + val vertexBuffer = GLGeometry.createFloatBuffer(vertices) + val texCoordBuffer = GLGeometry.createFloatBuffer(GLGeometry.TEX_COORDS) - // Pre-allocate buffers (reused every frame) - val vertexBuffer = createFloatBuffer(vertices) - val texCoordBuffer = createFloatBuffer(texCoords) - - // Extract and upload tile bitmap val tileBitmap = Bitmap.createBitmap(bitmap, tileX, tileY, tileWidth, tileHeight) - val textureId = loadTexture(tileBitmap) - tileBitmap.recycle() + val textureId = try { + loadTexture(tileBitmap) + } finally { + if (tileBitmap !== bitmap) tileBitmap.recycle() + } partialTiles.add(Tile( textureId = textureId, - x = tileX, - y = tileY, - width = tileWidth, - height = tileHeight, vertexBuffer = vertexBuffer, texCoordBuffer = texCoordBuffer )) } } catch (e: Throwable) { - // Recycle any textures already uploaded to the GPU before re-throwing for (tile in partialTiles) { GLUtil.deleteTexture(tile.textureId) } @@ -128,14 +89,6 @@ class GLPicture( tiles = partialTiles.toTypedArray() } - /** - * Draw all tiles to cover the full picture. - * Uses pre-allocated buffers for optimal performance (zero allocations per frame). - * - * @param program Shader program to use - * @param aPositionHandle Attribute location for vertex positions - * @param aTexCoordHandle Attribute location for texture coordinates - */ fun draw( program: Int, aPositionHandle: Int, @@ -145,20 +98,16 @@ class GLPicture( ) { GLES20.glUseProgram(program) - // Enable vertex attribute arrays GLES20.glEnableVertexAttribArray(aPositionHandle) GLES20.glEnableVertexAttribArray(aTexCoordHandle) - // Pass MVP matrix GLES20.glUniformMatrix4fv(uMvpMatrixHandle, 1, false, mvpMatrix, 0) - // Draw each tile using pre-allocated buffers (no per-frame allocation) for (tile in tiles) { // Bind texture to unit 0 (must set active unit explicitly to avoid relying on GL state) GLES20.glActiveTexture(GLES20.GL_TEXTURE0) GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tile.textureId) - // Use pre-allocated buffers - no allocation here! GLES20.glVertexAttribPointer( aPositionHandle, 2, GLES20.GL_FLOAT, false, 0, tile.vertexBuffer ) @@ -166,11 +115,9 @@ class GLPicture( aTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, tile.texCoordBuffer ) - // Draw quad GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4) } - // Disable vertex attribute arrays GLES20.glDisableVertexAttribArray(aPositionHandle) GLES20.glDisableVertexAttribArray(aTexCoordHandle) } @@ -185,9 +132,6 @@ class GLPicture( } } - /** - * Load a bitmap as an OpenGL texture. - */ private fun loadTexture(bitmap: Bitmap): Int { val textureIds = IntArray(1) GLES20.glGenTextures(1, textureIds, 0) @@ -197,48 +141,27 @@ class GLPicture( throw RuntimeException("Failed to generate texture ID") } - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId) + try { + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId) - // Set texture parameters - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE) - // Upload bitmap to GPU - GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0) + GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0) - val error = GLES20.glGetError() - if (error != GLES20.GL_NO_ERROR) { - GLES20.glDeleteTextures(1, intArrayOf(textureId), 0) - throw RuntimeException("Texture upload failed: error 0x${Integer.toHexString(error)}") + GLUtil.checkGLError("texture upload") + + return textureId + } catch (e: Throwable) { + GLES20.glDeleteTextures(1, textureIds, 0) + throw e } - - return textureId } - /** - * Create a native-order float buffer from an array. - */ - private fun createFloatBuffer(data: FloatArray): FloatBuffer { - return ByteBuffer.allocateDirect(data.size * 4) - .order(ByteOrder.nativeOrder()) - .asFloatBuffer() - .apply { - put(data) - position(0) - } - } - - /** - * Represents a single tile of the picture with pre-allocated GPU buffers. - */ private data class Tile( val textureId: Int, - val x: Int, - val y: Int, - val width: Int, - val height: Int, val vertexBuffer: FloatBuffer, val texCoordBuffer: FloatBuffer ) diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt deleted file mode 100644 index 32c3085..0000000 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt +++ /dev/null @@ -1,56 +0,0 @@ -package com.anthonyla.paperize.service.livewallpaper.gl - -import android.util.Log - -/** - * Handle for an OpenGL texture that manages lifecycle and prevents leaks. - * Textures must be explicitly recycled when no longer needed. - * - * @property textureId OpenGL texture ID - * @property width Texture width in pixels - * @property height Texture height in pixels - */ -class GLTextureHandle( - val textureId: Int, - val width: Int, - val height: Int -) { - - companion object { - private const val TAG = "GLTextureHandle" - } - - @Volatile - private var recycled = false - - /** - * Recycle the texture and free GPU memory. - * This must be called on the GL thread. - */ - fun recycle() { - if (!recycled) { - GLUtil.deleteTexture(textureId) - recycled = true - } - } - - /** - * Check if this texture has been recycled. - */ - fun isRecycled(): Boolean = recycled - - /** - * Finalize method to detect leaked textures. - * Note: Cannot call GL functions from finalizer (wrong thread). - */ - @Suppress("removal") - protected fun finalize() { - if (!recycled) { - Log.w(TAG, "Texture $textureId (${width}x${height}) was not recycled! This is a memory leak.") - } - } - - override fun toString(): String { - return "GLTextureHandle(id=$textureId, size=${width}x${height}, recycled=$recycled)" - } -} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt index 5cc014e..4c2ac6b 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt @@ -3,23 +3,11 @@ package com.anthonyla.paperize.service.livewallpaper.gl import android.opengl.GLES20 import android.util.Log -/** - * Utilities for OpenGL ES operations including shader compilation, - * program linking, and error checking. - */ object GLUtil { private const val TAG = "GLUtil" - /** - * Compile a shader from source code. - * - * @param type Shader type (GLES20.GL_VERTEX_SHADER or GLES20.GL_FRAGMENT_SHADER) - * @param source GLSL source code - * @return Shader handle - * @throws RuntimeException if compilation fails - */ - fun compileShader(type: Int, source: String): Int { + private fun compileShader(type: Int, source: String): Int { val shader = GLES20.glCreateShader(type) if (shader == 0) { throw RuntimeException("Failed to create shader") @@ -41,67 +29,50 @@ object GLUtil { return shader } - /** - * Create a program from vertex and fragment shaders. - * - * @param vertexShader Compiled vertex shader handle - * @param fragmentShader Compiled fragment shader handle - * @return Program handle - * @throws RuntimeException if linking fails - */ - fun createProgram(vertexShader: Int, fragmentShader: Int): Int { + private fun createProgram(vertexShader: Int, fragmentShader: Int): Int { val program = GLES20.glCreateProgram() if (program == 0) { throw RuntimeException("Failed to create program") } - GLES20.glAttachShader(program, vertexShader) - checkGLError("glAttachShader (vertex)") + try { + GLES20.glAttachShader(program, vertexShader) + checkGLError("glAttachShader (vertex)") - GLES20.glAttachShader(program, fragmentShader) - checkGLError("glAttachShader (fragment)") + GLES20.glAttachShader(program, fragmentShader) + checkGLError("glAttachShader (fragment)") - GLES20.glLinkProgram(program) + GLES20.glLinkProgram(program) - val linked = IntArray(1) - GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0) + val linked = IntArray(1) + GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0) - if (linked[0] == 0) { - val log = GLES20.glGetProgramInfoLog(program) + if (linked[0] == 0) { + val log = GLES20.glGetProgramInfoLog(program) + throw RuntimeException("Program linking failed:\n$log") + } + + return program + } catch (e: Throwable) { GLES20.glDeleteProgram(program) - throw RuntimeException("Program linking failed:\n$log") + throw e } - - return program } - /** - * Compile shaders and create a program in one call. - * - * @param vertexSource Vertex shader GLSL source - * @param fragmentSource Fragment shader GLSL source - * @return Program handle - * @throws RuntimeException if compilation or linking fails - */ fun createProgram(vertexSource: String, fragmentSource: String): Int { val vertexShader = compileShader(GLES20.GL_VERTEX_SHADER, vertexSource) - val fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource) - - val program = createProgram(vertexShader, fragmentShader) - - // Shaders can be deleted after linking - GLES20.glDeleteShader(vertexShader) - GLES20.glDeleteShader(fragmentShader) - - return program + try { + val fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource) + try { + return createProgram(vertexShader, fragmentShader) + } finally { + GLES20.glDeleteShader(fragmentShader) + } + } finally { + GLES20.glDeleteShader(vertexShader) + } } - /** - * Check for OpenGL errors and throw if one occurred. - * - * @param operation Description of the operation for error message - * @throws RuntimeException if GL error occurred - */ fun checkGLError(operation: String) { val error = GLES20.glGetError() if (error != GLES20.GL_NO_ERROR) { @@ -111,22 +82,12 @@ object GLUtil { } } - /** - * Get the maximum texture size supported by the GPU. - * - * @return Maximum texture dimension in pixels - */ fun getMaxTextureSize(): Int { val maxSize = IntArray(1) GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxSize, 0) return maxSize[0] } - /** - * Delete a shader program and check for errors. - * - * @param program Program handle to delete - */ fun deleteProgram(program: Int) { if (program != 0) { GLES20.glDeleteProgram(program) @@ -134,11 +95,6 @@ object GLUtil { } } - /** - * Delete a texture and check for errors. - * - * @param texture Texture handle to delete - */ fun deleteTexture(texture: Int) { if (texture != 0) { GLES20.glDeleteTextures(1, intArrayOf(texture), 0) @@ -146,11 +102,6 @@ object GLUtil { } } - /** - * Delete a framebuffer and check for errors. - * - * @param framebuffer Framebuffer handle to delete - */ fun deleteFramebuffer(framebuffer: Int) { if (framebuffer != 0) { GLES20.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0) diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt index b289e71..7c41303 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt @@ -1,10 +1,11 @@ package com.anthonyla.paperize.service.livewallpaper.gl +import android.opengl.EGL14 import android.opengl.GLSurfaceView import android.service.wallpaper.WallpaperService import android.util.Log import android.view.SurfaceHolder -import java.util.concurrent.LinkedBlockingQueue +import com.anthonyla.paperize.core.constants.Constants import javax.microedition.khronos.egl.EGL10 import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.egl.EGLContext @@ -21,24 +22,12 @@ abstract class GLWallpaperService : WallpaperService() { companion object { private const val TAG = "GLWallpaperService" - const val RENDERMODE_WHEN_DIRTY = 0 - const val RENDERMODE_CONTINUOUSLY = 1 } - /** - * Abstract engine that supports OpenGL ES rendering. - * Subclasses should override onCreateEngine() to return an instance. - */ abstract inner class GLEngine : Engine() { - private var glThread: GLThread? = null + @Volatile private var glThread: GLThread? = null private var renderer: GLSurfaceView.Renderer? = null - private var eglContextClientVersion = 2 - private var internalRenderMode = RENDERMODE_WHEN_DIRTY - - // EGL configuration - private var eglConfigChooser: EGLConfigChooser? = null - /** * Set the renderer for this engine. * Must be called before surface is created. @@ -47,68 +36,19 @@ abstract class GLWallpaperService : WallpaperService() { this.renderer = renderer } - /** - * Set the OpenGL ES context client version (2 or 3). - * Must be called before surface is created. - */ - fun setEGLContextClientVersion(version: Int) { - this.eglContextClientVersion = version - } - - - /** - * Simplified EGL config chooser for RGB888 with no depth/stencil. - */ - fun setEGLConfigChooser( - redSize: Int, - greenSize: Int, - blueSize: Int, - alphaSize: Int, - depthSize: Int, - stencilSize: Int - ) { - this.eglConfigChooser = SimpleEGLConfigChooser( - redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize, eglContextClientVersion - ) - } - - /** - * Set the render mode: RENDERMODE_WHEN_DIRTY or RENDERMODE_CONTINUOUSLY. - */ - fun setRenderMode(mode: Int) { - this.internalRenderMode = mode - } - - /** - * Request a render. Only has effect if render mode is RENDERMODE_WHEN_DIRTY. - */ fun requestRender() { glThread?.requestRender() } - /** - * Queue a runnable to be run on the GL thread. - */ - fun queueEvent(runnable: Runnable) { - glThread?.queueEvent(runnable) - } + fun queueEvent(runnable: Runnable): Boolean = glThread?.queueEvent(runnable) ?: false override fun onSurfaceCreated(holder: SurfaceHolder) { super.onSurfaceCreated(holder) - val configChooser = eglConfigChooser ?: SimpleEGLConfigChooser( - 8, 8, 8, 0, 0, 0, eglContextClientVersion - ) - glThread = GLThread( holder = holder, - renderer = renderer ?: throw IllegalStateException("Renderer not set"), - configChooser = configChooser, - eglContextClientVersion = eglContextClientVersion - ).apply { - renderMode = this@GLEngine.internalRenderMode - start() - } + renderer = checkNotNull(renderer) { "Renderer not set" } + ).apply { start() } } override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { @@ -138,35 +78,23 @@ abstract class GLWallpaperService : WallpaperService() { } } - /** - * GL rendering thread. - */ private class GLThread( private val holder: SurfaceHolder, - private val renderer: GLSurfaceView.Renderer, - private val configChooser: EGLConfigChooser, - private val eglContextClientVersion: Int + private val renderer: GLSurfaceView.Renderer ) : Thread("GLThread") { - @Volatile var renderMode = RENDERMODE_WHEN_DIRTY - - // LinkedBlockingQueue is thread-safe — no explicit synchronization needed. - // Using a single lock for render signalling eliminates the previous AB-BA deadlock - // where the GL thread held `lock` while acquiring `eventQueue`, and callers held - // `eventQueue` while trying to acquire `lock` in requestRender(). - private val eventQueue = LinkedBlockingQueue() + private val eventQueue = ArrayDeque() // java.lang.Object is intentional: this monitor uses wait()/notifyAll(), which // Kotlin's Any does not expose directly. @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") private val lock = Object() - @Volatile private var shouldExit = false - @Volatile private var paused = false - @Volatile private var hasSurface = true - @Volatile private var width = 0 - @Volatile private var height = 0 - @Volatile private var requestRender = true - @Volatile private var sizeChanged = true + private var shouldExit = false + private var paused = false + private var width = 0 + private var height = 0 + private var requestRender = true + private var sizeChanged = true private var egl: EGL10? = null private var eglDisplay: EGLDisplay? = null @@ -181,9 +109,12 @@ abstract class GLWallpaperService : WallpaperService() { } } - fun queueEvent(runnable: Runnable) { + fun queueEvent(runnable: Runnable): Boolean = synchronized(lock) { + if (shouldExit) return false eventQueue.add(runnable) - requestRender() + requestRender = true + lock.notifyAll() + true } fun onWindowResize(width: Int, height: Int) { @@ -229,57 +160,49 @@ abstract class GLWallpaperService : WallpaperService() { while (true) { var event: Runnable? = null + var newSize: Pair? = null synchronized(lock) { while (true) { - if (shouldExit) { - cleanupGL() - return - } - - // Process events — LinkedBlockingQueue.poll() is non-blocking and thread-safe - val polled = eventQueue.poll() + val polled = eventQueue.removeFirstOrNull() if (polled != null) { event = polled break } - // Check if we should render - val readyToDraw = hasSurface && !paused - if (readyToDraw && (renderMode == RENDERMODE_CONTINUOUSLY || requestRender)) { + // Drain accepted events (including renderer cleanup) before releasing EGL. + if (shouldExit) return + + if (!paused && width > 0 && height > 0 && requestRender) { requestRender = false + if (sizeChanged) { + newSize = width to height + sizeChanged = false + } break } - // Wait for event lock.wait() } } - // Execute event event?.let { it.run() continue } - // Handle size change - if (sizeChanged) { + newSize?.let { (width, height) -> gl?.let { renderer.onSurfaceChanged(it, width, height) } - sizeChanged = false } - // Render frame gl?.let { renderer.onDrawFrame(it) } - // Swap buffers egl?.let { eglInstance -> if (!eglInstance.eglSwapBuffers(eglDisplay, eglSurface)) { Log.w(TAG, "eglSwapBuffers failed") } } - // Yield to avoid hogging CPU - sleep(1) } } catch (e: Exception) { Log.e(TAG, "GL thread error", e) @@ -301,11 +224,10 @@ abstract class GLWallpaperService : WallpaperService() { throw RuntimeException("eglInitialize failed") } - val eglConfig = configChooser.chooseConfig(egl!!, eglDisplay!!) + val eglConfig = WallpaperEglConfigChooser().chooseConfig(egl!!, eglDisplay!!) val attribList = intArrayOf( - 0x3098, // EGL_CONTEXT_CLIENT_VERSION - eglContextClientVersion, + EGL14.EGL_CONTEXT_CLIENT_VERSION, Constants.GL_ES_VERSION, EGL10.EGL_NONE ) @@ -363,103 +285,27 @@ abstract class GLWallpaperService : WallpaperService() { } } - /** - * Interface for choosing EGL configuration. - */ - interface EGLConfigChooser { - fun chooseConfig(egl: EGL10, display: EGLDisplay): EGLConfig - } +} - /** - * Enhanced EGL config chooser with multiple fallback options. - * Tries progressively simpler configurations to maximize compatibility - * across different GPU vendors (Adreno, Mali, PowerVR, etc.) - */ - private class SimpleEGLConfigChooser( - private val redSize: Int, - private val greenSize: Int, - private val blueSize: Int, - private val alphaSize: Int, - private val depthSize: Int, - private val stencilSize: Int, - private val eglContextClientVersion: Int - ) : EGLConfigChooser { - - override fun chooseConfig(egl: EGL10, display: EGLDisplay): EGLConfig { - val renderableType = if (eglContextClientVersion >= 3) { - 0x0040 // EGL_OPENGL_ES3_BIT - } else { - 0x0004 // EGL_OPENGL_ES2_BIT - } - - // Log device info for debugging - GLCompatibility.logDeviceInfo() - - // Build list of configs to try in order of preference - val configSpecs = mutableListOf() - - // Config 1: Full spec with EGL_RENDERABLE_TYPE (most common/preferred) - configSpecs.add(intArrayOf( - EGL10.EGL_RED_SIZE, redSize, - EGL10.EGL_GREEN_SIZE, greenSize, - EGL10.EGL_BLUE_SIZE, blueSize, - EGL10.EGL_ALPHA_SIZE, alphaSize, - EGL10.EGL_DEPTH_SIZE, depthSize, - EGL10.EGL_STENCIL_SIZE, stencilSize, - 0x3142, renderableType, // EGL_RENDERABLE_TYPE - EGL10.EGL_NONE - )) - - // Config 2: Without EGL_RENDERABLE_TYPE (older devices) - configSpecs.add(intArrayOf( - EGL10.EGL_RED_SIZE, redSize, - EGL10.EGL_GREEN_SIZE, greenSize, - EGL10.EGL_BLUE_SIZE, blueSize, - EGL10.EGL_ALPHA_SIZE, alphaSize, - EGL10.EGL_DEPTH_SIZE, depthSize, - EGL10.EGL_STENCIL_SIZE, stencilSize, - EGL10.EGL_NONE - )) - - // Config 3: RGB565 (no alpha) - Mali GPU fallback - if (GLCompatibility.isLowEndGPU()) { - configSpecs.add(intArrayOf( - EGL10.EGL_RED_SIZE, 5, - EGL10.EGL_GREEN_SIZE, 6, - EGL10.EGL_BLUE_SIZE, 5, - EGL10.EGL_ALPHA_SIZE, 0, - EGL10.EGL_DEPTH_SIZE, 0, - EGL10.EGL_STENCIL_SIZE, 0, - EGL10.EGL_NONE - )) - Log.d(TAG, "Added RGB565 fallback config for low-end GPU") - } - - // Config 4: Minimal config (last resort) - configSpecs.add(intArrayOf( +internal class WallpaperEglConfigChooser : GLSurfaceView.EGLConfigChooser { + override fun chooseConfig(egl: EGL10, display: EGLDisplay): EGLConfig { + val colorSpecs = listOf( + intArrayOf(EGL10.EGL_RED_SIZE, 8, EGL10.EGL_GREEN_SIZE, 8, EGL10.EGL_BLUE_SIZE, 8), + intArrayOf(EGL10.EGL_RED_SIZE, 5, EGL10.EGL_GREEN_SIZE, 6, EGL10.EGL_BLUE_SIZE, 5), + intArrayOf() + ) + val configs = arrayOfNulls(1) + val count = IntArray(1) + for (colors in colorSpecs) { + val attributes = colors + intArrayOf( EGL10.EGL_SURFACE_TYPE, EGL10.EGL_WINDOW_BIT, + EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE - )) - - val numConfig = IntArray(1) - - for ((index, configSpec) in configSpecs.withIndex()) { - if (egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) { - if (numConfig[0] > 0) { - val configs = arrayOfNulls(numConfig[0]) - if (egl.eglChooseConfig(display, configSpec, configs, numConfig[0], numConfig)) { - val config = configs[0] - if (config != null) { - Log.d(TAG, "EGL config chosen using fallback level $index") - return config - } - } - } - } - Log.w(TAG, "EGL config fallback $index failed, trying next...") + ) + if (egl.eglChooseConfig(display, attributes, configs, 1, count) && count[0] > 0) { + return checkNotNull(configs[0]) } - - throw RuntimeException("No compatible EGL config found after all fallbacks") } + error("No compatible OpenGL ES 2 window config") } } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt index 060bc63..66d0965 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt @@ -7,10 +7,6 @@ import java.nio.FloatBuffer import kotlin.math.max import kotlin.math.min -/** - * Geometry utilities for OpenGL rendering including vertex positions, - * texture coordinates, and adaptive parallax calculations. - */ object GLGeometry { data class WallpaperTransform( @@ -38,9 +34,6 @@ object GLGeometry { return CrossfadeAlphas(current = 1f, next = nextAlpha) } - /** - * Calculate live-wallpaper scale and launcher-scroll offset without OpenGL dependencies. - */ fun calculateWallpaperTransform( viewWidth: Float, viewHeight: Float, @@ -116,15 +109,6 @@ object GLGeometry { 1.0f, 0.0f // Top-right ) - - - /** - * Create a native-order FloatBuffer from a float array. - * Required for passing vertex data to OpenGL. - * - * @param data Float array to convert - * @return FloatBuffer ready for use with OpenGL - */ fun createFloatBuffer(data: FloatArray): FloatBuffer { return ByteBuffer.allocateDirect(data.size * 4) .order(ByteOrder.nativeOrder()) @@ -134,17 +118,4 @@ object GLGeometry { position(0) } } - - /** - * Update an existing FloatBuffer with new data. - * More efficient than creating a new buffer. - * - * @param buffer Buffer to update - * @param data New data to put in buffer - */ - fun updateFloatBuffer(buffer: FloatBuffer, data: FloatArray) { - buffer.clear() - buffer.put(data) - buffer.position(0) - } } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt index 10b5a9d..9ca4e79 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt @@ -1,15 +1,7 @@ package com.anthonyla.paperize.service.livewallpaper.renderer -/** - * GLSL shader programs for live wallpaper rendering. - * Includes vertex shaders and fragment shaders for two-pass blur and color effects. - */ object GLShaders { - /** - * Simple vertex shader that passes through positions and texture coordinates. - * Used for all rendering passes. - */ const val VERTEX_SHADER = """ uniform mat4 u_mvpMatrix; attribute vec4 a_position; @@ -28,97 +20,40 @@ object GLShaders { """ /** - * Simple fragment shader for basic texture rendering without effects. - * Used for testing or when no effects are enabled. - */ - const val SIMPLE_FRAGMENT_SHADER = """ - precision mediump float; - uniform sampler2D u_texture; - uniform float u_alpha; - varying vec2 v_texCoord; - - void main() { - vec4 color = texture2D(u_texture, v_texCoord); - gl_FragColor = vec4(color.rgb, color.a * u_alpha); - } - """ - - /** - * Fragment shader for horizontal Gaussian blur pass. + * Fragment shader for directional Gaussian blur pass. * Uses 17-tap kernel (half-integer steps) to eliminate banding/ghosting at high blur radii. * Weights are pre-computed for sigma ~= 1.815 sampled at {0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4} steps. * Branchless: when blurRadius is 0, all offsets are 0 so all samples collapse to center. */ - const val BLUR_HORIZONTAL_FRAGMENT_SHADER = """ + const val BLUR_FRAGMENT_SHADER = """ precision mediump float; uniform sampler2D u_texture; uniform vec2 u_resolution; + uniform vec2 u_direction; uniform float u_blurRadius; varying vec2 v_texCoord; void main() { - vec2 pixelSize = 1.0 / u_resolution; - float r = u_blurRadius; + vec2 stepSize = u_direction * u_blurRadius / u_resolution; - // 17-tap Gaussian (half-integer steps: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0) - // Doubles sampling density vs 9-tap to eliminate aliasing at high blur radii vec4 color = texture2D(u_texture, v_texCoord) * 0.1120; - color += (texture2D(u_texture, v_texCoord + vec2(-0.5 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 0.5 * pixelSize.x * r, 0.0))) * 0.1078; - color += (texture2D(u_texture, v_texCoord + vec2(-1.0 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 1.0 * pixelSize.x * r, 0.0))) * 0.0962; - color += (texture2D(u_texture, v_texCoord + vec2(-1.5 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 1.5 * pixelSize.x * r, 0.0))) * 0.0796; - color += (texture2D(u_texture, v_texCoord + vec2(-2.0 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 2.0 * pixelSize.x * r, 0.0))) * 0.0610; - color += (texture2D(u_texture, v_texCoord + vec2(-2.5 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 2.5 * pixelSize.x * r, 0.0))) * 0.0434; - color += (texture2D(u_texture, v_texCoord + vec2(-3.0 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 3.0 * pixelSize.x * r, 0.0))) * 0.0286; - color += (texture2D(u_texture, v_texCoord + vec2(-3.5 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 3.5 * pixelSize.x * r, 0.0))) * 0.0175; - color += (texture2D(u_texture, v_texCoord + vec2(-4.0 * pixelSize.x * r, 0.0)) + - texture2D(u_texture, v_texCoord + vec2( 4.0 * pixelSize.x * r, 0.0))) * 0.0099; - - gl_FragColor = color; - } - """ - - /** - * Fragment shader for vertical Gaussian blur pass. - * Uses 17-tap kernel matching the horizontal pass. - */ - const val BLUR_VERTICAL_FRAGMENT_SHADER = """ - precision mediump float; - uniform sampler2D u_texture; - uniform vec2 u_resolution; - uniform float u_blurRadius; - varying vec2 v_texCoord; - - void main() { - vec2 pixelSize = 1.0 / u_resolution; - float r = u_blurRadius; - - // 17-tap Gaussian (half-integer steps: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0) - vec4 color = texture2D(u_texture, v_texCoord) * 0.1120; - - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -0.5 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 0.5 * pixelSize.y * r))) * 0.1078; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.0 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 1.0 * pixelSize.y * r))) * 0.0962; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.5 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 1.5 * pixelSize.y * r))) * 0.0796; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.0 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 2.0 * pixelSize.y * r))) * 0.0610; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.5 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 2.5 * pixelSize.y * r))) * 0.0434; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.0 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 3.0 * pixelSize.y * r))) * 0.0286; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.5 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 3.5 * pixelSize.y * r))) * 0.0175; - color += (texture2D(u_texture, v_texCoord + vec2(0.0, -4.0 * pixelSize.y * r)) + - texture2D(u_texture, v_texCoord + vec2(0.0, 4.0 * pixelSize.y * r))) * 0.0099; + color += (texture2D(u_texture, v_texCoord + (-0.5 * stepSize)) + + texture2D(u_texture, v_texCoord + (0.5 * stepSize))) * 0.1078; + color += (texture2D(u_texture, v_texCoord + (-1.0 * stepSize)) + + texture2D(u_texture, v_texCoord + (1.0 * stepSize))) * 0.0962; + color += (texture2D(u_texture, v_texCoord + (-1.5 * stepSize)) + + texture2D(u_texture, v_texCoord + (1.5 * stepSize))) * 0.0796; + color += (texture2D(u_texture, v_texCoord + (-2.0 * stepSize)) + + texture2D(u_texture, v_texCoord + (2.0 * stepSize))) * 0.0610; + color += (texture2D(u_texture, v_texCoord + (-2.5 * stepSize)) + + texture2D(u_texture, v_texCoord + (2.5 * stepSize))) * 0.0434; + color += (texture2D(u_texture, v_texCoord + (-3.0 * stepSize)) + + texture2D(u_texture, v_texCoord + (3.0 * stepSize))) * 0.0286; + color += (texture2D(u_texture, v_texCoord + (-3.5 * stepSize)) + + texture2D(u_texture, v_texCoord + (3.5 * stepSize))) * 0.0175; + color += (texture2D(u_texture, v_texCoord + (-4.0 * stepSize)) + + texture2D(u_texture, v_texCoord + (4.0 * stepSize))) * 0.0099; gl_FragColor = color; } @@ -142,7 +77,6 @@ object GLShaders { void main() { vec4 color = texture2D(u_texture, v_texCoord); - // 1. Apply darken (branchless - when factor is 0, multiplier is 1.0) color.rgb *= (1.0 - u_darkenFactor); // 2. Apply vignette — matches CPU vignetteBitmap gradient stops: @@ -151,9 +85,7 @@ object GLShaders { vec2 vignetteCenter = v_imageCoord - 0.5; float dist = length(vignetteCenter); float t = clamp(dist / 0.5, 0.0, 1.0); - // Inner segment: 0% → 10% over [0, 0.7] float innerDark = smoothstep(0.0, 0.7, t) * 0.1; - // Outer segment: 10% → 80% over [0.7, 1.0] float outerDark = smoothstep(0.7, 1.0, t) * 0.7; float darkAmount = innerDark + outerDark; color.rgb *= (1.0 - darkAmount * u_vignetteFactor); @@ -163,22 +95,10 @@ object GLShaders { float gray = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722)); color.rgb = mix(color.rgb, vec3(gray), u_grayscaleFactor); - // 4. Apply adaptive brightness multiplier color.rgb *= u_adaptiveBrightnessFactor; gl_FragColor = vec4(color.rgb, color.a * u_alpha); } """ - /** - * Solid color fragment shader for debugging and UI overlays. - */ - const val COLOR_FRAGMENT_SHADER = """ - precision mediump float; - uniform vec4 u_color; - - void main() { - gl_FragColor = u_color; - } - """ } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt index 6e250d2..ba576f1 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt @@ -5,119 +5,38 @@ import android.graphics.Bitmap import android.graphics.ImageDecoder import android.net.Uri import android.util.Log -import androidx.compose.ui.util.fastRoundToInt import com.anthonyla.paperize.core.ScalingType -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext +import com.anthonyla.paperize.core.util.calculateDecodeSize -/** - * Sealed interface for loading images from different sources. - * Provides type-safe abstraction for image loading with automatic - * sample size calculation and memory optimization. - */ sealed interface ImageLoader { - - /** - * Load the image as a Bitmap with the specified target dimensions. - * The image will be downsampled to approximately match the target size. - * - * @param targetWidth Target width in pixels - * @param targetHeight Target height in pixels - * @return Loaded bitmap, or null if loading failed - */ - suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? + /** Decode on a worker thread. The caller owns the returned bitmap. */ + fun load(targetWidth: Int, targetHeight: Int): Bitmap? } -/** - * Empty image loader that always returns null. - * Used as a null object pattern when no wallpaper is available. - */ object EmptyImageLoader : ImageLoader { - override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? = null + override fun load(targetWidth: Int, targetHeight: Int): Bitmap? = null } -/** - * Image loader for Android content URIs. - * Loads images from the MediaStore or other content providers. - * - * @property contentResolver Content resolver for URI access - * @property uri Content URI to load - * @property scalingType How the image will be scaled for display - */ class ContentUriImageLoader( private val contentResolver: ContentResolver, private val uri: Uri, private val scalingType: ScalingType = ScalingType.FILL ) : ImageLoader { - - companion object { - private const val TAG = "ContentUriImageLoader" - } - - override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? { - return withContext(Dispatchers.IO) { - try { - // ImageDecoder auto-applies EXIF orientation; info.size returns post-EXIF (display) - // dimensions. Computing decodeWidth/decodeHeight inside the lambda from info.size - // ensures correct aspect-ratio math regardless of EXIF rotation metadata. - val source = ImageDecoder.createSource(contentResolver, uri) - val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ -> - val srcWidth = info.size.width - val srcHeight = info.size.height - - val (decodeWidth, decodeHeight) = when (scalingType) { - ScalingType.FILL -> { - val scale = maxOf( - targetWidth.toFloat() / srcWidth, - targetHeight.toFloat() / srcHeight - ) - Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt()) - } - ScalingType.FIT -> { - val scale = minOf( - targetWidth.toFloat() / srcWidth, - targetHeight.toFloat() / srcHeight - ) - Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt()) - } - ScalingType.STRETCH -> Pair(targetWidth, targetHeight) - ScalingType.NONE -> { - // Cap at 2× screen size to prevent OOM on very large source images - val maxW = targetWidth * 2 - val maxH = targetHeight * 2 - if (srcWidth > maxW || srcHeight > maxH) { - val scale = minOf(maxW.toFloat() / srcWidth, maxH.toFloat() / srcHeight) - Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt()) - } else { - Pair(srcWidth, srcHeight) - } - } - } - - Log.d(TAG, "Loading image: ${srcWidth}x${srcHeight} -> ${decodeWidth}x${decodeHeight} " + - "(scaling: $scalingType, target: ${targetWidth}x${targetHeight})") - - decoder.setTargetSize(decodeWidth, decodeHeight) - decoder.isMutableRequired = false // Immutable for GPU upload - decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE - } - - // Validate loaded bitmap - if (bitmap.width <= 0 || bitmap.height <= 0) { - Log.e(TAG, "Loaded bitmap has invalid dimensions: ${bitmap.width}x${bitmap.height}") - bitmap.recycle() - return@withContext null - } - - bitmap - } catch (e: Exception) { - Log.e(TAG, "Failed to load image from $uri", e) - null - } catch (e: OutOfMemoryError) { - Log.e(TAG, "OOM loading image from $uri", e) - null - } + override fun load(targetWidth: Int, targetHeight: Int): Bitmap? = try { + val source = ImageDecoder.createSource(contentResolver, uri) + ImageDecoder.decodeBitmap(source) { decoder, info, _ -> + // ImageDecoder reports dimensions after applying EXIF orientation. + val (width, height) = calculateDecodeSize( + info.size.width, info.size.height, targetWidth, targetHeight, scalingType + ) + decoder.setTargetSize(width, height) + decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE } + } catch (e: Exception) { + Log.e("ContentUriImageLoader", "Failed to load image from $uri", e) + null + } catch (e: OutOfMemoryError) { + Log.e("ContentUriImageLoader", "OOM loading image from $uri", e) + null } - } diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt index 63b79bc..3f9156a 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt @@ -1,8 +1,6 @@ package com.anthonyla.paperize.service.livewallpaper.renderer import android.util.Log -import androidx.lifecycle.DefaultLifecycleObserver -import androidx.lifecycle.LifecycleOwner import com.anthonyla.paperize.core.constants.Constants import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -10,177 +8,64 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch -/** - * Abstract controller for managing wallpaper loading and rendering lifecycle. - * Handles visibility changes, load orchestration, and coordination between - * background loading and GL thread rendering. - */ -abstract class PaperizeRenderController( - private val renderer: PaperizeWallpaperRenderer, - private val callbacks: Callbacks, - private val controllerScope: CoroutineScope -) : DefaultLifecycleObserver { - - companion object { - private const val TAG = "PaperizeRenderController" - private const val RELOAD_THROTTLE_MS = Constants.RELOAD_THROTTLE_MS - } - - /** - * Callbacks for GL thread operations. - */ - interface Callbacks { - fun queueEventOnGlThread(event: () -> Unit) - fun requestRender() - } - - @Volatile - var visible: Boolean = false +/** All calls run on the engine's main dispatcher; its scope owns cancellation. */ +class PaperizeRenderController( + private val queueWallpaper: (ImageLoader, Boolean) -> Unit, + private val controllerScope: CoroutineScope, + private val openCurrentArtwork: suspend () -> ImageLoader +) { + var visible = false set(value) { field = value - if (value) { - // When becoming visible, execute any pending reload - if (hasPendingReload) { - hasPendingReload = false - reloadCurrentArtwork(ReloadImmediate) - } - } + if (value && hasPendingReload) reloadCurrentArtwork(immediate = true) } - @Volatile private var isLoading = false - - @Volatile private var hasPendingReload = false - private var throttleJob: Job? = null - /** - * Abstract method to open the current wallpaper for loading. - * Implemented by the service to integrate with queue system. - * - * @return ImageLoader for the current wallpaper - */ - protected abstract suspend fun openDownloadedCurrentArtwork(): ImageLoader - - /** - * Reload the current wallpaper. - * - * @param reason Reload reason (immediate or queued) - */ - fun reloadCurrentArtwork(reason: ReloadReason = ReloadQueued) { - Log.d(TAG, "reloadCurrentArtwork: reason=$reason, visible=$visible, loading=$isLoading") - - // If not visible, defer reload until visible - if (!visible) { + fun reloadCurrentArtwork(immediate: Boolean = false) { + if (!visible || isLoading) { hasPendingReload = true return } - // If already loading, skip - if (isLoading) { - Log.d(TAG, "Already loading, skipping reload") - return - } - - when (reason) { - is ReloadImmediate -> { - // Cancel any throttled reload and execute immediately - throttleJob?.cancel() - executeReload() - } - is ReloadQueued -> { - // Throttle reloads to avoid excessive processing - throttleJob?.cancel() - throttleJob = controllerScope.launch { - delay(RELOAD_THROTTLE_MS) - executeReload() - } + hasPendingReload = false + throttleJob?.cancel() + if (immediate) { + executeReload() + } else { + throttleJob = controllerScope.launch { + delay(Constants.RELOAD_THROTTLE_MS) + if (visible) executeReload() else hasPendingReload = true } } } - /** - * Force reload the current wallpaper, bypassing visibility check. - * Used for screen-off wallpaper changes where we want to load - * the next wallpaper while the screen is dark. - * Skips crossfade animation since screen is off and animation wouldn't be visible. - */ + /** Prepare the next wallpaper while the screen is dark, without crossfading. */ fun forceReloadCurrentArtwork() { - Log.d(TAG, "forceReloadCurrentArtwork: visible=$visible, loading=$isLoading") - - // Clear any pending reload since we're forcing a reload now + if (isLoading) return hasPendingReload = false - - // If already loading, skip - if (isLoading) { - Log.d(TAG, "Already loading, skipping force reload") - return - } - throttleJob?.cancel() - // Skip crossfade since screen is off - wallpaper will appear instantly when screen turns on executeReload(skipCrossfade = true) } - /** - * Execute wallpaper reload. - * - * @param skipCrossfade If true, skip crossfade animation and instantly swap wallpaper - */ private fun executeReload(skipCrossfade: Boolean = false) { isLoading = true - controllerScope.launch { try { - // Get image loader from service - val loader = openDownloadedCurrentArtwork() - - // Check for cancellation before passing to renderer - if (!isActive) return@launch - - // Queue wallpaper loading on renderer - // Renderer will load bitmap in background and upload to GPU on GL thread - renderer.queueWallpaper(loader, skipCrossfade) - - } catch (e: Exception) { - if (isActive) { - Log.e(TAG, "Error reloading wallpaper", e) + val loader = openCurrentArtwork() + if (isActive && !hasPendingReload) { + queueWallpaper(loader, skipCrossfade) } + } catch (e: Exception) { + if (isActive) Log.e("PaperizeRenderController", "Error reloading wallpaper", e) } finally { isLoading = false + if (isActive && hasPendingReload && visible) { + reloadCurrentArtwork(immediate = true) + } } } } - - override fun onStart(owner: LifecycleOwner) { - Log.d(TAG, "onStart") - // Lifecycle started - ready for operation - } - - override fun onStop(owner: LifecycleOwner) { - Log.d(TAG, "onStop") - // Lifecycle stopped - pause operations - throttleJob?.cancel() - } - - override fun onDestroy(owner: LifecycleOwner) { - Log.d(TAG, "onDestroy") - throttleJob?.cancel() - } } - -/** - * Sealed class representing reload reason. - */ -sealed class ReloadReason - -/** - * Immediate reload (triggered by user action like double-tap or broadcast). - */ -object ReloadImmediate : ReloadReason() - -/** - * Queued reload (throttled to avoid excessive processing). - */ -object ReloadQueued : ReloadReason() diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt index 69d23b2..8abaccd 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt @@ -14,23 +14,19 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.isActive import kotlinx.coroutines.Job import kotlinx.coroutines.CancellationException import java.nio.FloatBuffer +import java.util.concurrent.atomic.AtomicLong import android.opengl.Matrix import javax.microedition.khronos.egl.EGLConfig import javax.microedition.khronos.opengles.GL10 -/** - * Main OpenGL renderer for live wallpaper. - * Handles texture rendering, two-pass blur effects, color effects, - * crossfade animations, and parallax scrolling. - * - * @property context Application context - * @property callbacks Callbacks for queuing events on GL thread - */ class PaperizeWallpaperRenderer( private val context: Context, private val callbacks: Callbacks @@ -38,32 +34,21 @@ class PaperizeWallpaperRenderer( companion object { private const val TAG = "PaperizeRenderer" - // Time-based crossfade duration in milliseconds (consistent across all refresh rates) private const val CROSSFADE_DURATION_MS = Constants.CROSSFADE_DURATION_MS } - /** - * Callbacks for communication with the engine. - */ interface Callbacks { - fun queueEventOnGlThread(event: () -> Unit) + fun queueEventOnGlThread(event: () -> Unit): Boolean fun requestRender() } - // Surface dimensions - @Volatile private var surfaceWidth = 0 - @Volatile private var surfaceHeight = 0 + private val surfaceSize = MutableStateFlow?>(null) + private val surfaceWidth get() = surfaceSize.value?.first ?: 0 + private val surfaceHeight get() = surfaceSize.value?.second ?: 0 - // Display refresh rate (for future optimizations) - private var displayRefreshRate = 60f - - // Shader programs - private var simpleProgram = 0 - private var blurHorizontalProgram = 0 - private var blurVerticalProgram = 0 + private var blurProgram = 0 private var effectsProgram = 0 - // Attribute/uniform locations (for effects program) private var aPositionHandle = 0 private var aTexCoordHandle = 0 private var uTextureHandle = 0 @@ -74,84 +59,68 @@ class PaperizeWallpaperRenderer( private var uGrayscaleFactorHandle = 0 private var uAdaptiveBrightnessFactorHandle = 0 - // Cached uniform locations for horizontal blur program - private var blurHPositionHandle = 0 - private var blurHTexCoordHandle = 0 - private var blurHMvpMatrixHandle = 0 - private var blurHTextureHandle = 0 - private var blurHResolutionHandle = 0 - private var blurHRadiusHandle = 0 + private var blurPositionHandle = 0 + private var blurTexCoordHandle = 0 + private var blurMvpMatrixHandle = 0 + private var blurTextureHandle = 0 + private var blurResolutionHandle = 0 + private var blurRadiusHandle = 0 + private var blurDirectionHandle = 0 - // Cached uniform locations for vertical blur program - private var blurVPositionHandle = 0 - private var blurVTexCoordHandle = 0 - private var blurVMvpMatrixHandle = 0 - private var blurVTextureHandle = 0 - private var blurVResolutionHandle = 0 - private var blurVRadiusHandle = 0 - - // Geometry buffers private lateinit var vertexBuffer: FloatBuffer private lateinit var texCoordBuffer: FloatBuffer - // Framebuffers for two-pass blur (need two for proper blur + effects pipeline) private var blurFbo1 = 0 private var blurTexture1 = 0 private var blurFbo2 = 0 private var blurTexture2 = 0 - // Current wallpaper private var currentPicture: GLPicture? = null - // Crossfade state (time-based) private var nextPicture: GLPicture? = null - private var crossfadeProgress = 0f private var crossfadeStartTimeNanos = 0L - // Effects @Volatile private var currentEffects = WallpaperEffects() - // Parallax @Volatile private var normalOffsetX = 0.5f - // Scaling @Volatile private var currentScalingType = ScalingType.FILL - // Adaptive brightness (from ScheduleSettings) @Volatile private var adaptiveBrightnessEnabled = false - // Retain the current source so a fold/unfold or other surface-size change can - // decode the same wallpaper again at the new native resolution. - @Volatile private var currentImageLoader: ImageLoader? = null + // Retain the latest request, including images still decoding or waiting for upload, + // so a fold/unfold cannot replace it with the previously displayed wallpaper. + private var requestedImageLoader: ImageLoader? = null - // Matrices private val mvpMatrix = FloatArray(16) - private val projectionMatrix = FloatArray(16) - private val viewMatrix = FloatArray(16) private val identityMatrix = FloatArray(16) - // Coroutine scope for background loading private val loadingScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private var currentLoadJob: Job? = null + private val loadGeneration = AtomicLong() override fun onSurfaceCreated(gl: GL10, config: EGLConfig) { Log.d(TAG, "onSurfaceCreated") - // Set clear color + // A recreated surface has a new EGL context; old handles no longer belong to it. + surfaceSize.value = null + currentPicture = null + nextPicture = null + blurFbo1 = 0 + blurFbo2 = 0 + blurTexture1 = 0 + blurTexture2 = 0 + GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) - // Enable blending for crossfade GLES20.glEnable(GLES20.GL_BLEND) GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA) - // Compile shader programs compileShaders() - // Create geometry buffers vertexBuffer = GLGeometry.createFloatBuffer(GLGeometry.VERTICES) texCoordBuffer = GLGeometry.createFloatBuffer(GLGeometry.TEX_COORDS) - // Initialize identity matrix Matrix.setIdentityM(identityMatrix, 0) Log.d(TAG, "Surface created successfully") @@ -164,27 +133,24 @@ class PaperizeWallpaperRenderer( surfaceWidth > 0 && surfaceHeight > 0 && (surfaceWidth != width || surfaceHeight != height) - surfaceWidth = width - surfaceHeight = height + surfaceSize.value = width to height GLES20.glViewport(0, 0, width, height) - // Recreate framebuffers for blur at new resolution - createBlurFramebuffers(width, height) + deleteBlurResources() - if (sizeChanged) { - currentImageLoader?.let { loader -> - Log.d(TAG, "Surface size changed; reloading current wallpaper at ${width}x${height}") - queueWallpaper(loader, skipCrossfade = true) + if (sizeChanged || currentPicture == null) { + synchronized(this) { + requestedImageLoader?.let { loader -> + queueWallpaper(loader, skipCrossfade = true) + } } } } override fun onDrawFrame(gl: GL10) { - // Clear screen GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) - // Prevent division by zero in shaders if surface dimensions are invalid if (surfaceWidth <= 0 || surfaceHeight <= 0) { return } @@ -193,18 +159,22 @@ class PaperizeWallpaperRenderer( val next = nextPicture if (current == null && next == null) { - // No wallpaper to display return } - // Determine if we need blur val blurRadius = if (currentEffects.enableBlur) { (currentEffects.blurPercentage / 100.0f) * Constants.MAX_BLUR_RADIUS } else { 0f } - // Draw current picture + val crossfadeProgress = if (next != null) { + val elapsedMs = (System.nanoTime() - crossfadeStartTimeNanos) / 1_000_000f + (elapsedMs / CROSSFADE_DURATION_MS).coerceIn(0f, 1f) + } else { + 0f + } + val crossfadeAlphas = GLGeometry.calculateCrossfadeAlphas( progress = crossfadeProgress, hasNextPicture = next != null @@ -214,49 +184,28 @@ class PaperizeWallpaperRenderer( drawPictureWithEffects(picture, crossfadeAlphas.current, blurRadius) } - // Draw next picture (if crossfading) next?.let { picture -> - // Safety: If crossfade just started but timer wasn't set, set it now - if (crossfadeStartTimeNanos == 0L) { - crossfadeStartTimeNanos = System.nanoTime() - } - - // Draw next picture with its own alpha drawPictureWithEffects(picture, crossfadeAlphas.next, blurRadius) - // Update crossfade progress using time-based calculation - // This ensures consistent animation duration regardless of refresh rate (60Hz, 90Hz, 120Hz, etc.) - val currentTimeNanos = System.nanoTime() - val elapsedMs = (currentTimeNanos - crossfadeStartTimeNanos) / 1_000_000f - crossfadeProgress = (elapsedMs / CROSSFADE_DURATION_MS).coerceIn(0f, 1f) - if (crossfadeProgress >= 1.0f) { - // Crossfade complete currentPicture?.recycle() currentPicture = picture nextPicture = null - crossfadeProgress = 0f + crossfadeStartTimeNanos = 0L Log.d(TAG, "Crossfade complete") } else { - // Continue animating callbacks.requestRender() } } } - /** - * Draw a picture with full effects pipeline. - */ private fun drawPictureWithEffects(picture: GLPicture, alpha: Float, blurRadius: Float) { - // Calculate MVP matrix for Center Crop + Parallax calculateMvpMatrix(picture, mvpMatrix) - if (blurRadius > Constants.BLUR_MIN_THRESHOLD && currentEffects.enableBlur) { - // Two-pass blur pipeline + if (blurRadius > Constants.BLUR_MIN_THRESHOLD) { drawWithBlur(picture, alpha, blurRadius) } else { - // No blur - direct render with color effects drawWithColorEffects(picture, alpha) } } @@ -268,57 +217,37 @@ class PaperizeWallpaperRenderer( * Pass 3: FBO2 texture → Color effects → Screen */ private fun drawWithBlur(picture: GLPicture, alpha: Float, blurRadius: Float) { + if (blurFbo1 == 0) createBlurFramebuffers(surfaceWidth, surfaceHeight) + // Pass 1: Horizontal blur (source → FBO1) GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo1) GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight) GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) - GLES20.glUseProgram(blurHorizontalProgram) - GLES20.glUniform2f(blurHResolutionHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat()) - GLES20.glUniform1f(blurHRadiusHandle, blurRadius) - GLES20.glUniform1i(blurHTextureHandle, 0) // Bind texture unit 0 + GLES20.glUseProgram(blurProgram) + GLES20.glUniform2f(blurDirectionHandle, 1f, 0f) + GLES20.glUniform2f(blurResolutionHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat()) + GLES20.glUniform1f(blurRadiusHandle, blurRadius) + GLES20.glUniform1i(blurTextureHandle, 0) // Bind texture unit 0 - picture.draw(blurHorizontalProgram, blurHPositionHandle, blurHTexCoordHandle, mvpMatrix, blurHMvpMatrixHandle) + picture.draw(blurProgram, blurPositionHandle, blurTexCoordHandle, mvpMatrix, blurMvpMatrixHandle) // Pass 2: Vertical blur (FBO1 → FBO2) GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo2) GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) - GLES20.glUseProgram(blurVerticalProgram) - GLES20.glUniform2f(blurVResolutionHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat()) - GLES20.glUniform1f(blurVRadiusHandle, blurRadius) - - // Bind horizontal blur result as input texture GLES20.glActiveTexture(GLES20.GL_TEXTURE0) GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture1) - GLES20.glUniform1i(blurVTextureHandle, 0) - // Draw full-screen quad for vertical blur pass (Identity matrix) - drawQuad(blurVPositionHandle, blurVTexCoordHandle, blurVMvpMatrixHandle, identityMatrix) + GLES20.glUniform2f(blurDirectionHandle, 0f, 1f) + drawQuad(blurPositionHandle, blurTexCoordHandle, blurMvpMatrixHandle, identityMatrix) // Pass 3: Color effects (FBO2 → Screen) GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0) GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight) - GLES20.glUseProgram(effectsProgram) + setEffectUniforms(picture, alpha) - // Set color effect uniforms - respect enable flags - GLES20.glUniform1f(uAlphaHandle, alpha) - GLES20.glUniform1f( - uDarkenFactorHandle, - if (currentEffects.enableDarken) currentEffects.darkenPercentage / Constants.PERCENTAGE_DIVISOR else 0f - ) - GLES20.glUniform1f( - uVignetteFactorHandle, - if (currentEffects.enableVignette) currentEffects.vignettePercentage / Constants.PERCENTAGE_DIVISOR else 0f - ) - GLES20.glUniform1f( - uGrayscaleFactorHandle, - if (currentEffects.enableGrayscale) currentEffects.grayscalePercentage / Constants.PERCENTAGE_DIVISOR else 0f - ) - GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, adaptiveBrightnessFactor(picture)) - - // Bind the fully blurred texture as input GLES20.glActiveTexture(GLES20.GL_TEXTURE0) GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture2) GLES20.glUniform1i(uTextureHandle, 0) @@ -326,14 +255,14 @@ class PaperizeWallpaperRenderer( drawQuad(aPositionHandle, aTexCoordHandle, uMvpMatrixHandle, identityMatrix) } - /** - * Draw picture with color effects only (no blur). - */ private fun drawWithColorEffects(picture: GLPicture, alpha: Float) { - // Render to screen with effects + setEffectUniforms(picture, alpha) + picture.draw(effectsProgram, aPositionHandle, aTexCoordHandle, mvpMatrix, uMvpMatrixHandle) + } + + private fun setEffectUniforms(picture: GLPicture, alpha: Float) { GLES20.glUseProgram(effectsProgram) - // Set uniforms - respect enable flags for all effects GLES20.glUniform1f(uAlphaHandle, alpha) GLES20.glUniform1f( uDarkenFactorHandle, @@ -349,23 +278,14 @@ class PaperizeWallpaperRenderer( ) GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, adaptiveBrightnessFactor(picture)) - picture.draw(effectsProgram, aPositionHandle, aTexCoordHandle, mvpMatrix, uMvpMatrixHandle) } - /** - * Calculate MVP matrix for Center Crop scaling and Parallax. - */ private fun calculateMvpMatrix(picture: GLPicture, matrix: FloatArray) { val viewWidth = surfaceWidth.toFloat() val viewHeight = surfaceHeight.toFloat() val imageWidth = picture.width.toFloat() val imageHeight = picture.height.toFloat() - if (viewWidth == 0f || viewHeight == 0f || imageWidth == 0f || imageHeight == 0f) { - Matrix.setIdentityM(matrix, 0) - return - } - val transform = GLGeometry.calculateWallpaperTransform( viewWidth = viewWidth, viewHeight = viewHeight, @@ -377,25 +297,9 @@ class PaperizeWallpaperRenderer( normalizedOffsetX = normalOffsetX ) - // 3. Construct Matrix - // We use an orthographic projection matching the screen dimensions - // Left: -width/2, Right: width/2, Bottom: -height/2, Top: height/2 - // This makes 0,0 the center of the screen - Matrix.orthoM(projectionMatrix, 0, -viewWidth / 2f, viewWidth / 2f, -viewHeight / 2f, viewHeight / 2f, -1f, 1f) - - // Set view matrix (camera) - identity is fine for 2D - Matrix.setIdentityM(viewMatrix, 0) - - // Combine Projection * View - Matrix.multiplyMM(matrix, 0, projectionMatrix, 0, viewMatrix, 0) - - // Apply Model transformations - // Translate for parallax + Matrix.orthoM(matrix, 0, -viewWidth / 2f, viewWidth / 2f, -viewHeight / 2f, viewHeight / 2f, -1f, 1f) Matrix.translateM(matrix, 0, transform.horizontalOffset, 0f, 0f) - - // Scale to match image size * crop scale - // The quad is -1 to 1 (size 2), so we need to scale it to match image dimensions - // Actually, we want to map the quad (-1..1) to the image size (-w/2..w/2) + // The quad spans -1..1, so scale by half the displayed image dimensions. Matrix.scaleM( matrix, 0, @@ -405,9 +309,6 @@ class PaperizeWallpaperRenderer( ) } - /** - * Draw a full-screen quad with current buffers. - */ private fun drawQuad(aPositionHandle: Int, aTexCoordHandle: Int, uMvpMatrixHandle: Int, mvpMatrix: FloatArray) { GLES20.glEnableVertexAttribArray(aPositionHandle) GLES20.glEnableVertexAttribArray(aTexCoordHandle) @@ -423,21 +324,11 @@ class PaperizeWallpaperRenderer( GLES20.glDisableVertexAttribArray(aTexCoordHandle) } - /** - * Compile all shader programs and cache uniform locations. - */ private fun compileShaders() { - // Simple program - simpleProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.SIMPLE_FRAGMENT_SHADER) + blurProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.BLUR_FRAGMENT_SHADER) - // Blur programs - blurHorizontalProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.BLUR_HORIZONTAL_FRAGMENT_SHADER) - blurVerticalProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.BLUR_VERTICAL_FRAGMENT_SHADER) - - // Effects program effectsProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.EFFECTS_FRAGMENT_SHADER) - // Cache uniform/attribute locations for effects program aPositionHandle = GLES20.glGetAttribLocation(effectsProgram, "a_position") aTexCoordHandle = GLES20.glGetAttribLocation(effectsProgram, "a_texCoord") uTextureHandle = GLES20.glGetUniformLocation(effectsProgram, "u_texture") @@ -451,42 +342,32 @@ class PaperizeWallpaperRenderer( Log.d(TAG, "Effects uniform locations: alpha=$uAlphaHandle, darken=$uDarkenFactorHandle, " + "vignette=$uVignetteFactorHandle, grayscale=$uGrayscaleFactorHandle, adaptiveBrightness=$uAdaptiveBrightnessFactorHandle") - // Cache uniform/attribute locations for horizontal blur program - blurHPositionHandle = GLES20.glGetAttribLocation(blurHorizontalProgram, "a_position") - blurHTexCoordHandle = GLES20.glGetAttribLocation(blurHorizontalProgram, "a_texCoord") - blurHTextureHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_texture") - blurHMvpMatrixHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_mvpMatrix") - blurHResolutionHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_resolution") - blurHRadiusHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_blurRadius") - - // Cache uniform/attribute locations for vertical blur program - blurVPositionHandle = GLES20.glGetAttribLocation(blurVerticalProgram, "a_position") - blurVTexCoordHandle = GLES20.glGetAttribLocation(blurVerticalProgram, "a_texCoord") - blurVTextureHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_texture") - blurVMvpMatrixHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_mvpMatrix") - blurVResolutionHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_resolution") - blurVRadiusHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_blurRadius") + blurPositionHandle = GLES20.glGetAttribLocation(blurProgram, "a_position") + blurTexCoordHandle = GLES20.glGetAttribLocation(blurProgram, "a_texCoord") + blurTextureHandle = GLES20.glGetUniformLocation(blurProgram, "u_texture") + blurMvpMatrixHandle = GLES20.glGetUniformLocation(blurProgram, "u_mvpMatrix") + blurResolutionHandle = GLES20.glGetUniformLocation(blurProgram, "u_resolution") + blurRadiusHandle = GLES20.glGetUniformLocation(blurProgram, "u_blurRadius") + blurDirectionHandle = GLES20.glGetUniformLocation(blurProgram, "u_direction") Log.d(TAG, "Shaders compiled and uniforms cached") } - /** - * Create framebuffers for blur passes. - * Two FBOs are needed for proper 3-pass blur + effects pipeline. - */ private fun createBlurFramebuffers(width: Int, height: Int) { - // Delete old resources deleteBlurResources() - // Create FBO1 (horizontal blur output) - val (fbo1, tex1) = createFboWithTexture(width, height) - blurFbo1 = fbo1 - blurTexture1 = tex1 + try { + val (fbo1, tex1) = createFboWithTexture(width, height) + blurFbo1 = fbo1 + blurTexture1 = tex1 - // Create FBO2 (vertical blur output) - val (fbo2, tex2) = createFboWithTexture(width, height) - blurFbo2 = fbo2 - blurTexture2 = tex2 + val (fbo2, tex2) = createFboWithTexture(width, height) + blurFbo2 = fbo2 + blurTexture2 = tex2 + } catch (e: Throwable) { + deleteBlurResources() + throw e + } Log.d(TAG, "Blur framebuffers created: ${width}x${height}") } @@ -496,45 +377,46 @@ class PaperizeWallpaperRenderer( * @return Pair of (fboId, textureId) */ private fun createFboWithTexture(width: Int, height: Int): Pair { - // Create texture val textureIds = IntArray(1) GLES20.glGenTextures(1, textureIds, 0) val textureId = textureIds[0] - GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE) - GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE) - GLES20.glTexImage2D( - GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, - width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null - ) - - // Create framebuffer val fboIds = IntArray(1) - GLES20.glGenFramebuffers(1, fboIds, 0) - val fboId = fboIds[0] + try { + GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE) + GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE) + GLES20.glTexImage2D( + GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, + width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null + ) - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboId) - GLES20.glFramebufferTexture2D( - GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, - GLES20.GL_TEXTURE_2D, textureId, 0 - ) + GLES20.glGenFramebuffers(1, fboIds, 0) + val fboId = fboIds[0] - val status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) - if (status != GLES20.GL_FRAMEBUFFER_COMPLETE) { - throw RuntimeException("Framebuffer not complete: $status") + GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboId) + GLES20.glFramebufferTexture2D( + GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, + GLES20.GL_TEXTURE_2D, textureId, 0 + ) + + val status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER) + if (status != GLES20.GL_FRAMEBUFFER_COMPLETE) { + throw RuntimeException("Framebuffer not complete: $status") + } + + return Pair(fboId, textureId) + } catch (e: Throwable) { + GLES20.glDeleteFramebuffers(1, fboIds, 0) + GLES20.glDeleteTextures(1, textureIds, 0) + throw e + } finally { + GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0) } - - GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0) - - return Pair(fboId, textureId) } - /** - * Delete all blur-related GPU resources. - */ private fun deleteBlurResources() { if (blurFbo1 != 0) GLUtil.deleteFramebuffer(blurFbo1) if (blurFbo2 != 0) GLUtil.deleteFramebuffer(blurFbo2) @@ -547,22 +429,16 @@ class PaperizeWallpaperRenderer( blurTexture2 = 0 } - /** - * Queue a new wallpaper for loading and display. - * This method can be called from any thread. - * Will wait for valid surface dimensions before loading. - * - * @param imageLoader Image loader to use - * @param skipCrossfade If true, instantly swap wallpaper without crossfade animation - */ + /** Thread-safe request; waits for a surface and decodes off the GL thread. */ + @Synchronized fun queueWallpaper(imageLoader: ImageLoader, skipCrossfade: Boolean = false) { - // Cancel any existing loading job to prevent race conditions + requestedImageLoader = imageLoader + val generation = loadGeneration.incrementAndGet() currentLoadJob?.cancel() currentLoadJob = loadingScope.launch { try { - // Wait for valid surface dimensions (onSurfaceChanged may not have been called yet) - val (width, height) = waitForSurfaceDimensions() + val (width, height) = surfaceSize.filterNotNull().first() Log.d(TAG, "Loading wallpaper... (skipCrossfade=$skipCrossfade)") val bitmap = imageLoader.load(width, height) @@ -570,7 +446,6 @@ class PaperizeWallpaperRenderer( if (bitmap != null) { Log.d(TAG, "Wallpaper loaded: ${bitmap.width}x${bitmap.height}") - // Check for cancellation before uploading if (!isActive) { Log.d(TAG, "Loading cancelled, recycling bitmap") bitmap.recycle() @@ -581,12 +456,16 @@ class PaperizeWallpaperRenderer( // is evaluated at draw time so settings changes are immediate and do not // advance the wallpaper queue. val sourceBrightness = - com.anthonyla.paperize.core.util.calculateBitmapBrightness(bitmap) + com.anthonyla.paperize.core.util.BrightnessCalculator.calculateBitmapBrightness(bitmap) - // Upload to GPU on GL thread - callbacks.queueEventOnGlThread { - uploadBitmap(bitmap, sourceBrightness, imageLoader, skipCrossfade) + val queued = callbacks.queueEventOnGlThread { + if (loadGeneration.get() == generation) { + uploadBitmap(bitmap, sourceBrightness, skipCrossfade) + } else { + bitmap.recycle() + } } + if (!queued) bitmap.recycle() } else { Log.w(TAG, "Failed to load wallpaper (null bitmap)") } @@ -598,97 +477,36 @@ class PaperizeWallpaperRenderer( } } - /** - * Wait for valid surface dimensions. - * Polls until surfaceWidth and surfaceHeight are non-zero or timeout. - * Falls back to device display metrics if timeout occurs. - * - * @return Pair of (width, height) - */ - private suspend fun waitForSurfaceDimensions(): Pair { - val maxWaitMs = Constants.SURFACE_WAIT_TIMEOUT_MS - val pollIntervalMs = Constants.SURFACE_POLL_INTERVAL_MS - var waitedMs = 0L - - while (surfaceWidth <= 0 || surfaceHeight <= 0) { - if (waitedMs >= maxWaitMs) { - // Use actual device display metrics as fallback instead of hardcoded values - val displayMetrics = context.resources.displayMetrics - val fallbackWidth = displayMetrics.widthPixels - val fallbackHeight = displayMetrics.heightPixels - Log.w(TAG, "Timeout waiting for surface dimensions, using display metrics: ${fallbackWidth}x${fallbackHeight}") - return Pair(fallbackWidth, fallbackHeight) - } - kotlinx.coroutines.delay(pollIntervalMs) - waitedMs += pollIntervalMs - } - - return Pair(surfaceWidth, surfaceHeight) - } - - /** - * Upload a bitmap to GPU and start crossfade (or instant swap). - * Must be called on GL thread. - * - * @param bitmap The bitmap to upload - * @param sourceBrightness Luminance of the unmodified source bitmap - * @param imageLoader Source used to reproduce this bitmap after a surface resize - * @param skipCrossfade If true, instantly replace current wallpaper without animation - */ + /** Consumes [bitmap] on the GL thread, then swaps or crossfades to it. */ private fun uploadBitmap( bitmap: Bitmap, sourceBrightness: Float, - imageLoader: ImageLoader, skipCrossfade: Boolean = false ) { - // Validate bitmap before processing - if (bitmap.isRecycled) { - Log.e(TAG, "Cannot upload recycled bitmap") - return - } - if (bitmap.width <= 0 || bitmap.height <= 0) { - Log.e(TAG, "Cannot upload bitmap with invalid dimensions: ${bitmap.width}x${bitmap.height}") - bitmap.recycle() - return - } - try { val picture = GLPicture(bitmap, sourceBrightness) - currentImageLoader = imageLoader - - // Recycle bitmap (no longer needed after GPU upload) - bitmap.recycle() if (skipCrossfade) { - // Instant swap - no animation (used for screen-off changes) currentPicture?.recycle() nextPicture?.recycle() // Recycle any in-flight crossfade target currentPicture = picture nextPicture = null - crossfadeProgress = 0f + crossfadeStartTimeNanos = 0L Log.d(TAG, "Wallpaper instantly swapped (no crossfade): $picture") } else { - // Start crossfade with time-based animation nextPicture?.recycle() // Recycle interrupted crossfade target if any nextPicture = picture - crossfadeProgress = 0f + crossfadeStartTimeNanos = System.nanoTime() Log.d(TAG, "Wallpaper uploaded to GPU with crossfade: $picture") } callbacks.requestRender() - } catch (e: IllegalArgumentException) { - // GLPicture validation failed (recycled bitmap or invalid dimensions) - Log.e(TAG, "Failed to create GLPicture: ${e.message}") - if (!bitmap.isRecycled) { - bitmap.recycle() - } } catch (e: Exception) { Log.e(TAG, "Failed to upload bitmap to GPU", e) - if (!bitmap.isRecycled) { - bitmap.recycle() - } + } finally { + bitmap.recycle() } } @@ -758,20 +576,23 @@ class PaperizeWallpaperRenderer( * Cleanup resources. * Must be called on GL thread. */ - fun destroy() { + @Synchronized + fun cancelLoading() { + loadGeneration.incrementAndGet() loadingScope.cancel() - currentLoadJob?.cancel() + requestedImageLoader = null + } + + fun destroy() { + cancelLoading() currentPicture?.recycle() currentPicture = null nextPicture?.recycle() nextPicture = null - currentImageLoader = null - GLUtil.deleteProgram(simpleProgram) - GLUtil.deleteProgram(blurHorizontalProgram) - GLUtil.deleteProgram(blurVerticalProgram) + GLUtil.deleteProgram(blurProgram) GLUtil.deleteProgram(effectsProgram) deleteBlurResources() diff --git a/app/src/main/java/com/anthonyla/paperize/service/tile/WallpaperTileService.kt b/app/src/main/java/com/anthonyla/paperize/service/tile/WallpaperTileService.kt index 90c3787..f33ccab 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/tile/WallpaperTileService.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/tile/WallpaperTileService.kt @@ -4,9 +4,6 @@ import android.content.Intent import android.service.quicksettings.TileService import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService -/** - * Quick Settings Tile for changing wallpaper - */ class WallpaperTileService : TileService() { override fun onClick() { diff --git a/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt b/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt index 1661ce6..ded7bfa 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt @@ -4,32 +4,24 @@ import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.app.Service -import android.app.WallpaperManager import android.content.Intent import android.content.pm.ServiceInfo -import android.graphics.Bitmap import android.os.Build import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat import com.anthonyla.paperize.R -import com.anthonyla.paperize.core.EmptyAlbumException -import com.anthonyla.paperize.core.Result as PaperizeResult import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.WallpaperMode import com.anthonyla.paperize.core.constants.Constants -import com.anthonyla.paperize.core.util.setBitmapChecked -import com.anthonyla.paperize.domain.model.PreparedWallpaper -import com.anthonyla.paperize.domain.model.ScheduleSettings import com.anthonyla.paperize.domain.repository.SettingsRepository import com.anthonyla.paperize.domain.repository.WallpaperRepository -import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase -import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase import com.anthonyla.paperize.presentation.MainActivity import com.anthonyla.paperize.service.WallpaperChangeLock import com.anthonyla.paperize.service.worker.WallpaperScheduler import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob @@ -37,26 +29,20 @@ import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.sync.withLock -/** - * Foreground service for immediate wallpaper changes and effect reapplication. - */ @AndroidEntryPoint class WallpaperChangeService : Service() { - @Inject lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase - @Inject lateinit var reapplyEffectsUseCase: ReapplyEffectsUseCase + @Inject lateinit var wallpaperController: WallpaperController @Inject lateinit var settingsRepository: SettingsRepository @Inject lateinit var wallpaperChangeLock: WallpaperChangeLock @Inject lateinit var wallpaperScheduler: WallpaperScheduler @Inject lateinit var wallpaperRepository: WallpaperRepository private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - private lateinit var wallpaperManager: WallpaperManager private lateinit var notificationManager: NotificationManager override fun onCreate() { super.onCreate() - wallpaperManager = WallpaperManager.getInstance(this) notificationManager = getSystemService(NotificationManager::class.java) ?: error("NotificationManager not available") } @@ -112,13 +98,17 @@ class WallpaperChangeService : Service() { screenType } val settings = settingsRepository.getScheduleSettings() - if (changeWallpaper(effectiveScreenType, settings)) { + val outcome = wallpaperController.change(effectiveScreenType, settings) + if (outcome.emptyAlbum) showEmptyAlbumNotification() + if (outcome.changed) { wallpaperScheduler.resetAfterManualChange( effectiveScreenType, settings, wallpaperMode ) } + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Error changing wallpaper", e) showErrorNotification( @@ -133,164 +123,6 @@ class WallpaperChangeService : Service() { } } - private suspend fun changeWallpaper( - screenType: ScreenType, - settings: ScheduleSettings - ): Boolean = - when (screenType) { - ScreenType.LIVE -> { - sendBroadcast( - Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(packageName) - ) - Log.d(TAG, "Requested immediate live wallpaper reload") - true - } - - ScreenType.HOME -> settings.homeAlbumId?.let { - changeSingle(it, ScreenType.HOME) - } ?: false.also { Log.w(TAG, "No home album selected") } - - ScreenType.LOCK -> settings.lockAlbumId?.let { - changeSingle(it, ScreenType.LOCK) - } ?: false.also { Log.w(TAG, "No lock album selected") } - - ScreenType.BOTH -> { - val homeAlbumId = settings.homeAlbumId - val lockAlbumId = settings.lockAlbumId - if ( - homeAlbumId != null && - homeAlbumId == lockAlbumId && - !settings.separateSchedules - ) { - changeSynchronized(homeAlbumId, settings) - } else { - var changed = false - homeAlbumId?.let { changed = changeSingle(it, ScreenType.HOME) || changed } - ?: Log.w(TAG, "No home album selected") - lockAlbumId?.let { changed = changeSingle(it, ScreenType.LOCK) || changed } - ?: Log.w(TAG, "No lock album selected") - changed - } - } - } - - private suspend fun changeSynchronized( - albumId: String, - settings: ScheduleSettings - ): Boolean = - when (val result = changeWallpaperUseCase(albumId, ScreenType.HOME)) { - is PaperizeResult.Success -> { - val prepared = result.data - val samePresentation = - settings.homeEffects == settings.lockEffects && - settings.homeScalingType == settings.lockScalingType && - !settings.homeScrollingEnabled - - if (samePresentation) { - applyPrepared( - prepared, - WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK, - listOf(ScreenType.HOME, ScreenType.LOCK) - ) - Log.d(TAG, "Home and lock wallpaper set atomically") - } else { - applyPrepared( - prepared, - WallpaperManager.FLAG_SYSTEM, - listOf(ScreenType.HOME) - ) - Log.d(TAG, "Home wallpaper set in BOTH mode") - - when ( - val lockResult = reapplyEffectsUseCase( - albumId, - ScreenType.LOCK, - prepared.wallpaperId - ) - ) { - is PaperizeResult.Success -> { - val lockBitmap = lockResult.data - try { - wallpaperManager.setBitmapChecked( - lockBitmap, - WallpaperManager.FLAG_LOCK - ) - changeWallpaperUseCase.complete(prepared, ScreenType.LOCK) - Log.d(TAG, "Lock wallpaper set separately in BOTH mode") - } finally { - lockBitmap.recycle() - } - } - - is PaperizeResult.Error -> throw asException(lockResult.exception) - PaperizeResult.Loading -> error("Unexpected loading result") - } - } - true - } - - is PaperizeResult.Error -> { - if (result.exception is EmptyAlbumException) { - handleEmptyAlbumError(ScreenType.BOTH) - false - } else { - throw asException(result.exception) - } - } - - PaperizeResult.Loading -> error("Unexpected loading result") - } - - private suspend fun changeSingle( - albumId: String, - screenType: ScreenType - ): Boolean = - when (val result = changeWallpaperUseCase(albumId, screenType)) { - is PaperizeResult.Success -> { - val which = when (screenType) { - ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM - ScreenType.LOCK -> WallpaperManager.FLAG_LOCK - else -> error("Unsupported static screen: $screenType") - } - applyPrepared(result.data, which, listOf(screenType)) - Log.d(TAG, "$screenType wallpaper changed successfully") - true - } - - is PaperizeResult.Error -> { - if (result.exception is EmptyAlbumException) { - handleEmptyAlbumError(screenType) - false - } else { - throw asException(result.exception) - } - } - - PaperizeResult.Loading -> error("Unexpected loading result") - } - - private suspend fun applyPrepared( - prepared: PreparedWallpaper, - which: Int, - completedScreens: List - ) { - var platformAccepted = false - try { - wallpaperManager.setBitmapChecked(prepared.bitmap, which) - platformAccepted = true - completedScreens.forEach { screen -> - changeWallpaperUseCase.complete(prepared, screen) - } - } catch (e: Exception) { - if (!platformAccepted) { - changeWallpaperUseCase.restore(prepared) - } - throw e - } finally { - prepared.bitmap.recycle() - } - } - private fun handleApplySpecificWallpaper( wallpaperId: String?, screenType: ScreenType, @@ -309,10 +141,10 @@ class WallpaperChangeService : Service() { ?: error(getString(R.string.wallpaper_not_found)) val settings = settingsRepository.getScheduleSettings() - applySpecificWallpaper( + wallpaperController.applySpecific( albumId = wallpaper.albumId, wallpaperId = wallpaper.id, - screenType = screenType, + screen = screenType, settings = settings ) wallpaperScheduler.resetAfterManualChange( @@ -320,6 +152,8 @@ class WallpaperChangeService : Service() { settings = settings, wallpaperMode = wallpaperMode ) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Error applying selected wallpaper", e) showErrorNotification( @@ -333,123 +167,15 @@ class WallpaperChangeService : Service() { } } - private suspend fun applySpecificWallpaper( - albumId: String, - wallpaperId: String, - screenType: ScreenType, - settings: ScheduleSettings - ) { - when (screenType) { - ScreenType.HOME, ScreenType.LOCK -> applySpecificSingle( - albumId, - wallpaperId, - screenType, - settings.shuffleEnabled - ) - - ScreenType.BOTH -> { - val samePresentation = - settings.homeEffects == settings.lockEffects && - settings.homeScalingType == settings.lockScalingType && - !settings.homeScrollingEnabled - if (samePresentation) { - val bitmap = renderSpecific(albumId, wallpaperId, ScreenType.HOME) - try { - wallpaperManager.setBitmapChecked( - bitmap, - WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK - ) - changeWallpaperUseCase.completeSpecific( - albumId, - ScreenType.HOME, - wallpaperId, - settings.shuffleEnabled - ) - changeWallpaperUseCase.completeSpecific( - albumId, - ScreenType.LOCK, - wallpaperId, - settings.shuffleEnabled - ) - } finally { - bitmap.recycle() - } - } else { - applySpecificSingle( - albumId, - wallpaperId, - ScreenType.HOME, - settings.shuffleEnabled - ) - applySpecificSingle( - albumId, - wallpaperId, - ScreenType.LOCK, - settings.shuffleEnabled - ) - } - } - - ScreenType.LIVE -> error(getString(R.string.static_mode_required)) - } - Log.d(TAG, "Selected wallpaper applied to $screenType") - } - - private suspend fun applySpecificSingle( - albumId: String, - wallpaperId: String, - screenType: ScreenType, - shuffle: Boolean - ) { - val bitmap = renderSpecific(albumId, wallpaperId, screenType) - try { - val which = if (screenType == ScreenType.HOME) { - WallpaperManager.FLAG_SYSTEM - } else { - WallpaperManager.FLAG_LOCK - } - wallpaperManager.setBitmapChecked(bitmap, which) - changeWallpaperUseCase.completeSpecific(albumId, screenType, wallpaperId, shuffle) - } finally { - bitmap.recycle() - } - } - - private suspend fun renderSpecific( - albumId: String, - wallpaperId: String, - screenType: ScreenType - ): Bitmap = when (val result = reapplyEffectsUseCase(albumId, screenType, wallpaperId)) { - is PaperizeResult.Success -> result.data - is PaperizeResult.Error -> throw asException(result.exception) - PaperizeResult.Loading -> error("Unexpected loading result") - } - private fun handleReapplyEffects(screenType: ScreenType, startId: Int) { serviceScope.launch { wallpaperChangeLock.mutex.withLock { try { val settings = settingsRepository.getScheduleSettings() - when (screenType) { - ScreenType.HOME -> settings.homeAlbumId?.let { - reapplySingle(it, ScreenType.HOME) - } - - ScreenType.LOCK -> settings.lockAlbumId?.let { - reapplySingle(it, ScreenType.LOCK) - } - - ScreenType.BOTH -> { - settings.homeAlbumId?.let { - reapplySingle(it, ScreenType.HOME) - } - settings.lockAlbumId?.let { - reapplySingle(it, ScreenType.LOCK) - } - } - - ScreenType.LIVE -> Unit - } + val outcome = wallpaperController.reapply(screenType, settings) + if (outcome.emptyAlbum) showEmptyAlbumNotification() + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Error reapplying effects", e) showErrorNotification( @@ -464,63 +190,7 @@ class WallpaperChangeService : Service() { } } - private suspend fun reapplySingle( - albumId: String, - screenType: ScreenType - ) { - when (val result = reapplyEffectsUseCase(albumId, screenType)) { - is PaperizeResult.Success -> { - val bitmap = result.data - try { - val which = if (screenType == ScreenType.HOME) { - WallpaperManager.FLAG_SYSTEM - } else { - WallpaperManager.FLAG_LOCK - } - wallpaperManager.setBitmapChecked(bitmap, which) - Log.d(TAG, "$screenType effects reapplied successfully") - } finally { - bitmap.recycle() - } - } - - is PaperizeResult.Error -> { - Log.w(TAG, "Reapply failed for $screenType; advancing queue", result.exception) - changeSingle(albumId, screenType) - } - - PaperizeResult.Loading -> error("Unexpected loading result") - } - } - - private suspend fun handleEmptyAlbumError(screenType: ScreenType) { - val settings = settingsRepository.getScheduleSettings() - val updated = when (screenType) { - ScreenType.HOME -> { - val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null - settings.copy( - homeAlbumId = null, - enableChanger = lockStillActive && settings.enableChanger - ) - } - - ScreenType.LOCK -> { - val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null - settings.copy( - lockAlbumId = null, - enableChanger = homeStillActive && settings.enableChanger - ) - } - - ScreenType.BOTH -> settings.copy( - homeAlbumId = null, - lockAlbumId = null, - enableChanger = false - ) - - ScreenType.LIVE -> settings.copy(enableChanger = false) - } - settingsRepository.updateScheduleSettings(updated) + private fun showEmptyAlbumNotification() { showErrorNotification( getString(R.string.no_wallpapers_in_album), getString(R.string.wallpaper_changer_disabled_empty_album) @@ -561,9 +231,6 @@ class WallpaperChangeService : Service() { notificationManager.notify(ERROR_NOTIFICATION_ID, notification) } - private fun asException(throwable: Throwable): Exception = - throwable as? Exception ?: RuntimeException(throwable) - override fun onBind(intent: Intent?): IBinder? = null override fun onDestroy() { diff --git a/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperController.kt b/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperController.kt new file mode 100644 index 0000000..64abf88 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperController.kt @@ -0,0 +1,152 @@ +package com.anthonyla.paperize.service.wallpaper + +import android.app.WallpaperManager +import android.content.Context +import android.content.Intent +import android.graphics.Bitmap +import com.anthonyla.paperize.core.EmptyAlbumException +import com.anthonyla.paperize.core.ScreenType +import com.anthonyla.paperize.core.constants.Constants +import com.anthonyla.paperize.core.util.setBitmapChecked +import com.anthonyla.paperize.domain.model.PreparedWallpaper +import com.anthonyla.paperize.domain.model.ScheduleSettings +import com.anthonyla.paperize.domain.repository.SettingsRepository +import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase +import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase +import dagger.hilt.android.qualifiers.ApplicationContext +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext +import javax.inject.Inject + +data class WallpaperChangeOutcome(val changed: Boolean = false, val emptyAlbum: Boolean = false) + +/** Call while holding WallpaperChangeLock so applying and resetting schedules stay ordered. */ +class WallpaperController @Inject constructor( + @param:ApplicationContext private val context: Context, + private val wallpaperManager: WallpaperManager, + private val prepare: ChangeWallpaperUseCase, + private val render: ReapplyEffectsUseCase, + private val settingsRepository: SettingsRepository +) { + suspend fun change(screen: ScreenType, settings: ScheduleSettings): WallpaperChangeOutcome = when (screen) { + ScreenType.LIVE -> { + context.sendBroadcast(Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(context.packageName)) + WallpaperChangeOutcome(changed = true) + } + ScreenType.HOME -> changeSelected(settings.homeAlbumId, screen) + ScreenType.LOCK -> changeSelected(settings.lockAlbumId, screen) + ScreenType.BOTH -> { + val home = settings.homeAlbumId + if (home != null && home == settings.lockAlbumId && !settings.separateSchedules) { + changeSynchronized(home, settings) + } else { + combine(changeSelected(home, ScreenType.HOME), changeSelected(settings.lockAlbumId, ScreenType.LOCK)) + } + } + } + + private suspend fun changeSelected(albumId: String?, screen: ScreenType): WallpaperChangeOutcome { + if (albumId == null) return WallpaperChangeOutcome() + val prepared = prepareOrDisable(albumId, screen) ?: return WallpaperChangeOutcome(emptyAlbum = true) + applyPrepared(prepared, screen) + return WallpaperChangeOutcome(changed = true) + } + + private suspend fun changeSynchronized(albumId: String, settings: ScheduleSettings): WallpaperChangeOutcome { + val prepared = prepareOrDisable(albumId, ScreenType.BOTH) ?: return WallpaperChangeOutcome(emptyAlbum = true) + if (settings.sameStaticPresentation()) { + applyPrepared(prepared, ScreenType.BOTH) + } else { + applyPrepared(prepared, ScreenType.HOME) + val lockBitmap = render(albumId, ScreenType.LOCK, prepared.wallpaperId).getOrThrow() + applyBitmap(lockBitmap, ScreenType.LOCK) { prepare.complete(prepared, ScreenType.LOCK) } + } + return WallpaperChangeOutcome(changed = true) + } + + private suspend fun prepareOrDisable(albumId: String, screen: ScreenType): PreparedWallpaper? { + try { + return prepare(albumId, if (screen == ScreenType.BOTH) ScreenType.HOME else screen).getOrThrow() + } catch (_: EmptyAlbumException) { + settingsRepository.clearEmptyAlbumSelection(albumId, screen) + return null + } + } + + private suspend fun applyPrepared(prepared: PreparedWallpaper, screen: ScreenType) { + var accepted = false + try { + currentCoroutineContext().ensureActive() + wallpaperManager.setBitmapChecked(prepared.bitmap, screen.flags()) + accepted = true + // Once Android accepts the bitmap, cancellation must not leave our current item stale. + withContext(NonCancellable) { + screen.staticScreens().forEach { prepare.complete(prepared, it) } + } + } catch (e: Exception) { + if (!accepted) withContext(NonCancellable) { prepare.restore(prepared) } + throw e + } finally { + prepared.bitmap.recycle() + } + } + + suspend fun applySpecific(albumId: String, wallpaperId: String, screen: ScreenType, settings: ScheduleSettings) { + val targets = if (screen == ScreenType.BOTH && !settings.sameStaticPresentation()) { + listOf(ScreenType.HOME, ScreenType.LOCK) + } else listOf(screen) + for (target in targets) { + val renderScreen = if (target == ScreenType.BOTH) ScreenType.HOME else target + val bitmap = render(albumId, renderScreen, wallpaperId).getOrThrow() + applyBitmap(bitmap, target) { + target.staticScreens().forEach { + prepare.completeSpecific(albumId, it, wallpaperId, settings.shuffleEnabled) + } + } + } + } + + suspend fun reapply(screen: ScreenType, settings: ScheduleSettings): WallpaperChangeOutcome { + if (screen == ScreenType.LIVE) return WallpaperChangeOutcome() + var outcome = WallpaperChangeOutcome() + for (target in screen.staticScreens()) { + val albumId = if (target == ScreenType.HOME) settings.homeAlbumId else settings.lockAlbumId + if (albumId == null) continue + val bitmap = render(albumId, target).getOrNull() + val result = if (bitmap == null) changeSelected(albumId, target) else { + applyBitmap(bitmap, target) + WallpaperChangeOutcome(changed = true) + } + outcome = combine(outcome, result) + } + return outcome + } + + private suspend fun applyBitmap(bitmap: Bitmap, screen: ScreenType, onApplied: suspend () -> Unit = {}) { + try { + currentCoroutineContext().ensureActive() + wallpaperManager.setBitmapChecked(bitmap, screen.flags()) + withContext(NonCancellable) { onApplied() } + } finally { + bitmap.recycle() + } + } + + private fun combine(first: WallpaperChangeOutcome, second: WallpaperChangeOutcome) = WallpaperChangeOutcome( + changed = first.changed || second.changed, emptyAlbum = first.emptyAlbum || second.emptyAlbum + ) + + private fun ScheduleSettings.sameStaticPresentation() = + homeEffects == lockEffects && homeScalingType == lockScalingType && !homeScrollingEnabled + + private fun ScreenType.staticScreens() = if (this == ScreenType.BOTH) listOf(ScreenType.HOME, ScreenType.LOCK) else listOf(this) + + private fun ScreenType.flags(): Int = when (this) { + ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM + ScreenType.LOCK -> WallpaperManager.FLAG_LOCK + ScreenType.BOTH -> WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK + ScreenType.LIVE -> error("Live wallpaper is applied by its engine") + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/worker/AlbumRefreshWorker.kt b/app/src/main/java/com/anthonyla/paperize/service/worker/AlbumRefreshWorker.kt index 685b17c..ebdf588 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/worker/AlbumRefreshWorker.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/worker/AlbumRefreshWorker.kt @@ -7,36 +7,25 @@ import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import com.anthonyla.paperize.core.Result as CoreResult import com.anthonyla.paperize.domain.repository.AlbumRepository -import com.anthonyla.paperize.domain.usecase.RefreshAlbumUseCase import com.anthonyla.paperize.domain.usecase.RefreshFolderUseCase import dagger.assisted.Assisted import dagger.assisted.AssistedInject import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.first -/** - * Background worker that validates and refreshes all albums daily - * - * - Runs once daily (typically at 3 AM) - * - Validates all wallpaper and folder URIs in all albums - * - Removes confirmed missing entries while preserving inaccessible sources - * - Rescans all folders for new wallpapers and adds them to albums - * - Only runs when wallpaper changer is enabled - */ @HiltWorker class AlbumRefreshWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val albumRepository: AlbumRepository, - private val refreshFolderUseCase: RefreshFolderUseCase, - private val refreshAlbumUseCase: RefreshAlbumUseCase + private val refreshFolderUseCase: RefreshFolderUseCase ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): androidx.work.ListenableWorker.Result { return try { Log.d(TAG, "Starting daily album refresh") - val albums = albumRepository.getAllAlbums().first() + val albums = albumRepository.getAlbumSummaries().first() if (albums.isEmpty()) { Log.d(TAG, "No albums to refresh") @@ -48,7 +37,7 @@ class AlbumRefreshWorker @AssistedInject constructor( var failedCount = 0 albums.forEach { album -> - when (val result = refreshAlbumUseCase(album.id)) { + when (val result = albumRepository.pruneMissingEntries(album.id)) { is CoreResult.Success -> { val removedCount = result.data totalRemoved += removedCount @@ -60,7 +49,6 @@ class AlbumRefreshWorker @AssistedInject constructor( Log.e(TAG, "Error validating album '${album.name}'", result.exception) failedCount++ } - CoreResult.Loading -> Unit } // Reload after validation, which may have removed folders from the snapshot. @@ -72,13 +60,11 @@ class AlbumRefreshWorker @AssistedInject constructor( Log.e(TAG, "Error refreshing folder '${folder.name}'", result.exception) failedCount++ } - CoreResult.Loading -> Unit } } } Log.d(TAG, "Daily album refresh completed: removed $totalRemoved items, added $totalAdded new wallpapers across ${albums.size} albums ($failedCount failures)") - // Return success even if some albums failed (partial success) androidx.work.ListenableWorker.Result.success() } catch (e: CancellationException) { throw e diff --git a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt index 0d9c524..a02add2 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt @@ -1,36 +1,25 @@ package com.anthonyla.paperize.service.worker -import android.app.WallpaperManager import android.content.Context -import android.content.Intent import android.util.Log import androidx.hilt.work.HiltWorker import androidx.work.CoroutineWorker import androidx.work.WorkerParameters -import com.anthonyla.paperize.core.EmptyAlbumException -import com.anthonyla.paperize.core.Result as PaperizeResult import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.constants.Constants -import com.anthonyla.paperize.core.util.setBitmapChecked -import com.anthonyla.paperize.domain.model.PreparedWallpaper -import com.anthonyla.paperize.domain.model.ScheduleSettings import com.anthonyla.paperize.domain.repository.SettingsRepository -import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase -import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase import com.anthonyla.paperize.service.WallpaperChangeLock import dagger.assisted.Assisted import dagger.assisted.AssistedInject +import com.anthonyla.paperize.service.wallpaper.WallpaperController +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.sync.withLock -/** - * WorkManager worker for scheduled wallpaper changes. - */ @HiltWorker class WallpaperChangeWorker @AssistedInject constructor( @Assisted private val context: Context, @Assisted workerParams: WorkerParameters, - private val changeWallpaperUseCase: ChangeWallpaperUseCase, - private val reapplyEffectsUseCase: ReapplyEffectsUseCase, + private val wallpaperController: WallpaperController, private val settingsRepository: SettingsRepository, private val wallpaperChangeLock: WallpaperChangeLock ) : CoroutineWorker(context, workerParams) { @@ -43,10 +32,12 @@ class WallpaperChangeWorker @AssistedInject constructor( Log.d(TAG, "Starting wallpaper change for $screenType") wallpaperChangeLock.mutex.withLock { - changeWallpaper(screenType) + wallpaperController.change(screenType, settingsRepository.getScheduleSettings()) } Log.d(TAG, "Wallpaper change completed successfully for $screenType") Result.success() + } catch (e: CancellationException) { + throw e } catch (e: Exception) { Log.e(TAG, "Error changing wallpaper", e) if (runAttemptCount < Constants.MAX_WORK_RETRY_ATTEMPTS) { @@ -57,213 +48,6 @@ class WallpaperChangeWorker @AssistedInject constructor( } } - private suspend fun changeWallpaper(screenType: ScreenType) { - val settings = settingsRepository.getScheduleSettings() - val wallpaperManager = WallpaperManager.getInstance(context) - - when (screenType) { - ScreenType.LIVE -> { - context.sendBroadcast( - Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(context.packageName) - ) - Log.d(TAG, "Sent reload broadcast to live wallpaper service") - } - - ScreenType.HOME -> { - settings.homeAlbumId?.let { - changeSingle(it, ScreenType.HOME, settings, wallpaperManager) - } ?: Log.w(TAG, "No home album selected") - } - - ScreenType.LOCK -> { - settings.lockAlbumId?.let { - changeSingle(it, ScreenType.LOCK, settings, wallpaperManager) - } ?: Log.w(TAG, "No lock album selected") - } - - ScreenType.BOTH -> { - val homeAlbumId = settings.homeAlbumId - val lockAlbumId = settings.lockAlbumId - if ( - homeAlbumId != null && - homeAlbumId == lockAlbumId && - !settings.separateSchedules - ) { - changeSynchronized(homeAlbumId, settings, wallpaperManager) - } else { - homeAlbumId?.let { - changeSingle(it, ScreenType.HOME, settings, wallpaperManager) - } ?: Log.w(TAG, "No home album selected for BOTH mode") - lockAlbumId?.let { - changeSingle(it, ScreenType.LOCK, settings, wallpaperManager) - } ?: Log.w(TAG, "No lock album selected for BOTH mode") - } - } - } - } - - private suspend fun changeSynchronized( - albumId: String, - settings: ScheduleSettings, - wallpaperManager: WallpaperManager - ) { - when (val result = changeWallpaperUseCase(albumId, ScreenType.HOME)) { - is PaperizeResult.Success -> { - val prepared = result.data - val samePresentation = - settings.homeEffects == settings.lockEffects && - settings.homeScalingType == settings.lockScalingType && - !settings.homeScrollingEnabled - - if (samePresentation) { - applyPrepared( - prepared = prepared, - wallpaperManager = wallpaperManager, - which = WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK, - completedScreens = listOf(ScreenType.HOME, ScreenType.LOCK) - ) - Log.d(TAG, "Home and lock wallpaper set atomically") - } else { - // Distinct effects require two platform writes. Each screen is committed only - // after its own write succeeds. - applyPrepared( - prepared = prepared, - wallpaperManager = wallpaperManager, - which = WallpaperManager.FLAG_SYSTEM, - completedScreens = listOf(ScreenType.HOME) - ) - Log.d(TAG, "Home wallpaper set in BOTH mode") - - when ( - val lockResult = reapplyEffectsUseCase( - albumId, - ScreenType.LOCK, - prepared.wallpaperId - ) - ) { - is PaperizeResult.Success -> { - val lockBitmap = lockResult.data - try { - wallpaperManager.setBitmapChecked( - lockBitmap, - WallpaperManager.FLAG_LOCK - ) - changeWallpaperUseCase.complete(prepared, ScreenType.LOCK) - Log.d(TAG, "Lock wallpaper set separately in BOTH mode") - } finally { - lockBitmap.recycle() - } - } - - is PaperizeResult.Error -> throw asException(lockResult.exception) - PaperizeResult.Loading -> error("Unexpected loading result") - } - } - } - - is PaperizeResult.Error -> { - if (result.exception is EmptyAlbumException) { - Log.w(TAG, "Album is empty for BOTH screens; disabling changer") - settingsRepository.updateScheduleSettings( - settings.copy( - homeAlbumId = null, - lockAlbumId = null, - enableChanger = false - ) - ) - } else { - throw asException(result.exception) - } - } - - PaperizeResult.Loading -> error("Unexpected loading result") - } - } - - private suspend fun changeSingle( - albumId: String, - screenType: ScreenType, - settings: ScheduleSettings, - wallpaperManager: WallpaperManager - ) { - when (val result = changeWallpaperUseCase(albumId, screenType)) { - is PaperizeResult.Success -> { - val flag = when (screenType) { - ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM - ScreenType.LOCK -> WallpaperManager.FLAG_LOCK - else -> error("Unsupported static screen: $screenType") - } - applyPrepared(result.data, wallpaperManager, flag, listOf(screenType)) - Log.d(TAG, "$screenType wallpaper changed successfully") - } - - is PaperizeResult.Error -> { - if (result.exception is EmptyAlbumException) { - disableEmptyScreen(screenType, settings) - } else { - throw asException(result.exception) - } - } - - PaperizeResult.Loading -> error("Unexpected loading result") - } - } - - private suspend fun applyPrepared( - prepared: PreparedWallpaper, - wallpaperManager: WallpaperManager, - which: Int, - completedScreens: List - ) { - var platformAccepted = false - try { - wallpaperManager.setBitmapChecked(prepared.bitmap, which) - platformAccepted = true - completedScreens.forEach { screen -> - changeWallpaperUseCase.complete(prepared, screen) - } - } catch (e: Exception) { - if (!platformAccepted) { - changeWallpaperUseCase.restore(prepared) - } - throw e - } finally { - prepared.bitmap.recycle() - } - } - - private suspend fun disableEmptyScreen( - screenType: ScreenType, - settings: ScheduleSettings - ) { - when (screenType) { - ScreenType.HOME -> { - val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null - settingsRepository.updateScheduleSettings( - settings.copy( - homeAlbumId = null, - enableChanger = lockStillActive && settings.enableChanger - ) - ) - } - - ScreenType.LOCK -> { - val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null - settingsRepository.updateScheduleSettings( - settings.copy( - lockAlbumId = null, - enableChanger = homeStillActive && settings.enableChanger - ) - ) - } - - else -> Unit - } - } - - private fun asException(throwable: Throwable): Exception = - throwable as? Exception ?: RuntimeException(throwable) - private companion object { const val TAG = "WallpaperChangeWorker" } diff --git a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt index 97800c5..08e2a43 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt @@ -2,35 +2,22 @@ package com.anthonyla.paperize.service.worker import android.content.Context import android.util.Log -import androidx.work.Constraints import androidx.work.Data import androidx.work.ExistingPeriodicWorkPolicy -import androidx.work.NetworkType import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager -import kotlinx.coroutines.flow.first import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.WallpaperMode import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.domain.model.ScheduleSettings import dagger.hilt.android.qualifiers.ApplicationContext -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import java.util.Calendar import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock -/** - * WorkManager-based scheduler for wallpaper changes - * - * Advantages over AlarmManager: - * - Better battery efficiency (system optimizes execution timing) - * - No SCHEDULE_EXACT_ALARM permission needed - * - Respects Doze mode and battery optimization - * - Built-in constraint support (network, charging, idle) - * - More reliable across Android versions and OEMs - */ @Singleton class WallpaperScheduler @Inject constructor( @param:ApplicationContext private val context: Context @@ -47,39 +34,25 @@ class WallpaperScheduler @Inject constructor( * * @param screenType HOME, LOCK, or BOTH (for synchronized schedules) * @param intervalMinutes Interval between changes (minimum 15 minutes for WorkManager) - * @param networkRequired Whether network is required (for future online wallpaper support) - * @param requireCharging Whether device must be charging */ fun scheduleWallpaperChange( screenType: ScreenType, intervalMinutes: Int, - networkRequired: Boolean = false, - requireCharging: Boolean = false, - resetInterval: Boolean = false + resetInterval: Boolean = false, + onlyIfNotScheduled: Boolean = false ) { val adjustedInterval = intervalMinutes.toLong().coerceAtLeast(Constants.MIN_INTERVAL_MINUTES.toLong()) val workName = getWorkName(screenType) - // Build constraints - val constraints = Constraints.Builder() - .setRequiredNetworkType( - if (networkRequired) NetworkType.CONNECTED else NetworkType.NOT_REQUIRED - ) - .setRequiresCharging(requireCharging) - .build() - - // Build input data val inputData = Data.Builder() .putString(Constants.EXTRA_SCREEN_TYPE, screenType.name) .build() - // Create periodic work request val workRequest = PeriodicWorkRequestBuilder( adjustedInterval, TimeUnit.MINUTES ) - .setConstraints(constraints) .setInputData(inputData) .addTag(getWorkTag(screenType)) .apply { @@ -97,7 +70,7 @@ class WallpaperScheduler @Inject constructor( // Replacing periodic work starts a new first period, which can otherwise run immediately. workManager.enqueueUniquePeriodicWork( workName, - ExistingPeriodicWorkPolicy.UPDATE, + if (onlyIfNotScheduled) ExistingPeriodicWorkPolicy.KEEP else ExistingPeriodicWorkPolicy.UPDATE, workRequest ) @@ -111,129 +84,40 @@ class WallpaperScheduler @Inject constructor( wallpaperMode: WallpaperMode ) { scheduledScreensToReset(screenType, settings, wallpaperMode).forEach { scheduledScreen -> - val interval = when (scheduledScreen) { - ScreenType.HOME, ScreenType.BOTH -> settings.homeIntervalMinutes - ScreenType.LOCK -> settings.lockIntervalMinutes - ScreenType.LIVE -> settings.liveIntervalMinutes - } scheduleWallpaperChange( screenType = scheduledScreen, - intervalMinutes = interval, + intervalMinutes = settings.intervalMinutes(scheduledScreen), resetInterval = true ) } } - /** - * Schedule both home and lock wallpaper changes - * - * @param homeIntervalMinutes Home screen interval (0 to disable) - * @param lockIntervalMinutes Lock screen interval (0 to disable) - * @param synchronized Whether home and lock should use the same wallpaper (when intervals match) - * @param networkRequired Whether network is required - * @param requireCharging Whether device must be charging - * @param onlyIfNotScheduled If true, only schedule if work is not already scheduled (for app startup) - */ - suspend fun scheduleWallpaperChanges( - homeIntervalMinutes: Int, - lockIntervalMinutes: Int, - synchronized: Boolean = false, - networkRequired: Boolean = false, - requireCharging: Boolean = false, + /** Reconcile all jobs from the same policy on startup, settings edits and album selection. */ + suspend fun updateSchedules( + settings: ScheduleSettings, + mode: WallpaperMode, onlyIfNotScheduled: Boolean = false - ) { - mutex.withLock { - // Don't cancel all first - let UPDATE policy handle existing work - // This prevents immediate wallpaper change when just updating intervals - - // Check if both should be synchronized (same interval, synchronized flag set) - val shouldSync = synchronized && - homeIntervalMinutes > 0 && - lockIntervalMinutes > 0 && - homeIntervalMinutes == lockIntervalMinutes - - if (shouldSync) { - // When synchronized, schedule a single BOTH job that sets both screens - // This ensures both screens always show the same wallpaper - if (!onlyIfNotScheduled || !isWorkScheduled(ScreenType.BOTH)) { - scheduleWallpaperChange( - ScreenType.BOTH, - homeIntervalMinutes, - networkRequired, - requireCharging - ) - // Cancel any existing separate HOME/LOCK jobs - cancelWallpaperChange(ScreenType.HOME) - cancelWallpaperChange(ScreenType.LOCK) - Log.d(TAG, "Scheduled synchronized wallpaper changes (BOTH) every $homeIntervalMinutes minutes") - } else { - Log.d(TAG, "Skipped scheduling BOTH wallpaper changes - already scheduled") - } - } else { - // Independent schedules - schedule or cancel each separately - // Check if BOTH was scheduled BEFORE cancelling it - // This is needed to force schedule HOME/LOCK when switching from sync mode - val wasBothScheduled = isWorkScheduled(ScreenType.BOTH) - - // Cancel BOTH job if it exists (switching from sync to separate mode) - cancelWallpaperChange(ScreenType.BOTH) - - // When switching away from sync mode, we must ensure HOME/LOCK are scheduled - // even if onlyIfNotScheduled is true, because they were previously suppressed - val forceSchedule = wasBothScheduled - - if (homeIntervalMinutes > 0) { - if (!onlyIfNotScheduled || forceSchedule || !isWorkScheduled(ScreenType.HOME)) { - scheduleWallpaperChange( - ScreenType.HOME, - homeIntervalMinutes, - networkRequired, - requireCharging - ) - } else { - Log.d(TAG, "Skipped scheduling HOME wallpaper changes - already scheduled") - } - } else { - cancelWallpaperChange(ScreenType.HOME) - } - - if (lockIntervalMinutes > 0) { - if (!onlyIfNotScheduled || forceSchedule || !isWorkScheduled(ScreenType.LOCK)) { - scheduleWallpaperChange( - ScreenType.LOCK, - lockIntervalMinutes, - networkRequired, - requireCharging - ) - } else { - Log.d(TAG, "Skipped scheduling LOCK wallpaper changes - already scheduled") - } - } else { - cancelWallpaperChange(ScreenType.LOCK) - } - } - - // Schedule daily album refresh to validate all albums - if (!onlyIfNotScheduled || !isAlbumRefreshScheduled()) { - scheduleAlbumRefresh() - } else { - Log.d(TAG, "Skipped scheduling album refresh - already scheduled") - } + ) = mutex.withLock { + val enabled = settings.enableChanger && settings.hasRequiredAlbums(mode) + val targets = if (enabled) settings.activeScreens(mode) else emptySet() + for (screen in ScreenType.entries) { + val interval = settings.intervalMinutes(screen) + val handledByEngine = screen == ScreenType.LIVE && interval < Constants.MIN_INTERVAL_MINUTES + if (screen in targets && interval > 0 && !handledByEngine) { + scheduleWallpaperChange(screen, interval, onlyIfNotScheduled = onlyIfNotScheduled) + } else { + cancelWallpaperChange(screen) + } } + if (enabled) scheduleAlbumRefresh(onlyIfNotScheduled) else cancelAlbumRefresh() } - /** - * Cancel wallpaper change schedule for specific screen - */ fun cancelWallpaperChange(screenType: ScreenType) { val workName = getWorkName(screenType) workManager.cancelUniqueWork(workName) Log.d(TAG, "Cancelled $screenType wallpaper change schedule") } - /** - * Cancel all wallpaper change schedules - */ fun cancelAllWallpaperChanges() { workManager.cancelUniqueWork(Constants.WORK_NAME_HOME) workManager.cancelUniqueWork(Constants.WORK_NAME_LOCK) @@ -243,20 +127,8 @@ class WallpaperScheduler @Inject constructor( Log.d(TAG, "Cancelled all wallpaper change schedules") } - /** - * Schedule daily album refresh worker - * - * Runs once per day (typically at 3 AM) to validate and refresh all albums: - * - Validates all wallpaper and folder URIs in all albums - * - Removes invalid entries (deleted files, permission changes, etc.) - * - Rescans all folders for new wallpapers and adds them to albums - */ - fun scheduleAlbumRefresh() { - val constraints = Constraints.Builder() - .setRequiredNetworkType(NetworkType.NOT_REQUIRED) - .build() - - // Calculate initial delay to target 3 AM + /** Refresh daily, with the first run targeting 3 AM. */ + fun scheduleAlbumRefresh(onlyIfNotScheduled: Boolean = false) { val calendar = Calendar.getInstance() val nowMillis = calendar.timeInMillis @@ -274,23 +146,19 @@ class WallpaperScheduler @Inject constructor( 1, TimeUnit.DAYS ) - .setConstraints(constraints) .setInitialDelay(initialDelay, TimeUnit.MILLISECONDS) .addTag(Constants.WORK_TAG_REFRESH) .build() workManager.enqueueUniquePeriodicWork( Constants.WORK_NAME_REFRESH, - ExistingPeriodicWorkPolicy.UPDATE, + if (onlyIfNotScheduled) ExistingPeriodicWorkPolicy.KEEP else ExistingPeriodicWorkPolicy.UPDATE, workRequest ) Log.d(TAG, "Scheduled daily album refresh") } - /** - * Cancel daily album refresh worker - */ fun cancelAlbumRefresh() { workManager.cancelUniqueWork(Constants.WORK_NAME_REFRESH) Log.d(TAG, "Cancelled daily album refresh") @@ -314,87 +182,20 @@ class WallpaperScheduler @Inject constructor( } } - /** - * Check if wallpaper change work is already scheduled - * - * @param screenType Screen type to check - * @return true if work is scheduled (ENQUEUED or RUNNING), false otherwise - */ - private suspend fun isWorkScheduled(screenType: ScreenType): Boolean { - val workName = getWorkName(screenType) - val workInfos = try { - workManager.getWorkInfosForUniqueWorkFlow(workName).first() - } catch (e: Exception) { - Log.e(TAG, "Error checking work status", e) - return false - } - - if (workInfos.isEmpty()) return false - - return workInfos.any { workInfo -> - workInfo.state == androidx.work.WorkInfo.State.ENQUEUED || - workInfo.state == androidx.work.WorkInfo.State.RUNNING - } - } - - /** - * Check if album refresh work is already scheduled - * - * @return true if work is scheduled (ENQUEUED or RUNNING), false otherwise - */ - private suspend fun isAlbumRefreshScheduled(): Boolean { - val workInfos = try { - workManager.getWorkInfosForUniqueWorkFlow(Constants.WORK_NAME_REFRESH).first() - } catch (e: Exception) { - Log.e(TAG, "Error checking refresh status", e) - return false - } - - if (workInfos.isEmpty()) return false - - return workInfos.any { workInfo -> - workInfo.state == androidx.work.WorkInfo.State.ENQUEUED || - workInfo.state == androidx.work.WorkInfo.State.RUNNING - } - } } -/** Pure scheduling policy shared with tests. */ internal fun scheduledScreensToReset( manualScreen: ScreenType, settings: ScheduleSettings, wallpaperMode: WallpaperMode ): Set { - if (!settings.enableChanger) return emptySet() - - if (wallpaperMode == WallpaperMode.LIVE) { - return if ( - manualScreen == ScreenType.LIVE && - settings.liveAlbumId != null && - settings.liveIntervalMinutes >= Constants.MIN_INTERVAL_MINUTES - ) { - setOf(ScreenType.LIVE) - } else { - emptySet() - } - } - - if (manualScreen == ScreenType.LIVE) return emptySet() - - val homeActive = settings.homeEnabled && settings.homeAlbumId != null - val lockActive = settings.lockEnabled && settings.lockAlbumId != null - val synchronized = homeActive && lockActive && - settings.homeAlbumId == settings.lockAlbumId && - !settings.separateSchedules - - if (synchronized) return setOf(ScreenType.BOTH) - - return buildSet { - if ((manualScreen == ScreenType.HOME || manualScreen == ScreenType.BOTH) && homeActive) { - add(ScreenType.HOME) - } - if ((manualScreen == ScreenType.LOCK || manualScreen == ScreenType.BOTH) && lockActive) { - add(ScreenType.LOCK) + if (!settings.enableChanger || !settings.hasRequiredAlbums(wallpaperMode)) return emptySet() + return settings.activeScreens(wallpaperMode).filterTo(mutableSetOf()) { screen -> + when (screen) { + ScreenType.LIVE -> manualScreen == ScreenType.LIVE && + settings.liveIntervalMinutes >= Constants.MIN_INTERVAL_MINUTES + ScreenType.BOTH -> manualScreen != ScreenType.LIVE + else -> manualScreen == screen || manualScreen == ScreenType.BOTH } } } diff --git a/app/src/main/res/values-b+zh+Hans/strings.xml b/app/src/main/res/values-b+zh+Hans/strings.xml index e3314fd..64e5c91 100644 --- a/app/src/main/res/values-b+zh+Hans/strings.xml +++ b/app/src/main/res/values-b+zh+Hans/strings.xml @@ -1,5 +1,6 @@ + 无法创建相册,请重试。 Paperize 正在添加文件夹… 正在添加壁纸… @@ -10,29 +11,28 @@ 壁纸 图库 返回 - 添加文件夹 + 添加文件夹 添加相册 输入相册名称 相册名称 取消 保存 删除 - 重命名 未选择相册 当前选中的相册 同意 欢迎 - 开始使用 + 开始使用 允许 隐私政策 恢复默认 重置所有数据 确定要将所有设置和数据恢复默认吗? 确定 - 已选择 %1$s + 已选择 %1$s 请阅读并同意以下隐私声明后使用本应用。 隐私声明 - 确定要删除吗? + 确定要删除吗? 删除相册? 动画 提升视觉观感 @@ -43,7 +43,7 @@ 点击此处查看我们的隐私政策 外观 关于 - + %d 张壁纸 简介 @@ -58,7 +58,7 @@ 空相册 这个相册里还没有壁纸。请先向相册中添加壁纸,然后再选择它。 确定 - 填充 + 填充 适应 拉伸 亮度效果 @@ -68,7 +68,7 @@ 显示间隔滑块 时间间隔 模糊效果 - 锁屏 + 锁屏 暗角效果 无 灰度滤镜 @@ -78,7 +78,7 @@ 随机 天 小时 - 调整画面亮度 + 调整画面亮度 为画面添加模糊 压暗画面边缘 将画面变为灰度 @@ -90,7 +90,7 @@ 在桌面页面之间滑动可移动壁纸(需要桌面支持) Paperize 动态壁纸 带特效与交互功能的动态壁纸 - 自适应亮度 + 自适应亮度 根据深色/浅色模式调整亮度 随机打乱壁纸顺序 正在更换壁纸… @@ -112,8 +112,6 @@ 保存 当前锁屏壁纸 当前主屏幕壁纸 - 已选择 - 未选择 已启用 @@ -130,8 +128,6 @@ 交互效果 当前壁纸 - - 名称(A-Z) 名称(Z-A) @@ -150,22 +146,21 @@ 分 低于 15 分钟的间隔仅在 Paperize 作为可见的动态壁纸运行时生效。 - + 壁纸更换通知 相册中没有壁纸 相册为空,壁纸更换已停用。 - 无法构建壁纸队列 多次重试后仍未找到有效壁纸 这张壁纸已不可用。 应用单张壁纸前,请先切换到静态壁纸模式。 - + 视差效果在你的系统或桌面上可能无法生效。 - + 小时 @@ -175,8 +170,6 @@ 点击 + 创建你的第一个相册 - - 相册 选择壁纸模式 之后可以在设置中更改 @@ -188,7 +181,7 @@ 选择动态壁纸 若想以动态壁纸模式使用 Paperize,你需要在系统设置中把它选为动态壁纸。 - 打开壁纸选择器 + 打开壁纸选择器 稍后 @@ -230,4 +223,7 @@ 刷新文件夹 已检查文件夹中的新壁纸。 无法刷新此文件夹。请确认文件夹可访问后重试。 + 无法加载相册。请返回后重试。 + 无法保存顺序。请重试。 + 无法完成数据重置,请重试。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b8f2d40..d4a8fe3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,5 +1,6 @@ + Could not create the album. Please try again. Paperize Adding folder… Adding wallpapers… @@ -10,29 +11,28 @@ Wallpaper Library Back - Add folder + Add folder Add album Enter the name of the album Album Name Cancel Save Delete - Edit Name No album selected Currently selected album Agree Welcome - I\'m In + I\'m In Allow Privacy Policy Reset to default Reset all data Are you sure you want to reset all settings and data to default? Confirm - %1$s selected + %1$s selected Please read and agree to the following privacy notice to use the app. Privacy Notice - Are you sure you want to delete this? + Are you sure you want to delete this? Delete album? Animation Increase visual appeal @@ -43,7 +43,7 @@ Click here to view our privacy policy Appearance About - + %d wallpaper %d wallpapers @@ -59,7 +59,7 @@ Empty Album This album has no wallpapers. Please add wallpapers to the album before selecting it. OK - Fill + Fill Fit Stretch Brightness Effect @@ -69,7 +69,7 @@ Show interval sliders Time Interval Blur Effect - Lock + Lock Vignette Effect None Gray Filter @@ -79,7 +79,7 @@ Shuffle Days Hours - Change the image brightness + Change the image brightness Add blur to the image Darken the edges of the image Make the colors grayscale @@ -91,7 +91,7 @@ Swipe between home-screen pages to move the wallpaper (launcher support required) Paperize Live Wallpaper Dynamic wallpapers with effects and interactive features - Adaptive Brightness + Adaptive Brightness Adjust brightness based on dark/light mode Randomly shuffle the wallpapers Changing wallpaper… @@ -113,8 +113,6 @@ Save Current lock screen wallpaper Current home screen wallpaper - Selected - Not selected Enabled @@ -131,8 +129,6 @@ Interactive Effects Current Wallpapers - - Name (A-Z) Name (Z-A) @@ -151,22 +147,21 @@ min Intervals under 15 minutes run only while Paperize is the visible live wallpaper. - + Wallpaper change notifications No wallpapers in album Wallpaper changer has been disabled because the album is empty. - Failed to build wallpaper queue Could not find a valid wallpaper after retries This wallpaper is no longer available. Switch to static wallpaper mode before applying an individual wallpaper. - + Parallax effect may not work with your OEM or launcher. - + hour hours @@ -178,8 +173,6 @@ Tap + to create your first album - - Album Choose Wallpaper Mode You can change this later in settings @@ -191,7 +184,7 @@ Select Live Wallpaper To use Paperize in Live Wallpaper mode, you need to select it as your live wallpaper from the system settings. - Open Wallpaper Picker + Open Wallpaper Picker Later @@ -233,4 +226,7 @@ Refresh folder Folder checked for new wallpapers. Could not refresh this folder. Check that it is accessible, then try again. + Could not load the album. Go back and try again. + Could not save the order. Please try again. + Could not finish resetting data. Please try again. diff --git a/app/src/test/java/com/anthonyla/paperize/core/ResultTest.kt b/app/src/test/java/com/anthonyla/paperize/core/ResultTest.kt index 3f18cd2..4d3eca8 100644 --- a/app/src/test/java/com/anthonyla/paperize/core/ResultTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/core/ResultTest.kt @@ -1,280 +1,20 @@ package com.anthonyla.paperize.core -import org.junit.Assert.* +import kotlinx.coroutines.CancellationException +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows import org.junit.Test -/** - * Unit tests for Result sealed class - */ class ResultTest { - - // ============================================================ - // Test: Success - // ============================================================ - @Test - fun `Success isSuccess returns true`() { - val result: Result = Result.Success("data") - assertTrue(result.isSuccess) + fun `captured failure retains the original exception when unwrapped`() { + val failure = IllegalStateException("boom") + val result = Result.runCatching { throw failure } + assertSame(failure, assertThrows(IllegalStateException::class.java) { result.getOrThrow() }) } - @Test - fun `Success isError returns false`() { - val result: Result = Result.Success("data") - assertFalse(result.isError) - } - - @Test - fun `Success isLoading returns false`() { - val result: Result = Result.Success("data") - assertFalse(result.isLoading) - } - - @Test - fun `Success getOrNull returns data`() { - val result: Result = Result.Success("test data") - assertEquals("test data", result.getOrNull()) - } - - @Test - fun `Success exceptionOrNull returns null`() { - val result: Result = Result.Success("data") - assertNull(result.exceptionOrNull()) - } - - // ============================================================ - // Test: Error - // ============================================================ - - @Test - fun `Error isError returns true`() { - val result: Result = Result.Error(Exception("error")) - assertTrue(result.isError) - } - - @Test - fun `Error isSuccess returns false`() { - val result: Result = Result.Error(Exception("error")) - assertFalse(result.isSuccess) - } - - @Test - fun `Error isLoading returns false`() { - val result: Result = Result.Error(Exception("error")) - assertFalse(result.isLoading) - } - - @Test - fun `Error getOrNull returns null`() { - val result: Result = Result.Error(Exception("error")) - assertNull(result.getOrNull()) - } - - @Test - fun `Error exceptionOrNull returns exception`() { - val exception = Exception("test error") - val result: Result = Result.Error(exception) - assertEquals(exception, result.exceptionOrNull()) - } - - @Test - fun `Error message defaults to exception message`() { - val result = Result.Error(Exception("my error message")) - assertEquals("my error message", result.message) - } - - @Test - fun `Error can have custom message`() { - val result = Result.Error(Exception("original"), message = "custom message") - assertEquals("custom message", result.message) - } - - // ============================================================ - // Test: Loading - // ============================================================ - - @Test - fun `Loading isLoading returns true`() { - val result: Result = Result.Loading - assertTrue(result.isLoading) - } - - @Test - fun `Loading isSuccess returns false`() { - val result: Result = Result.Loading - assertFalse(result.isSuccess) - } - - @Test - fun `Loading isError returns false`() { - val result: Result = Result.Loading - assertFalse(result.isError) - } - - @Test - fun `Loading getOrNull returns null`() { - val result: Result = Result.Loading - assertNull(result.getOrNull()) - } - - // ============================================================ - // Test: onSuccess callback - // ============================================================ - - @Test - fun `onSuccess executes callback for Success`() { - var callbackExecuted = false - var receivedData: String? = null - - Result.Success("my data").onSuccess { - callbackExecuted = true - receivedData = it - } - - assertTrue(callbackExecuted) - assertEquals("my data", receivedData) - } - - @Test - fun `onSuccess does not execute callback for Error`() { - var callbackExecuted = false - - Result.Error(Exception("error")).onSuccess { - callbackExecuted = true - } - - assertFalse(callbackExecuted) - } - - @Test - fun `onSuccess returns same result for chaining`() { - val result = Result.Success("data") - val returned = result.onSuccess { } - assertSame(result, returned) - } - - // ============================================================ - // Test: onError callback - // ============================================================ - - @Test - fun `onError executes callback for Error`() { - var callbackExecuted = false - val exception = Exception("test error") - - Result.Error(exception).onError { - callbackExecuted = true - assertEquals(exception, it) - } - - assertTrue(callbackExecuted) - } - - @Test - fun `onError does not execute callback for Success`() { - var callbackExecuted = false - - Result.Success("data").onError { - callbackExecuted = true - } - - assertFalse(callbackExecuted) - } - - @Test - fun `onError returns same result for chaining`() { - val result: Result = Result.Error(Exception("error")) - val returned = result.onError { } - assertSame(result, returned) - } - - // ============================================================ - // Test: map extension - // ============================================================ - - @Test - fun `map transforms Success data`() { - val result = Result.Success(5) - val mapped = result.map { it * 2 } - - assertTrue(mapped.isSuccess) - assertEquals(10, mapped.getOrNull()) - } - - @Test - fun `map preserves Error`() { - val exception = Exception("error") - val result: Result = Result.Error(exception, "custom message") - val mapped = result.map { it * 2 } - - assertTrue(mapped.isError) - assertEquals(exception, mapped.exceptionOrNull()) - } - - @Test - fun `map preserves Loading`() { - val result: Result = Result.Loading - val mapped = result.map { it * 2 } - - assertTrue(mapped.isLoading) - } - - // ============================================================ - // Test: flatMap extension - // ============================================================ - - @Test - fun `flatMap transforms Success to Success`() { - val result = Result.Success(5) - val flatMapped = result.flatMap { Result.Success(it.toString()) } - - assertTrue(flatMapped.isSuccess) - assertEquals("5", flatMapped.getOrNull()) - } - - @Test - fun `flatMap transforms Success to Error`() { - val result = Result.Success(5) - val flatMapped = result.flatMap { Result.Error(Exception("failed")) } - - assertTrue(flatMapped.isError) - } - - @Test - fun `flatMap preserves Error`() { - val exception = Exception("original error") - val result: Result = Result.Error(exception) - val flatMapped = result.flatMap { Result.Success(it.toString()) } - - assertTrue(flatMapped.isError) - assertEquals(exception, flatMapped.exceptionOrNull()) - } - - @Test - fun `flatMap preserves Loading`() { - val result: Result = Result.Loading - val flatMapped = result.flatMap { Result.Success(it.toString()) } - - assertTrue(flatMapped.isLoading) - } - - // ============================================================ - // Test: runCatching companion - // ============================================================ - - @Test - fun `runCatching returns Success when block succeeds`() { - val result = Result.runCatching { 42 } - - assertTrue(result.isSuccess) - assertEquals(42, result.getOrNull()) - } - - @Test - fun `runCatching returns Error when block throws`() { - val result = Result.runCatching { throw IllegalStateException("boom") } - - assertTrue(result.isError) - assertTrue(result.exceptionOrNull() is IllegalStateException) + @Test(expected = CancellationException::class) + fun `runCatching propagates cancellation`() { + Result.runCatching { throw CancellationException() } } } diff --git a/app/src/test/java/com/anthonyla/paperize/core/ScalingTypeTest.kt b/app/src/test/java/com/anthonyla/paperize/core/ScalingTypeTest.kt deleted file mode 100644 index 92e1181..0000000 --- a/app/src/test/java/com/anthonyla/paperize/core/ScalingTypeTest.kt +++ /dev/null @@ -1,93 +0,0 @@ -package com.anthonyla.paperize.core - -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for ScalingType enum - */ -class ScalingTypeTest { - - // ============================================================ - // Test: fromString - // ============================================================ - - @Test - fun `fromString with FILL returns FILL`() { - assertEquals(ScalingType.FILL, ScalingType.fromString("FILL")) - } - - @Test - fun `fromString with FIT returns FIT`() { - assertEquals(ScalingType.FIT, ScalingType.fromString("FIT")) - } - - @Test - fun `fromString with STRETCH returns STRETCH`() { - assertEquals(ScalingType.STRETCH, ScalingType.fromString("STRETCH")) - } - - @Test - fun `fromString with NONE returns NONE`() { - assertEquals(ScalingType.NONE, ScalingType.fromString("NONE")) - } - - @Test - fun `fromString is case insensitive`() { - assertEquals(ScalingType.FILL, ScalingType.fromString("fill")) - assertEquals(ScalingType.FILL, ScalingType.fromString("Fill")) - assertEquals(ScalingType.FIT, ScalingType.fromString("fit")) - assertEquals(ScalingType.FIT, ScalingType.fromString("Fit")) - assertEquals(ScalingType.STRETCH, ScalingType.fromString("stretch")) - assertEquals(ScalingType.NONE, ScalingType.fromString("none")) - } - - @Test - fun `fromString with null returns FILL as default`() { - assertEquals(ScalingType.FILL, ScalingType.fromString(null)) - } - - @Test - fun `fromString with empty string returns FILL as default`() { - assertEquals(ScalingType.FILL, ScalingType.fromString("")) - } - - @Test - fun `fromString with invalid value returns FILL as default`() { - assertEquals(ScalingType.FILL, ScalingType.fromString("invalid")) - assertEquals(ScalingType.FILL, ScalingType.fromString("crop")) - assertEquals(ScalingType.FILL, ScalingType.fromString("center")) - assertEquals(ScalingType.FILL, ScalingType.fromString("123")) - } - - @Test - fun `fromString with whitespace returns FILL as default`() { - assertEquals(ScalingType.FILL, ScalingType.fromString(" ")) - assertEquals(ScalingType.FILL, ScalingType.fromString(" FILL ")) - } - - // ============================================================ - // Test: Enum values - // ============================================================ - - @Test - fun `enum has exactly four values`() { - assertEquals(4, ScalingType.entries.size) - } - - @Test - fun `enum values are FILL, FIT, STRETCH, NONE`() { - assertTrue(ScalingType.entries.contains(ScalingType.FILL)) - assertTrue(ScalingType.entries.contains(ScalingType.FIT)) - assertTrue(ScalingType.entries.contains(ScalingType.STRETCH)) - assertTrue(ScalingType.entries.contains(ScalingType.NONE)) - } - - @Test - fun `enum names are correct`() { - assertEquals("FILL", ScalingType.FILL.name) - assertEquals("FIT", ScalingType.FIT.name) - assertEquals("STRETCH", ScalingType.STRETCH.name) - assertEquals("NONE", ScalingType.NONE.name) - } -} diff --git a/app/src/test/java/com/anthonyla/paperize/core/ScreenTypeTest.kt b/app/src/test/java/com/anthonyla/paperize/core/ScreenTypeTest.kt deleted file mode 100644 index 67dfe53..0000000 --- a/app/src/test/java/com/anthonyla/paperize/core/ScreenTypeTest.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.anthonyla.paperize.core - -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for ScreenType enum - */ -class ScreenTypeTest { - - // ============================================================ - // Test: fromString - // ============================================================ - - @Test - fun `fromString with HOME returns HOME`() { - assertEquals(ScreenType.HOME, ScreenType.fromString("HOME")) - } - - @Test - fun `fromString with LOCK returns LOCK`() { - assertEquals(ScreenType.LOCK, ScreenType.fromString("LOCK")) - } - - @Test - fun `fromString with BOTH returns BOTH`() { - assertEquals(ScreenType.BOTH, ScreenType.fromString("BOTH")) - } - - @Test - fun `fromString with LIVE returns LIVE`() { - assertEquals(ScreenType.LIVE, ScreenType.fromString("LIVE")) - } - - @Test - fun `fromString is case insensitive for home`() { - assertEquals(ScreenType.HOME, ScreenType.fromString("home")) - assertEquals(ScreenType.HOME, ScreenType.fromString("Home")) - assertEquals(ScreenType.HOME, ScreenType.fromString("HOME")) - } - - @Test - fun `fromString is case insensitive for lock`() { - assertEquals(ScreenType.LOCK, ScreenType.fromString("lock")) - assertEquals(ScreenType.LOCK, ScreenType.fromString("Lock")) - } - - @Test - fun `fromString is case insensitive for both`() { - assertEquals(ScreenType.BOTH, ScreenType.fromString("both")) - assertEquals(ScreenType.BOTH, ScreenType.fromString("Both")) - } - - @Test - fun `fromString is case insensitive for live`() { - assertEquals(ScreenType.LIVE, ScreenType.fromString("live")) - assertEquals(ScreenType.LIVE, ScreenType.fromString("Live")) - } - - @Test - fun `fromString with null returns BOTH as default`() { - assertEquals(ScreenType.BOTH, ScreenType.fromString(null)) - } - - @Test - fun `fromString with empty string returns BOTH as default`() { - assertEquals(ScreenType.BOTH, ScreenType.fromString("")) - } - - @Test - fun `fromString with invalid value returns BOTH as default`() { - assertEquals(ScreenType.BOTH, ScreenType.fromString("invalid")) - assertEquals(ScreenType.BOTH, ScreenType.fromString("screen")) - assertEquals(ScreenType.BOTH, ScreenType.fromString("123")) - } - - @Test - fun `fromString with whitespace returns BOTH as default`() { - assertEquals(ScreenType.BOTH, ScreenType.fromString(" ")) - assertEquals(ScreenType.BOTH, ScreenType.fromString(" HOME ")) - } - - // ============================================================ - // Test: Enum values - // ============================================================ - - @Test - fun `enum has exactly four values`() { - assertEquals(4, ScreenType.entries.size) - } - - @Test - fun `enum values are HOME, LOCK, BOTH, LIVE`() { - assertTrue(ScreenType.entries.contains(ScreenType.HOME)) - assertTrue(ScreenType.entries.contains(ScreenType.LOCK)) - assertTrue(ScreenType.entries.contains(ScreenType.BOTH)) - assertTrue(ScreenType.entries.contains(ScreenType.LIVE)) - } - - @Test - fun `enum names are correct`() { - assertEquals("HOME", ScreenType.HOME.name) - assertEquals("LOCK", ScreenType.LOCK.name) - assertEquals("BOTH", ScreenType.BOTH.name) - assertEquals("LIVE", ScreenType.LIVE.name) - } -} diff --git a/app/src/test/java/com/anthonyla/paperize/core/StoredEnumTest.kt b/app/src/test/java/com/anthonyla/paperize/core/StoredEnumTest.kt new file mode 100644 index 0000000..3441be8 --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/core/StoredEnumTest.kt @@ -0,0 +1,23 @@ +package com.anthonyla.paperize.core + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class StoredEnumTest { + @Test fun storedNamesAcceptEitherCase() { + ScalingType.entries.forEach { assertEquals(it, ScalingType.fromString(it.name.lowercase())) } + ScreenType.entries.forEach { assertEquals(it, ScreenType.fromString(it.name.lowercase())) } + WallpaperMode.entries.forEach { assertEquals(it, WallpaperMode.fromString(it.name.lowercase())) } + WallpaperMediaType.entries.forEach { assertEquals(it, WallpaperMediaType.fromString(it.name.lowercase())) } + } + + @Test fun missingOrUnrecognizedValuesUseTheirStorageDefaults() { + listOf(null, "", "unrecognized").forEach { + assertEquals(ScalingType.FILL, ScalingType.fromString(it)) + assertEquals(ScreenType.BOTH, ScreenType.fromString(it)) + assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(it)) + assertNull(WallpaperMediaType.fromString(it)) + } + } +} diff --git a/app/src/test/java/com/anthonyla/paperize/core/WallpaperMediaTypeTest.kt b/app/src/test/java/com/anthonyla/paperize/core/WallpaperMediaTypeTest.kt deleted file mode 100644 index 025298a..0000000 --- a/app/src/test/java/com/anthonyla/paperize/core/WallpaperMediaTypeTest.kt +++ /dev/null @@ -1,238 +0,0 @@ -package com.anthonyla.paperize.core - -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for WallpaperMediaType enum - */ -class WallpaperMediaTypeTest { - - // ============================================================ - // Test: fromExtension - JPEG formats - // ============================================================ - - @Test - fun `fromExtension with jpg returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("jpg")) - } - - @Test - fun `fromExtension with jpeg returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("jpeg")) - } - - // ============================================================ - // Test: fromExtension - Modern formats - // ============================================================ - - @Test - fun `fromExtension with png returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("png")) - } - - @Test - fun `fromExtension with webp returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("webp")) - } - - @Test - fun `fromExtension with avif returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("avif")) - } - - // ============================================================ - // Test: fromExtension - Apple formats - // ============================================================ - - @Test - fun `fromExtension with heic returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("heic")) - } - - @Test - fun `fromExtension with heif returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("heif")) - } - - // ============================================================ - // Test: fromExtension - Legacy formats - // ============================================================ - - @Test - fun `fromExtension with bmp returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("bmp")) - } - - @Test - fun `fromExtension with gif returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("gif")) - } - - @Test - fun `fromExtension with tiff returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("tiff")) - } - - @Test - fun `fromExtension with tif returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("tif")) - } - - // ============================================================ - // Test: fromExtension - Vector format - // ============================================================ - - @Test - fun `fromExtension with svg returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("svg")) - } - - // ============================================================ - // Test: fromExtension - Case insensitivity - // ============================================================ - - @Test - fun `fromExtension is case insensitive for uppercase`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("JPG")) - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("PNG")) - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("WEBP")) - } - - @Test - fun `fromExtension is case insensitive for mixed case`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("Jpg")) - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("PnG")) - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromExtension("WebP")) - } - - // ============================================================ - // Test: fromExtension - Unsupported/Invalid extensions - // ============================================================ - - @Test - fun `fromExtension with unsupported extension returns null`() { - assertNull(WallpaperMediaType.fromExtension("mp4")) - assertNull(WallpaperMediaType.fromExtension("mp3")) - assertNull(WallpaperMediaType.fromExtension("pdf")) - assertNull(WallpaperMediaType.fromExtension("txt")) - assertNull(WallpaperMediaType.fromExtension("doc")) - } - - @Test - fun `fromExtension with empty string returns null`() { - assertNull(WallpaperMediaType.fromExtension("")) - } - - @Test - fun `fromExtension with whitespace returns null`() { - assertNull(WallpaperMediaType.fromExtension(" ")) - assertNull(WallpaperMediaType.fromExtension(" ")) - } - - // ============================================================ - // Test: fromString - Valid values - // ============================================================ - - @Test - fun `fromString with IMAGE returns IMAGE`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("IMAGE")) - } - - @Test - fun `fromString is case insensitive`() { - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("image")) - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("Image")) - assertEquals(WallpaperMediaType.IMAGE, WallpaperMediaType.fromString("iMaGe")) - } - - // ============================================================ - // Test: fromString - Invalid/null values - // ============================================================ - - @Test - fun `fromString with null returns null`() { - assertNull(WallpaperMediaType.fromString(null)) - } - - @Test - fun `fromString with empty string returns null`() { - assertNull(WallpaperMediaType.fromString("")) - } - - @Test - fun `fromString with invalid value returns null`() { - assertNull(WallpaperMediaType.fromString("invalid")) - assertNull(WallpaperMediaType.fromString("video")) - assertNull(WallpaperMediaType.fromString("IMAGES")) - } - - // ============================================================ - // Test: supportedExtensions property - // ============================================================ - - @Test - fun `IMAGE supportedExtensions contains all expected formats`() { - val extensions = WallpaperMediaType.IMAGE.supportedExtensions - - // JPEG formats - assertTrue(extensions.contains("jpg")) - assertTrue(extensions.contains("jpeg")) - - // Modern formats - assertTrue(extensions.contains("png")) - assertTrue(extensions.contains("webp")) - assertTrue(extensions.contains("avif")) - - // Apple formats - assertTrue(extensions.contains("heic")) - assertTrue(extensions.contains("heif")) - - // Legacy formats - assertTrue(extensions.contains("bmp")) - assertTrue(extensions.contains("gif")) - assertTrue(extensions.contains("tiff")) - assertTrue(extensions.contains("tif")) - - // Vector - assertTrue(extensions.contains("svg")) - } - - @Test - fun `IMAGE supportedExtensions has expected count`() { - // jpg, jpeg, png, webp, avif, heic, heif, bmp, gif, tiff, tif, svg = 12 - assertEquals(12, WallpaperMediaType.IMAGE.supportedExtensions.size) - } - - // ============================================================ - // Test: supportedInStaticMode property - // ============================================================ - - @Test - fun `IMAGE is supported in static mode`() { - assertTrue(WallpaperMediaType.IMAGE.supportedInStaticMode) - } - - // ============================================================ - // Test: supportedInLiveMode property - // ============================================================ - - @Test - fun `IMAGE is supported in live mode`() { - assertTrue(WallpaperMediaType.IMAGE.supportedInLiveMode) - } - - // ============================================================ - // Test: Enum values - // ============================================================ - - @Test - fun `enum has exactly one value`() { - assertEquals(1, WallpaperMediaType.entries.size) - } - - @Test - fun `enum value name is IMAGE`() { - assertEquals("IMAGE", WallpaperMediaType.IMAGE.name) - } -} diff --git a/app/src/test/java/com/anthonyla/paperize/core/WallpaperModeTest.kt b/app/src/test/java/com/anthonyla/paperize/core/WallpaperModeTest.kt deleted file mode 100644 index b8fb70e..0000000 --- a/app/src/test/java/com/anthonyla/paperize/core/WallpaperModeTest.kt +++ /dev/null @@ -1,86 +0,0 @@ -package com.anthonyla.paperize.core - -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for WallpaperMode enum - */ -class WallpaperModeTest { - - // ============================================================ - // Test: fromString - // ============================================================ - - @Test - fun `fromString with STATIC returns STATIC`() { - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("STATIC")) - } - - @Test - fun `fromString with LIVE returns LIVE`() { - assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("LIVE")) - } - - @Test - fun `fromString is case insensitive for static`() { - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("static")) - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("Static")) - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("STATIC")) - } - - @Test - fun `fromString is case insensitive for live`() { - assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("live")) - assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("Live")) - assertEquals(WallpaperMode.LIVE, WallpaperMode.fromString("LIVE")) - } - - @Test - fun `fromString with null returns STATIC as default`() { - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(null)) - } - - @Test - fun `fromString with empty string returns STATIC as default`() { - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("")) - } - - @Test - fun `fromString with invalid value returns STATIC as default`() { - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("invalid")) - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("dynamic")) - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString("123")) - } - - @Test - fun `fromString with whitespace returns STATIC as default`() { - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(" ")) - assertEquals(WallpaperMode.STATIC, WallpaperMode.fromString(" STATIC ")) - } - - // ============================================================ - // Test: Enum values - // ============================================================ - - @Test - fun `enum has exactly two values`() { - assertEquals(2, WallpaperMode.entries.size) - } - - @Test - fun `enum values are STATIC and LIVE`() { - assertTrue(WallpaperMode.entries.contains(WallpaperMode.STATIC)) - assertTrue(WallpaperMode.entries.contains(WallpaperMode.LIVE)) - } - - @Test - fun `STATIC name is correct`() { - assertEquals("STATIC", WallpaperMode.STATIC.name) - } - - @Test - fun `LIVE name is correct`() { - assertEquals("LIVE", WallpaperMode.LIVE.name) - } -} diff --git a/app/src/test/java/com/anthonyla/paperize/core/util/BrightnessCalculatorTest.kt b/app/src/test/java/com/anthonyla/paperize/core/util/BrightnessCalculatorTest.kt index c349027..98ac6bd 100644 --- a/app/src/test/java/com/anthonyla/paperize/core/util/BrightnessCalculatorTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/core/util/BrightnessCalculatorTest.kt @@ -1,74 +1,28 @@ package com.anthonyla.paperize.core.util -import com.anthonyla.paperize.core.constants.Constants import org.junit.Assert.assertEquals import org.junit.Test class BrightnessCalculatorTest { - @Test - fun `calculateLuminance returns correct value for white`() { - // White = 0xFFFFFFFF - val white = 0xFFFFFFFF.toInt() - val luminance = BrightnessCalculator.calculateLuminance(white) - // 0.2126 * 1 + 0.7152 * 1 + 0.0722 * 1 = 1.0 - assertEquals(1.0, luminance, 0.001) + fun `luminance ignores alpha and weights color channels`() { + assertEquals(0.0, BrightnessCalculator.calculateLuminance(0xFF000000.toInt()), 0.001) + assertEquals(1.0, BrightnessCalculator.calculateLuminance(0xFFFFFFFF.toInt()), 0.001) + assertEquals(0.2126, BrightnessCalculator.calculateLuminance(0x00FF0000), 0.001) } @Test - fun `calculateLuminance returns correct value for black`() { - // Black = 0xFF000000 - val black = 0xFF000000.toInt() - val luminance = BrightnessCalculator.calculateLuminance(black) - assertEquals(0.0, luminance, 0.001) + fun `adaptive brightness changes only images at odds with the system theme`() { + assertEquals(0.7f, 0.9f * BrightnessCalculator.getAdaptiveMultiplier(true, 0.9f), 0.001f) + assertEquals(0.4f, 0.2f * BrightnessCalculator.getAdaptiveMultiplier(false, 0.2f), 0.001f) + assertEquals(1f, BrightnessCalculator.getAdaptiveMultiplier(true, 0.5f), 0.001f) + assertEquals(1f, BrightnessCalculator.getAdaptiveMultiplier(false, 0.5f), 0.001f) } @Test - fun `calculateLuminance returns correct value for red`() { - // Red = 0xFFFF0000 - val red = 0xFFFF0000.toInt() - val luminance = BrightnessCalculator.calculateLuminance(red) - assertEquals(Constants.LUMINANCE_RED, luminance, 0.001) - } - - @Test - fun `getAdaptiveMultiplier in dark mode darkens bright image`() { - // If brightness > LIGHT_BRIGHTNESS_MIN (0.8), should return TARGET_BRIGHTNESS_DARK / brightness - val brightness = 0.9f - val multiplier = BrightnessCalculator.getAdaptiveMultiplier(true, brightness) - val expected = Constants.TARGET_BRIGHTNESS_DARK / brightness - assertEquals(expected, multiplier, 0.001f) - } - - @Test - fun `getAdaptiveMultiplier in dark mode does not change dark image`() { - // If brightness <= LIGHT_BRIGHTNESS_MIN (0.8), should return 1.0 - val brightness = 0.5f - val multiplier = BrightnessCalculator.getAdaptiveMultiplier(true, brightness) - assertEquals(1.0f, multiplier, 0.001f) - } - - @Test - fun `getAdaptiveMultiplier in light mode brightens dark image`() { - // If brightness < DARK_BRIGHTNESS_MAX (0.3), should return TARGET_BRIGHTNESS_LIGHT / brightness - val brightness = 0.2f - val multiplier = BrightnessCalculator.getAdaptiveMultiplier(false, brightness) - val expected = Constants.TARGET_BRIGHTNESS_LIGHT / brightness - assertEquals(expected, multiplier, 0.001f) - } - - @Test - fun `getAdaptiveMultiplier in light mode does not change bright image`() { - // If brightness >= DARK_BRIGHTNESS_MAX (0.3), should return 1.0 - val brightness = 0.5f - val multiplier = BrightnessCalculator.getAdaptiveMultiplier(false, brightness) - assertEquals(1.0f, multiplier, 0.001f) - } - - @Test - fun `getAdaptiveMultiplier returns 1_0 for very dark items to avoid noise`() { - val brightness = 0.005f - val multiplier = BrightnessCalculator.getAdaptiveMultiplier(true, brightness) - assertEquals(1.0f, multiplier, 0.001f) + fun `near black images are not amplified or divided by zero`() { + listOf(0f, 0.005f).forEach { brightness -> + assertEquals(1f, BrightnessCalculator.getAdaptiveMultiplier(false, brightness), 0f) + } } } diff --git a/app/src/test/java/com/anthonyla/paperize/core/util/QueueBuilderTest.kt b/app/src/test/java/com/anthonyla/paperize/core/util/QueueBuilderTest.kt index 3f64346..ddba906 100644 --- a/app/src/test/java/com/anthonyla/paperize/core/util/QueueBuilderTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/core/util/QueueBuilderTest.kt @@ -1,206 +1,17 @@ package com.anthonyla.paperize.core.util -import org.junit.Assert.* +import org.junit.Assert.assertEquals import org.junit.Test -/** - * Unit tests for QueueBuilder utility - */ class QueueBuilderTest { - - // ============================================================ - // Test: buildSequentialQueue - // ============================================================ - @Test - fun `buildSequentialQueue sorts by display order`() { - val wallpapers = listOf( - "w3" to 2, - "w1" to 0, - "w2" to 1 + fun `merge keeps surviving order and appends new items once`() { + val merged = QueueBuilder.mergeWithExistingQueue( + existingQueueIds = listOf("third", "removed", "first"), + allWallpaperIds = listOf("first", "second", "third", "fourth") ) - - val queue = QueueBuilder.buildSequentialQueue(wallpapers) - - assertEquals(listOf("w1", "w2", "w3"), queue) + assertEquals(listOf("third", "first"), merged.take(2)) + assertEquals(setOf("second", "fourth"), merged.drop(2).toSet()) + assertEquals(4, merged.size) } - - @Test - fun `buildSequentialQueue handles empty list`() { - val queue = QueueBuilder.buildSequentialQueue(emptyList()) - assertTrue(queue.isEmpty()) - } - - @Test - fun `buildSequentialQueue handles single item`() { - val queue = QueueBuilder.buildSequentialQueue(listOf("w1" to 5)) - assertEquals(listOf("w1"), queue) - } - - @Test - fun `buildSequentialQueue handles non-contiguous display orders`() { - val wallpapers = listOf( - "w3" to 100, - "w1" to 5, - "w2" to 50 - ) - - val queue = QueueBuilder.buildSequentialQueue(wallpapers) - - assertEquals(listOf("w1", "w2", "w3"), queue) - } - - // ============================================================ - // Test: buildShuffledQueue - // ============================================================ - - @Test - fun `buildShuffledQueue contains all original IDs`() { - val ids = listOf("w1", "w2", "w3", "w4", "w5") - - val shuffled = QueueBuilder.buildShuffledQueue(ids) - - assertEquals(ids.size, shuffled.size) - assertTrue(shuffled.containsAll(ids)) - } - - @Test - fun `buildShuffledQueue handles empty list`() { - val shuffled = QueueBuilder.buildShuffledQueue(emptyList()) - assertTrue(shuffled.isEmpty()) - } - - @Test - fun `buildShuffledQueue handles single item`() { - val shuffled = QueueBuilder.buildShuffledQueue(listOf("w1")) - assertEquals(listOf("w1"), shuffled) - } - - @Test - fun `buildShuffledQueue produces different order over multiple calls`() { - val ids = (1..100).map { "w$it" } - - // Run multiple times and check if we ever get a different order - // With 100 items, the chance of same order is astronomically low - val results = (1..10).map { QueueBuilder.buildShuffledQueue(ids) } - val allSame = results.all { it == results.first() } - - assertFalse("Shuffle should produce different orders", allSame) - } - - // ============================================================ - // Test: mergeWithExistingQueueDeterministic - // ============================================================ - - @Test - fun `mergeWithExistingQueue preserves existing order`() { - val existing = listOf("w3", "w1", "w2") - val all = listOf("w1", "w2", "w3") - - val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all) - - assertEquals(listOf("w3", "w1", "w2"), merged) - } - - @Test - fun `mergeWithExistingQueue filters removed wallpapers`() { - val existing = listOf("w1", "w2", "w3") - val all = listOf("w1", "w3") // w2 was removed - - val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all) - - assertEquals(listOf("w1", "w3"), merged) - } - - @Test - fun `mergeWithExistingQueue appends new wallpapers`() { - val existing = listOf("w1", "w2") - val all = listOf("w1", "w2", "w3", "w4") // w3, w4 are new - - val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all) - - assertEquals(listOf("w1", "w2", "w3", "w4"), merged) - } - - @Test - fun `mergeWithExistingQueue handles empty existing queue`() { - val existing = emptyList() - val all = listOf("w1", "w2", "w3") - - val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all) - - assertEquals(all, merged) - } - - @Test - fun `mergeWithExistingQueue handles empty all list`() { - val existing = listOf("w1", "w2") - val all = emptyList() - - val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all) - - assertTrue(merged.isEmpty()) - } - - @Test - fun `mergeWithExistingQueue complex scenario`() { - // Existing queue order: w3, w1, w5 (w2 was played) - // Current album: w1, w3, w4, w5, w6 (w2 removed, w4 and w6 added) - val existing = listOf("w3", "w1", "w5") - val all = listOf("w1", "w3", "w4", "w5", "w6") - - val merged = QueueBuilder.mergeWithExistingQueueDeterministic(existing, all) - - // Should preserve w3, w1, w5 order, then add w4, w6 - assertEquals(listOf("w3", "w1", "w5", "w4", "w6"), merged) - } - - // ============================================================ - // Test: buildQueue - // ============================================================ - - @Test - fun `buildQueue sequential uses display order`() { - val wallpapers = listOf( - createWallpaper("w2", displayOrder = 1), - createWallpaper("w1", displayOrder = 0) - ) - - val result = QueueBuilder.buildQueue(wallpapers, shuffle = false) - - assertEquals(listOf("w1", "w2"), result) - } - - @Test - fun `buildQueue shuffle without other screen produces new shuffle`() { - val wallpapers = (1..50).map { createWallpaper("w$it") } - - val result = QueueBuilder.buildQueue(wallpapers, shuffle = true) - - assertEquals(50, result.size) - assertTrue(result.containsAll(wallpapers.map { it.id })) - } - - @Test - fun `buildQueue shuffle with other screen synchronizes order`() { - val wallpapers = (1..5).map { createWallpaper("w$it") } - val otherQueue = listOf("w3", "w1", "w2", "w4", "w5") - - val result = QueueBuilder.buildQueue(wallpapers, shuffle = true, otherScreenQueue = otherQueue) - - assertEquals(otherQueue, result) - } - - // ============================================================ - // Helpers - // ============================================================ - - private fun createWallpaper(id: String, displayOrder: Int = 0) = com.anthonyla.paperize.domain.model.Wallpaper( - id = id, - albumId = "album-1", - uri = "content://test/$id", - fileName = "$id.jpg", - displayOrder = displayOrder, - dateModified = System.currentTimeMillis() - ) } diff --git a/app/src/test/java/com/anthonyla/paperize/core/util/WallpaperSorterTest.kt b/app/src/test/java/com/anthonyla/paperize/core/util/WallpaperSorterTest.kt index ff40db0..7d6e33d 100644 --- a/app/src/test/java/com/anthonyla/paperize/core/util/WallpaperSorterTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/core/util/WallpaperSorterTest.kt @@ -5,266 +5,8 @@ import com.anthonyla.paperize.domain.model.Wallpaper import org.junit.Assert.* import org.junit.Test -/** - * Unit tests for WallpaperSorter utility - */ class WallpaperSorterTest { - // ============================================================ - // Test: sortWallpapersByName - // ============================================================ - - @Test - fun `sortWallpapersByName ascending sorts A to Z`() { - val wallpapers = listOf( - createWallpaper("z_photo.jpg"), - createWallpaper("a_photo.jpg"), - createWallpaper("m_photo.jpg") - ) - - val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true) - - assertEquals("a_photo.jpg", sorted[0].fileName) - assertEquals("m_photo.jpg", sorted[1].fileName) - assertEquals("z_photo.jpg", sorted[2].fileName) - } - - @Test - fun `sortWallpapersByName descending sorts Z to A`() { - val wallpapers = listOf( - createWallpaper("a_photo.jpg"), - createWallpaper("m_photo.jpg"), - createWallpaper("z_photo.jpg") - ) - - val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = false) - - assertEquals("z_photo.jpg", sorted[0].fileName) - assertEquals("m_photo.jpg", sorted[1].fileName) - assertEquals("a_photo.jpg", sorted[2].fileName) - } - - @Test - fun `sortWallpapersByName is case insensitive`() { - val wallpapers = listOf( - createWallpaper("Zebra.jpg"), - createWallpaper("apple.jpg"), - createWallpaper("BANANA.jpg") - ) - - val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true) - - assertEquals("apple.jpg", sorted[0].fileName) - assertEquals("BANANA.jpg", sorted[1].fileName) - assertEquals("Zebra.jpg", sorted[2].fileName) - } - - @Test - fun `sortWallpapersByName with empty list returns empty list`() { - val sorted = WallpaperSorter.sortWallpapersByName(emptyList(), ascending = true) - assertTrue(sorted.isEmpty()) - } - - @Test - fun `sortWallpapersByName with single item returns same list`() { - val wallpapers = listOf(createWallpaper("photo.jpg")) - val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true) - assertEquals(1, sorted.size) - assertEquals("photo.jpg", sorted[0].fileName) - } - - // ============================================================ - // Test: sortWallpapersByDateAdded - // ============================================================ - - @Test - fun `sortWallpapersByDateAdded ascending sorts oldest first`() { - val wallpapers = listOf( - createWallpaper("c.jpg", addedAt = 3000L), - createWallpaper("a.jpg", addedAt = 1000L), - createWallpaper("b.jpg", addedAt = 2000L) - ) - - val sorted = WallpaperSorter.sortWallpapersByDateAdded(wallpapers, ascending = true) - - assertEquals(1000L, sorted[0].addedAt) - assertEquals(2000L, sorted[1].addedAt) - assertEquals(3000L, sorted[2].addedAt) - } - - @Test - fun `sortWallpapersByDateAdded descending sorts newest first`() { - val wallpapers = listOf( - createWallpaper("a.jpg", addedAt = 1000L), - createWallpaper("c.jpg", addedAt = 3000L), - createWallpaper("b.jpg", addedAt = 2000L) - ) - - val sorted = WallpaperSorter.sortWallpapersByDateAdded(wallpapers, ascending = false) - - assertEquals(3000L, sorted[0].addedAt) - assertEquals(2000L, sorted[1].addedAt) - assertEquals(1000L, sorted[2].addedAt) - } - - // ============================================================ - // Test: sortWallpapersByDateModified - // ============================================================ - - @Test - fun `sortWallpapersByDateModified ascending sorts oldest first`() { - val wallpapers = listOf( - createWallpaper("c.jpg", dateModified = 3000L), - createWallpaper("a.jpg", dateModified = 1000L), - createWallpaper("b.jpg", dateModified = 2000L) - ) - - val sorted = WallpaperSorter.sortWallpapersByDateModified(wallpapers, ascending = true) - - assertEquals(1000L, sorted[0].dateModified) - assertEquals(2000L, sorted[1].dateModified) - assertEquals(3000L, sorted[2].dateModified) - } - - @Test - fun `sortWallpapersByDateModified descending sorts newest first`() { - val wallpapers = listOf( - createWallpaper("a.jpg", dateModified = 1000L), - createWallpaper("c.jpg", dateModified = 3000L), - createWallpaper("b.jpg", dateModified = 2000L) - ) - - val sorted = WallpaperSorter.sortWallpapersByDateModified(wallpapers, ascending = false) - - assertEquals(3000L, sorted[0].dateModified) - assertEquals(2000L, sorted[1].dateModified) - assertEquals(1000L, sorted[2].dateModified) - } - - // ============================================================ - // Test: sortFoldersByName - // ============================================================ - - @Test - fun `sortFoldersByName ascending sorts A to Z`() { - val folders = listOf( - createFolder("Wallpapers"), - createFolder("Animals"), - createFolder("Nature") - ) - - val sorted = WallpaperSorter.sortFoldersByName(folders, ascending = true) - - assertEquals("Animals", sorted[0].name) - assertEquals("Nature", sorted[1].name) - assertEquals("Wallpapers", sorted[2].name) - } - - @Test - fun `sortFoldersByName descending sorts Z to A`() { - val folders = listOf( - createFolder("Animals"), - createFolder("Nature"), - createFolder("Wallpapers") - ) - - val sorted = WallpaperSorter.sortFoldersByName(folders, ascending = false) - - assertEquals("Wallpapers", sorted[0].name) - assertEquals("Nature", sorted[1].name) - assertEquals("Animals", sorted[2].name) - } - - // ============================================================ - // Test: sortFoldersByDateModified - // ============================================================ - - @Test - fun `sortFoldersByDateModified ascending sorts oldest first`() { - val folders = listOf( - createFolder("C", dateModified = 3000L), - createFolder("A", dateModified = 1000L), - createFolder("B", dateModified = 2000L) - ) - - val sorted = WallpaperSorter.sortFoldersByDateModified(folders, ascending = true) - - assertEquals(1000L, sorted[0].dateModified) - assertEquals(2000L, sorted[1].dateModified) - assertEquals(3000L, sorted[2].dateModified) - } - - // ============================================================ - // Test: applyDisplayOrder - // ============================================================ - - @Test - fun `applyDisplayOrder sets indices correctly`() { - val wallpapers = listOf( - createWallpaper("a.jpg", displayOrder = 5), - createWallpaper("b.jpg", displayOrder = 10), - createWallpaper("c.jpg", displayOrder = 15) - ) - - val result = WallpaperSorter.applyDisplayOrder(wallpapers) - - assertEquals(0, result[0].displayOrder) - assertEquals(1, result[1].displayOrder) - assertEquals(2, result[2].displayOrder) - } - - @Test - fun `applyDisplayOrder with empty list returns empty list`() { - val result = WallpaperSorter.applyDisplayOrder(emptyList()) - assertTrue(result.isEmpty()) - } - - // ============================================================ - // Test: applyFolderDisplayOrder - // ============================================================ - - @Test - fun `applyFolderDisplayOrder sets indices correctly`() { - val folders = listOf( - createFolder("A", displayOrder = 99), - createFolder("B", displayOrder = 50), - createFolder("C", displayOrder = 1) - ) - - val result = WallpaperSorter.applyFolderDisplayOrder(folders) - - assertEquals(0, result[0].displayOrder) - assertEquals(1, result[1].displayOrder) - assertEquals(2, result[2].displayOrder) - } - - // ============================================================ - // Test: Integration - Sort then apply order - // ============================================================ - - @Test - fun `sort then applyDisplayOrder produces correct order`() { - val wallpapers = listOf( - createWallpaper("z.jpg", displayOrder = 0), - createWallpaper("a.jpg", displayOrder = 1), - createWallpaper("m.jpg", displayOrder = 2) - ) - - val sorted = WallpaperSorter.sortWallpapersByName(wallpapers, ascending = true) - val withOrder = WallpaperSorter.applyDisplayOrder(sorted) - - assertEquals("a.jpg", withOrder[0].fileName) - assertEquals(0, withOrder[0].displayOrder) - assertEquals("m.jpg", withOrder[1].fileName) - assertEquals(1, withOrder[1].displayOrder) - assertEquals("z.jpg", withOrder[2].fileName) - assertEquals(2, withOrder[2].displayOrder) - } - - // ============================================================ - // Test: shiftWallpaper - // ============================================================ - @Test fun `shiftWallpaper moves item and updates indices`() { val wallpapers = listOf( @@ -273,7 +15,6 @@ class WallpaperSorterTest { createWallpaper("c.jpg", displayOrder = 2) ) - // Move 'a' to the end (index 2) val result = WallpaperSorter.shiftWallpaper(wallpapers, "content://test/a.jpg", "content://test/c.jpg") assertEquals("b.jpg", result[0].fileName) @@ -291,10 +32,6 @@ class WallpaperSorterTest { assertEquals(wallpapers, result) } - // ============================================================ - // Test: shiftFolder - // ============================================================ - @Test fun `shiftFolder moves folder and updates indices`() { val folders = listOf( @@ -303,7 +40,6 @@ class WallpaperSorterTest { createFolder("C", displayOrder = 2) ) - // Move 'C' to the beginning (index 0) val result = WallpaperSorter.shiftFolder(folders, "content://folder/C", "content://folder/A") assertEquals("C", result[0].name) @@ -314,10 +50,6 @@ class WallpaperSorterTest { assertEquals(2, result[2].displayOrder) } - // ============================================================ - // Test: shiftWallpaperInFolder - // ============================================================ - @Test fun `shiftWallpaperInFolder updates correct folder and cover URI`() { val folders = listOf( @@ -343,10 +75,6 @@ class WallpaperSorterTest { assertEquals("content://test/w2", f1.coverUri) } - // ============================================================ - // Test: sortAllAlphabetically - // ============================================================ - @Test fun `sortAllAlphabetically sorts everything correctly`() { val folders = listOf( @@ -370,12 +98,14 @@ class WallpaperSorterTest { assertEquals("Z", sortedFolders[1].name) assertEquals("a.jpg", sortedWallpapers[0].fileName) assertEquals("z.jpg", sortedWallpapers[1].fileName) + assertEquals(listOf(0, 1), sortedFolders.map { it.displayOrder }) + assertEquals("content://test/w1", sortedFolders[0].coverUri) + val (reversedFolders, reversedImages) = WallpaperSorter.sortAllAlphabetically(folders, wallpapers, ascending = false) + assertEquals(listOf("Z", "A"), reversedFolders.map { it.name }) + assertEquals(listOf("z.jpg", "a.jpg"), reversedImages.map { it.fileName }) + assertEquals("content://test/w2", reversedFolders[1].coverUri) } - // ============================================================ - // Test: sortAllByDateModified - // ============================================================ - @Test fun `sortAllByDateModified sorts everything correctly`() { val folders = listOf( @@ -400,10 +130,6 @@ class WallpaperSorterTest { assertEquals("a.jpg", sortedWallpapers[0].fileName) } - // ============================================================ - // Helpers - // ============================================================ - private fun createWallpaper( fileName: String, displayOrder: Int = 0, diff --git a/app/src/test/java/com/anthonyla/paperize/data/mapper/AlbumMapperTest.kt b/app/src/test/java/com/anthonyla/paperize/data/mapper/AlbumMapperTest.kt deleted file mode 100644 index 302d10a..0000000 --- a/app/src/test/java/com/anthonyla/paperize/data/mapper/AlbumMapperTest.kt +++ /dev/null @@ -1,183 +0,0 @@ -package com.anthonyla.paperize.data.mapper - -import com.anthonyla.paperize.data.database.entities.AlbumEntity -import com.anthonyla.paperize.domain.model.Album -import com.anthonyla.paperize.domain.model.Folder -import com.anthonyla.paperize.domain.model.Wallpaper -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for AlbumMapper - */ -class AlbumMapperTest { - - // ============================================================ - // Test: AlbumEntity.toDomainModel() - // ============================================================ - - @Test - fun `entity toDomainModel maps all fields correctly`() { - val entity = createAlbumEntity() - val domain = entity.toDomainModel() - - assertEquals(entity.id, domain.id) - assertEquals(entity.name, domain.name) - assertEquals(entity.coverUri, domain.coverUri) - assertEquals(entity.createdAt, domain.createdAt) - assertEquals(entity.modifiedAt, domain.modifiedAt) - assertTrue(domain.wallpapers.isEmpty()) - assertTrue(domain.folders.isEmpty()) - } - - @Test - fun `entity toDomainModel with wallpapers includes them`() { - val entity = createAlbumEntity() - val wallpapers = listOf( - createWallpaper(id = "w1"), - createWallpaper(id = "w2") - ) - - val domain = entity.toDomainModel(wallpapers = wallpapers) - - assertEquals(2, domain.wallpapers.size) - assertEquals("w1", domain.wallpapers[0].id) - assertEquals("w2", domain.wallpapers[1].id) - } - - @Test - fun `entity toDomainModel with folders includes them`() { - val entity = createAlbumEntity() - val folders = listOf( - createFolder(id = "f1"), - createFolder(id = "f2") - ) - - val domain = entity.toDomainModel(folders = folders) - - assertEquals(2, domain.folders.size) - assertEquals("f1", domain.folders[0].id) - assertEquals("f2", domain.folders[1].id) - } - - @Test - fun `entity toDomainModel with wallpapers and folders includes both`() { - val entity = createAlbumEntity() - val wallpapers = listOf(createWallpaper(id = "w1")) - val folders = listOf(createFolder(id = "f1")) - - val domain = entity.toDomainModel(wallpapers = wallpapers, folders = folders) - - assertEquals(1, domain.wallpapers.size) - assertEquals(1, domain.folders.size) - } - - @Test - fun `entity with null coverUri maps correctly`() { - val entity = createAlbumEntity(coverUri = null) - val domain = entity.toDomainModel() - - assertNull(domain.coverUri) - } - - // ============================================================ - // Test: Album.toEntity() - // ============================================================ - - @Test - fun `domain toEntity maps all fields correctly`() { - val domain = createAlbumDomain() - val entity = domain.toEntity() - - assertEquals(domain.id, entity.id) - assertEquals(domain.name, entity.name) - assertEquals(domain.coverUri, entity.coverUri) - assertEquals(domain.createdAt, entity.createdAt) - assertEquals(domain.modifiedAt, entity.modifiedAt) - } - - @Test - fun `domain toEntity does not include nested collections`() { - val domain = createAlbumDomain().copy( - wallpapers = listOf(createWallpaper(id = "w1")), - folders = listOf(createFolder(id = "f1")) - ) - val entity = domain.toEntity() - - // Entity should only have album fields, not nested collections - assertEquals(domain.id, entity.id) - assertEquals(domain.name, entity.name) - } - - // ============================================================ - // Test: List extensions - // ============================================================ - - @Test - fun `list of entities toDomainModels maps all items`() { - val entities = listOf( - createAlbumEntity(id = "a1", name = "Album 1"), - createAlbumEntity(id = "a2", name = "Album 2"), - createAlbumEntity(id = "a3", name = "Album 3") - ) - - val domains = entities.toDomainModels() - - assertEquals(3, domains.size) - assertEquals("a1", domains[0].id) - assertEquals("a2", domains[1].id) - assertEquals("a3", domains[2].id) - } - - @Test - fun `empty list toDomainModels returns empty list`() { - val entities = emptyList() - val domains = entities.toDomainModels() - - assertTrue(domains.isEmpty()) - } - - // ============================================================ - // Test: Round-trip conversion - // ============================================================ - - @Test - fun `entity to domain to entity preserves all data`() { - val original = createAlbumEntity() - val converted = original.toDomainModel().toEntity() - - assertEquals(original.id, converted.id) - assertEquals(original.name, converted.name) - assertEquals(original.coverUri, converted.coverUri) - assertEquals(original.createdAt, converted.createdAt) - assertEquals(original.modifiedAt, converted.modifiedAt) - } - - // ============================================================ - // Helpers - // ============================================================ - - private fun createAlbumEntity( - id: String = "album-1", - name: String = "Test Album", - coverUri: String? = "content://cover/image.jpg" - ) = AlbumEntity( - id = id, - name = name, - coverUri = coverUri, - createdAt = 1000L, - modifiedAt = 2000L - ) - - private fun createAlbumDomain() = Album( - id = "album-1", - name = "Test Album", - coverUri = "content://cover/image.jpg", - createdAt = 1000L, - modifiedAt = 2000L - ) - - private fun createWallpaper(id: String) = Wallpaper.empty(id = id, albumId = "album-1") - - private fun createFolder(id: String) = Folder.empty(id = id, albumId = "album-1") -} diff --git a/app/src/test/java/com/anthonyla/paperize/data/mapper/FolderMapperTest.kt b/app/src/test/java/com/anthonyla/paperize/data/mapper/FolderMapperTest.kt deleted file mode 100644 index cd3c221..0000000 --- a/app/src/test/java/com/anthonyla/paperize/data/mapper/FolderMapperTest.kt +++ /dev/null @@ -1,172 +0,0 @@ -package com.anthonyla.paperize.data.mapper - -import com.anthonyla.paperize.data.database.entities.FolderEntity -import com.anthonyla.paperize.domain.model.Folder -import com.anthonyla.paperize.domain.model.Wallpaper -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for FolderMapper - */ -class FolderMapperTest { - - // ============================================================ - // Test: FolderEntity.toDomainModel() - // ============================================================ - - @Test - fun `entity toDomainModel maps all fields correctly`() { - val entity = createFolderEntity() - val domain = entity.toDomainModel() - - assertEquals(entity.id, domain.id) - assertEquals(entity.albumId, domain.albumId) - assertEquals(entity.name, domain.name) - assertEquals(entity.uri, domain.uri) - assertEquals(entity.coverUri, domain.coverUri) - assertEquals(entity.dateModified, domain.dateModified) - assertEquals(entity.displayOrder, domain.displayOrder) - assertEquals(entity.addedAt, domain.addedAt) - assertTrue(domain.wallpapers.isEmpty()) - } - - @Test - fun `entity toDomainModel with wallpapers includes them`() { - val entity = createFolderEntity() - val wallpapers = listOf( - createWallpaper(id = "w1"), - createWallpaper(id = "w2") - ) - - val domain = entity.toDomainModel(wallpapers) - - assertEquals(2, domain.wallpapers.size) - assertEquals("w1", domain.wallpapers[0].id) - assertEquals("w2", domain.wallpapers[1].id) - } - - @Test - fun `entity with null coverUri maps correctly`() { - val entity = createFolderEntity(coverUri = null) - val domain = entity.toDomainModel() - - assertNull(domain.coverUri) - } - - @Test - fun `entity with coverUri maps correctly`() { - val entity = createFolderEntity(coverUri = "content://cover/image.jpg") - val domain = entity.toDomainModel() - - assertEquals("content://cover/image.jpg", domain.coverUri) - } - - // ============================================================ - // Test: Folder.toEntity() - // ============================================================ - - @Test - fun `domain toEntity maps all fields correctly`() { - val domain = createFolderDomain() - val entity = domain.toEntity() - - assertEquals(domain.id, entity.id) - assertEquals(domain.albumId, entity.albumId) - assertEquals(domain.name, entity.name) - assertEquals(domain.uri, entity.uri) - assertEquals(domain.coverUri, entity.coverUri) - assertEquals(domain.dateModified, entity.dateModified) - assertEquals(domain.displayOrder, entity.displayOrder) - assertEquals(domain.addedAt, entity.addedAt) - } - - @Test - fun `domain toEntity does not include wallpapers`() { - val domain = createFolderDomain().copy( - wallpapers = listOf(createWallpaper(id = "w1")) - ) - val entity = domain.toEntity() - - // Entity should not have wallpapers - they're stored separately - assertEquals(domain.id, entity.id) - } - - // ============================================================ - // Test: List extensions - // ============================================================ - - @Test - fun `list of entities toDomainModels maps all items`() { - val entities = listOf( - createFolderEntity(id = "f1"), - createFolderEntity(id = "f2"), - createFolderEntity(id = "f3") - ) - - val domains = entities.toDomainModels() - - assertEquals(3, domains.size) - assertEquals("f1", domains[0].id) - assertEquals("f2", domains[1].id) - assertEquals("f3", domains[2].id) - } - - @Test - fun `empty list toDomainModels returns empty list`() { - val entities = emptyList() - val domains = entities.toDomainModels() - - assertTrue(domains.isEmpty()) - } - - // ============================================================ - // Test: Round-trip conversion - // ============================================================ - - @Test - fun `entity to domain to entity preserves all data`() { - val original = createFolderEntity() - val converted = original.toDomainModel().toEntity() - - assertEquals(original.id, converted.id) - assertEquals(original.albumId, converted.albumId) - assertEquals(original.name, converted.name) - assertEquals(original.uri, converted.uri) - assertEquals(original.coverUri, converted.coverUri) - assertEquals(original.dateModified, converted.dateModified) - assertEquals(original.displayOrder, converted.displayOrder) - assertEquals(original.addedAt, converted.addedAt) - } - - // ============================================================ - // Helpers - // ============================================================ - - private fun createFolderEntity( - id: String = "folder-1", - coverUri: String? = "content://cover/default.jpg" - ) = FolderEntity( - id = id, - albumId = "album-1", - name = "Test Folder", - uri = "content://folder/test", - coverUri = coverUri, - dateModified = 1000L, - displayOrder = 0, - addedAt = 2000L - ) - - private fun createFolderDomain() = Folder( - id = "folder-1", - albumId = "album-1", - name = "Test Folder", - uri = "content://folder/test", - coverUri = "content://cover/default.jpg", - dateModified = 1000L, - displayOrder = 0, - addedAt = 2000L - ) - - private fun createWallpaper(id: String) = Wallpaper.empty(id = id, albumId = "album-1") -} diff --git a/app/src/test/java/com/anthonyla/paperize/data/mapper/WallpaperMapperTest.kt b/app/src/test/java/com/anthonyla/paperize/data/mapper/WallpaperMapperTest.kt deleted file mode 100644 index c288b18..0000000 --- a/app/src/test/java/com/anthonyla/paperize/data/mapper/WallpaperMapperTest.kt +++ /dev/null @@ -1,184 +0,0 @@ -package com.anthonyla.paperize.data.mapper - -import com.anthonyla.paperize.core.WallpaperMediaType -import com.anthonyla.paperize.core.WallpaperSourceType -import com.anthonyla.paperize.data.database.entities.WallpaperEntity -import com.anthonyla.paperize.domain.model.Wallpaper -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for WallpaperMapper - */ -class WallpaperMapperTest { - - // ============================================================ - // Test: WallpaperEntity.toDomainModel() - // ============================================================ - - @Test - fun `entity toDomainModel maps all fields correctly`() { - val entity = createWallpaperEntity() - val domain = entity.toDomainModel() - - assertEquals(entity.id, domain.id) - assertEquals(entity.albumId, domain.albumId) - assertEquals(entity.folderId, domain.folderId) - assertEquals(entity.uri, domain.uri) - assertEquals(entity.fileName, domain.fileName) - assertEquals(entity.dateModified, domain.dateModified) - assertEquals(entity.displayOrder, domain.displayOrder) - assertEquals(entity.sourceType, domain.sourceType) - assertEquals(entity.addedAt, domain.addedAt) - assertEquals(entity.mediaType, domain.mediaType) - } - - @Test - fun `entity with null folderId maps correctly`() { - val entity = createWallpaperEntity(folderId = null) - val domain = entity.toDomainModel() - - assertNull(domain.folderId) - } - - @Test - fun `entity with FOLDER sourceType maps correctly`() { - val entity = createWallpaperEntity( - folderId = "folder-123", - sourceType = WallpaperSourceType.FOLDER - ) - val domain = entity.toDomainModel() - - assertEquals("folder-123", domain.folderId) - assertEquals(WallpaperSourceType.FOLDER, domain.sourceType) - } - - // ============================================================ - // Test: Wallpaper.toEntity() - // ============================================================ - - @Test - fun `domain toEntity maps all fields correctly`() { - val domain = createWallpaperDomain() - val entity = domain.toEntity() - - assertEquals(domain.id, entity.id) - assertEquals(domain.albumId, entity.albumId) - assertEquals(domain.folderId, entity.folderId) - assertEquals(domain.uri, entity.uri) - assertEquals(domain.fileName, entity.fileName) - assertEquals(domain.dateModified, entity.dateModified) - assertEquals(domain.displayOrder, entity.displayOrder) - assertEquals(domain.sourceType, entity.sourceType) - assertEquals(domain.addedAt, entity.addedAt) - assertEquals(domain.mediaType, entity.mediaType) - } - - @Test - fun `domain with null folderId toEntity maps correctly`() { - val domain = createWallpaperDomain(folderId = null) - val entity = domain.toEntity() - - assertNull(entity.folderId) - } - - // ============================================================ - // Test: List extensions - // ============================================================ - - @Test - fun `list of entities toDomainModels maps all items`() { - val entities = listOf( - createWallpaperEntity(id = "w1"), - createWallpaperEntity(id = "w2"), - createWallpaperEntity(id = "w3") - ) - - val domains = entities.toDomainModels() - - assertEquals(3, domains.size) - assertEquals("w1", domains[0].id) - assertEquals("w2", domains[1].id) - assertEquals("w3", domains[2].id) - } - - @Test - fun `empty list toDomainModels returns empty list`() { - val entities = emptyList() - val domains = entities.toDomainModels() - - assertTrue(domains.isEmpty()) - } - - @Test - fun `list of domains toEntities maps all items`() { - val domains = listOf( - createWallpaperDomain(id = "w1"), - createWallpaperDomain(id = "w2") - ) - - val entities = domains.toEntities() - - assertEquals(2, entities.size) - assertEquals("w1", entities[0].id) - assertEquals("w2", entities[1].id) - } - - // ============================================================ - // Test: Round-trip conversion - // ============================================================ - - @Test - fun `entity to domain to entity preserves all data`() { - val original = createWallpaperEntity() - val converted = original.toDomainModel().toEntity() - - assertEquals(original.id, converted.id) - assertEquals(original.albumId, converted.albumId) - assertEquals(original.folderId, converted.folderId) - assertEquals(original.uri, converted.uri) - assertEquals(original.fileName, converted.fileName) - assertEquals(original.dateModified, converted.dateModified) - assertEquals(original.displayOrder, converted.displayOrder) - assertEquals(original.sourceType, converted.sourceType) - assertEquals(original.addedAt, converted.addedAt) - assertEquals(original.mediaType, converted.mediaType) - } - - // ============================================================ - // Helpers - // ============================================================ - - private fun createWallpaperEntity( - id: String = "wallpaper-1", - folderId: String? = null, - sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT - ) = WallpaperEntity( - id = id, - albumId = "album-1", - folderId = folderId, - uri = "content://test/image.jpg", - fileName = "image.jpg", - dateModified = 1000L, - displayOrder = 0, - sourceType = sourceType, - addedAt = 2000L, - mediaType = WallpaperMediaType.IMAGE - ) - - private fun createWallpaperDomain( - id: String = "wallpaper-1", - folderId: String? = null - ) = Wallpaper( - id = id, - albumId = "album-1", - folderId = folderId, - uri = "content://test/image.jpg", - fileName = "image.jpg", - dateModified = 1000L, - displayOrder = 0, - sourceType = WallpaperSourceType.DIRECT, - addedAt = 2000L, - mediaType = WallpaperMediaType.IMAGE - ) -} diff --git a/app/src/test/java/com/anthonyla/paperize/domain/model/AlbumTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/model/AlbumTest.kt deleted file mode 100644 index 0d021df..0000000 --- a/app/src/test/java/com/anthonyla/paperize/domain/model/AlbumTest.kt +++ /dev/null @@ -1,180 +0,0 @@ -package com.anthonyla.paperize.domain.model - -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for Album domain model - */ -class AlbumTest { - - // ============================================================ - // Test: totalWallpaperCount - // ============================================================ - - @Test - fun `totalWallpaperCount with empty album returns zero`() { - val album = Album.empty(id = "1", name = "Test") - assertEquals(0, album.totalWallpaperCount) - } - - @Test - fun `totalWallpaperCount with direct wallpapers only`() { - val wallpapers = listOf( - Wallpaper.empty(id = "w1", albumId = "1"), - Wallpaper.empty(id = "w2", albumId = "1") - ) - val album = Album( - id = "1", - name = "Test", - coverUri = null, - wallpapers = wallpapers - ) - assertEquals(2, album.totalWallpaperCount) - } - - @Test - fun `totalWallpaperCount with folders only`() { - val folderWallpapers = listOf( - Wallpaper.empty(id = "w1", albumId = "1"), - Wallpaper.empty(id = "w2", albumId = "1"), - Wallpaper.empty(id = "w3", albumId = "1") - ) - val folders = listOf( - Folder.empty(id = "f1", albumId = "1").copy(wallpapers = folderWallpapers) - ) - val album = Album( - id = "1", - name = "Test", - coverUri = null, - folders = folders - ) - assertEquals(3, album.totalWallpaperCount) - } - - @Test - fun `totalWallpaperCount with mixed direct and folder wallpapers`() { - val directWallpapers = listOf( - Wallpaper.empty(id = "w1", albumId = "1") - ) - val folderWallpapers = listOf( - Wallpaper.empty(id = "w2", albumId = "1"), - Wallpaper.empty(id = "w3", albumId = "1") - ) - val folders = listOf( - Folder.empty(id = "f1", albumId = "1").copy(wallpapers = folderWallpapers) - ) - val album = Album( - id = "1", - name = "Test", - coverUri = null, - wallpapers = directWallpapers, - folders = folders - ) - assertEquals(3, album.totalWallpaperCount) - } - - // ============================================================ - // Test: allWallpapers - // ============================================================ - - @Test - fun `allWallpapers returns combined direct and folder wallpapers`() { - val directWallpaper = Wallpaper.empty(id = "direct", albumId = "1") - val folderWallpaper = Wallpaper.empty(id = "folder", albumId = "1") - val folders = listOf( - Folder.empty(id = "f1", albumId = "1").copy(wallpapers = listOf(folderWallpaper)) - ) - val album = Album( - id = "1", - name = "Test", - coverUri = null, - wallpapers = listOf(directWallpaper), - folders = folders - ) - - val allWallpapers = album.allWallpapers - assertEquals(2, allWallpapers.size) - assertTrue(allWallpapers.any { it.id == "direct" }) - assertTrue(allWallpapers.any { it.id == "folder" }) - } - - @Test - fun `allWallpapers with empty album returns empty list`() { - val album = Album.empty() - assertTrue(album.allWallpapers.isEmpty()) - } - - // ============================================================ - // Test: sortedWallpapers - // ============================================================ - - @Test - fun `sortedWallpapers returns wallpapers sorted by displayOrder`() { - val wallpapers = listOf( - Wallpaper.empty(id = "w3", albumId = "1").copy(displayOrder = 3), - Wallpaper.empty(id = "w1", albumId = "1").copy(displayOrder = 1), - Wallpaper.empty(id = "w2", albumId = "1").copy(displayOrder = 2) - ) - val album = Album( - id = "1", - name = "Test", - coverUri = null, - wallpapers = wallpapers - ) - - val sorted = album.sortedWallpapers - assertEquals("w1", sorted[0].id) - assertEquals("w2", sorted[1].id) - assertEquals("w3", sorted[2].id) - } - - // ============================================================ - // Test: isEmpty - // ============================================================ - - @Test - fun `isEmpty returns true for empty album`() { - val album = Album.empty() - assertTrue(album.isEmpty) - } - - @Test - fun `isEmpty returns false when album has wallpapers`() { - val album = Album( - id = "1", - name = "Test", - coverUri = null, - wallpapers = listOf(Wallpaper.empty(id = "w1", albumId = "1")) - ) - assertFalse(album.isEmpty) - } - - @Test - fun `isEmpty returns false when folder has wallpapers`() { - val folderWithWallpapers = Folder.empty(id = "f1", albumId = "1").copy( - wallpapers = listOf(Wallpaper.empty(id = "w1", albumId = "1")) - ) - val album = Album( - id = "1", - name = "Test", - coverUri = null, - folders = listOf(folderWithWallpapers) - ) - assertFalse(album.isEmpty) - } - - // ============================================================ - // Test: Companion object - // ============================================================ - - @Test - fun `empty factory creates album with empty collections`() { - val album = Album.empty(id = "test-id", name = "Test Album") - assertEquals("test-id", album.id) - assertEquals("Test Album", album.name) - assertNull(album.coverUri) - assertTrue(album.wallpapers.isEmpty()) - assertTrue(album.folders.isEmpty()) - } -} diff --git a/app/src/test/java/com/anthonyla/paperize/domain/model/FolderTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/model/FolderTest.kt deleted file mode 100644 index 02e43e0..0000000 --- a/app/src/test/java/com/anthonyla/paperize/domain/model/FolderTest.kt +++ /dev/null @@ -1,126 +0,0 @@ -package com.anthonyla.paperize.domain.model - -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for Folder domain model - */ -class FolderTest { - - // ============================================================ - // Test: displayName - // ============================================================ - - // Note: displayName uses Uri.decode() which is an Android API - // These tests verify behavior in JVM environment where Uri.decode() returns input unchanged - - @Test - fun `displayName returns name for simple names`() { - val folder = createFolder(name = "Wallpapers") - // In JVM tests, Uri.decode returns null, so fallback to name is used - assertEquals("Wallpapers", folder.displayName) - } - - @Test - fun `displayName handles empty name gracefully`() { - val folder = createFolder(name = "") - assertEquals("", folder.displayName) - } - - // ============================================================ - // Test: wallpaperCount - // ============================================================ - - @Test - fun `wallpaperCount returns zero for empty folder`() { - val folder = Folder.empty() - assertEquals(0, folder.wallpaperCount) - } - - @Test - fun `wallpaperCount returns correct count`() { - val wallpapers = listOf( - Wallpaper.empty(id = "w1", albumId = "a1"), - Wallpaper.empty(id = "w2", albumId = "a1"), - Wallpaper.empty(id = "w3", albumId = "a1") - ) - val folder = createFolder().copy(wallpapers = wallpapers) - assertEquals(3, folder.wallpaperCount) - } - - // ============================================================ - // Test: isEmpty - // ============================================================ - - @Test - fun `isEmpty returns true for folder with no wallpapers`() { - val folder = Folder.empty() - assertTrue(folder.isEmpty) - } - - @Test - fun `isEmpty returns false for folder with wallpapers`() { - val folder = createFolder().copy( - wallpapers = listOf(Wallpaper.empty(id = "w1", albumId = "a1")) - ) - assertFalse(folder.isEmpty) - } - - // ============================================================ - // Test: sortedWallpapers - // ============================================================ - - @Test - fun `sortedWallpapers returns wallpapers sorted by displayOrder`() { - val wallpapers = listOf( - Wallpaper.empty(id = "w3", albumId = "a1").copy(displayOrder = 3), - Wallpaper.empty(id = "w1", albumId = "a1").copy(displayOrder = 1), - Wallpaper.empty(id = "w2", albumId = "a1").copy(displayOrder = 2) - ) - val folder = createFolder().copy(wallpapers = wallpapers) - - val sorted = folder.sortedWallpapers - assertEquals("w1", sorted[0].id) - assertEquals("w2", sorted[1].id) - assertEquals("w3", sorted[2].id) - } - - @Test - fun `sortedWallpapers returns empty list for empty folder`() { - val folder = Folder.empty() - assertTrue(folder.sortedWallpapers.isEmpty()) - } - - // ============================================================ - // Test: Companion object - // ============================================================ - - @Test - fun `empty factory creates folder with default values`() { - val folder = Folder.empty(id = "test-id", albumId = "album-1") - assertEquals("test-id", folder.id) - assertEquals("album-1", folder.albumId) - assertEquals("", folder.name) - assertEquals("", folder.uri) - assertNull(folder.coverUri) - assertEquals(0L, folder.dateModified) - assertTrue(folder.wallpapers.isEmpty()) - } - - // ============================================================ - // Helper - // ============================================================ - - private fun createFolder( - name: String = "TestFolder" - ) = Folder( - id = "folder-1", - albumId = "album-1", - name = name, - uri = "content://folder/$name", - coverUri = null, - dateModified = System.currentTimeMillis(), - displayOrder = 0 - ) -} diff --git a/app/src/test/java/com/anthonyla/paperize/domain/model/ScheduleSettingsTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/model/ScheduleSettingsTest.kt index 3c95017..9d43453 100644 --- a/app/src/test/java/com/anthonyla/paperize/domain/model/ScheduleSettingsTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/domain/model/ScheduleSettingsTest.kt @@ -1,47 +1,34 @@ package com.anthonyla.paperize.domain.model import com.anthonyla.paperize.core.ScalingType -import com.anthonyla.paperize.core.constants.Constants -import org.junit.Assert.* +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test -/** - * Unit tests for ScheduleSettings domain model - */ class ScheduleSettingsTest { - - // ============================================================ - // Test: validate() - // ============================================================ - @Test - fun `validate coerces interval below minimum to minimum`() { + fun `validation applies distinct static and live minimums and validates all screens`() { + val effects = WallpaperEffects(darkenPercentage = 150, blurPercentage = -10) val settings = ScheduleSettings( - homeIntervalMinutes = 5, // Below MIN_INTERVAL_MINUTES (15) - lockIntervalMinutes = 10, - liveIntervalMinutes = 1 - ) - - val validated = settings.validate() - - assertEquals(Constants.MIN_INTERVAL_MINUTES, validated.homeIntervalMinutes) - assertEquals(Constants.MIN_INTERVAL_MINUTES, validated.lockIntervalMinutes) - assertEquals(Constants.MIN_LIVE_INTERVAL_MINUTES, validated.liveIntervalMinutes) - } - - @Test - fun `validate keeps valid intervals unchanged`() { - val settings = ScheduleSettings( - homeIntervalMinutes = 60, + homeIntervalMinutes = 5, lockIntervalMinutes = 120, - liveIntervalMinutes = 30 + liveIntervalMinutes = 0, + homeEffects = effects, + lockEffects = effects, + liveEffects = effects + ) + val validEffects = effects.copy(darkenPercentage = 100, blurPercentage = 0) + assertEquals( + settings.copy( + homeIntervalMinutes = 15, + liveIntervalMinutes = 1, + homeEffects = validEffects, + lockEffects = validEffects, + liveEffects = validEffects + ), + settings.validate() ) - - val validated = settings.validate() - - assertEquals(60, validated.homeIntervalMinutes) - assertEquals(120, validated.lockIntervalMinutes) - assertEquals(30, validated.liveIntervalMinutes) } @Test @@ -50,204 +37,46 @@ class ScheduleSettingsTest { assertTrue(usesVisibleLiveTimer(1)) assertTrue(usesVisibleLiveTimer(14)) assertFalse(usesVisibleLiveTimer(15)) - assertFalse(usesVisibleLiveTimer(60)) } @Test - fun `validate validates effect percentages`() { - val effects = WallpaperEffects( - darkenPercentage = 150, // Over 100 - blurPercentage = -10 // Negative - ) - val settings = ScheduleSettings(homeEffects = effects) - - val validated = settings.validate() - - assertEquals(100, validated.homeEffects.darkenPercentage) - assertEquals(0, validated.homeEffects.blurPercentage) - } - - // ============================================================ - // Test: hasSchedulingChanges() - // ============================================================ - - @Test - fun `hasSchedulingChanges returns false for identical settings`() { - val settings1 = ScheduleSettings.default() - val settings2 = ScheduleSettings.default() - - assertFalse(settings1.hasSchedulingChanges(settings2)) + fun `schedule edits require rescheduling without reapplying display effects`() { + val current = ScheduleSettings() + listOf( + current.copy(enableChanger = true), + current.copy(homeAlbumId = "home"), + current.copy(lockAlbumId = "lock"), + current.copy(liveAlbumId = "live"), + current.copy(homeEnabled = true), + current.copy(lockEnabled = true), + current.copy(homeIntervalMinutes = 120), + current.copy(lockIntervalMinutes = 120), + current.copy(liveIntervalMinutes = 120), + current.copy(separateSchedules = true) + ).forEach { edited -> + assertTrue("Scheduling: $edited", current.hasSchedulingChanges(edited)) + assertFalse("Display: $edited", current.hasDisplayChanges(edited)) + } } @Test - fun `hasSchedulingChanges returns true when homeEnabled changes`() { - val settings1 = ScheduleSettings(homeEnabled = true) - val settings2 = ScheduleSettings(homeEnabled = false) - - assertTrue(settings1.hasSchedulingChanges(settings2)) - } - - @Test - fun `hasSchedulingChanges returns true when lockEnabled changes`() { - val settings1 = ScheduleSettings(lockEnabled = true) - val settings2 = ScheduleSettings(lockEnabled = false) - - assertTrue(settings1.hasSchedulingChanges(settings2)) - } - - @Test - fun `hasSchedulingChanges returns true when homeIntervalMinutes changes`() { - val settings1 = ScheduleSettings(homeIntervalMinutes = 60) - val settings2 = ScheduleSettings(homeIntervalMinutes = 120) - - assertTrue(settings1.hasSchedulingChanges(settings2)) - } - - @Test - fun `hasSchedulingChanges returns true when lockIntervalMinutes changes`() { - val settings1 = ScheduleSettings(lockIntervalMinutes = 60) - val settings2 = ScheduleSettings(lockIntervalMinutes = 30) - - assertTrue(settings1.hasSchedulingChanges(settings2)) - } - - @Test - fun `hasSchedulingChanges returns true when separateSchedules changes`() { - val settings1 = ScheduleSettings(separateSchedules = true) - val settings2 = ScheduleSettings(separateSchedules = false) - - assertTrue(settings1.hasSchedulingChanges(settings2)) - } - - @Test - fun `hasSchedulingChanges returns true when liveIntervalMinutes changes`() { - val settings1 = ScheduleSettings(liveIntervalMinutes = 60) - val settings2 = ScheduleSettings(liveIntervalMinutes = 120) - - assertTrue(settings1.hasSchedulingChanges(settings2)) - } - - @Test - fun `hasSchedulingChanges returns false when only display settings change`() { - val settings1 = ScheduleSettings( - homeScalingType = ScalingType.FILL, - adaptiveBrightness = false - ) - val settings2 = ScheduleSettings( - homeScalingType = ScalingType.FIT, - adaptiveBrightness = true - ) - - assertFalse(settings1.hasSchedulingChanges(settings2)) - } - - // ============================================================ - // Test: hasDisplayChanges() - // ============================================================ - - @Test - fun `hasDisplayChanges returns false for identical settings`() { - val settings1 = ScheduleSettings.default() - val settings2 = ScheduleSettings.default() - - assertFalse(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when homeScalingType changes`() { - val settings1 = ScheduleSettings(homeScalingType = ScalingType.FILL) - val settings2 = ScheduleSettings(homeScalingType = ScalingType.FIT) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when lockScalingType changes`() { - val settings1 = ScheduleSettings(lockScalingType = ScalingType.FILL) - val settings2 = ScheduleSettings(lockScalingType = ScalingType.STRETCH) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when home scrolling changes`() { - val settings1 = ScheduleSettings(homeScrollingEnabled = false) - val settings2 = ScheduleSettings(homeScrollingEnabled = true) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when homeEffects change`() { - val settings1 = ScheduleSettings(homeEffects = WallpaperEffects(enableBlur = false)) - val settings2 = ScheduleSettings(homeEffects = WallpaperEffects(enableBlur = true)) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when lockEffects change`() { - val settings1 = ScheduleSettings(lockEffects = WallpaperEffects(darkenPercentage = 0)) - val settings2 = ScheduleSettings(lockEffects = WallpaperEffects(darkenPercentage = 50)) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when liveEffects change`() { - val settings1 = ScheduleSettings(liveEffects = WallpaperEffects.none()) - val settings2 = ScheduleSettings(liveEffects = WallpaperEffects(enableVignette = true)) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when liveScalingType changes`() { - val settings1 = ScheduleSettings(liveScalingType = ScalingType.FILL) - val settings2 = ScheduleSettings(liveScalingType = ScalingType.NONE) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns true when adaptiveBrightness changes`() { - val settings1 = ScheduleSettings(adaptiveBrightness = false) - val settings2 = ScheduleSettings(adaptiveBrightness = true) - - assertTrue(settings1.hasDisplayChanges(settings2)) - } - - @Test - fun `hasDisplayChanges returns false when only scheduling settings change`() { - val settings1 = ScheduleSettings( - homeEnabled = true, - homeIntervalMinutes = 60 - ) - val settings2 = ScheduleSettings( - homeEnabled = false, - homeIntervalMinutes = 120 - ) - - assertFalse(settings1.hasDisplayChanges(settings2)) - } - - // ============================================================ - // Test: Companion object - // ============================================================ - - @Test - fun `default factory creates settings with default values`() { - val settings = ScheduleSettings.default() - - assertFalse(settings.enableChanger) - assertFalse(settings.separateSchedules) - assertFalse(settings.shuffleEnabled) - assertFalse(settings.homeEnabled) - assertFalse(settings.lockEnabled) - assertFalse(settings.homeScrollingEnabled) - assertNull(settings.homeAlbumId) - assertNull(settings.lockAlbumId) - assertEquals(Constants.DEFAULT_INTERVAL_MINUTES, settings.homeIntervalMinutes) - assertEquals(Constants.DEFAULT_INTERVAL_MINUTES, settings.lockIntervalMinutes) + fun `display edits require reapplication without resetting schedules`() { + val current = ScheduleSettings() + val effects = WallpaperEffects(enableBlur = true) + listOf( + current.copy(homeScalingType = ScalingType.FIT), + current.copy(lockScalingType = ScalingType.STRETCH), + current.copy(liveScalingType = ScalingType.NONE), + current.copy(homeScrollingEnabled = true), + current.copy(homeEffects = effects), + current.copy(lockEffects = effects), + current.copy(liveEffects = effects), + current.copy(adaptiveBrightness = true) + ).forEach { edited -> + assertTrue("Display: $edited", current.hasDisplayChanges(edited)) + assertFalse("Scheduling: $edited", current.hasSchedulingChanges(edited)) + } + assertFalse(current.hasSchedulingChanges(current)) + assertFalse(current.hasDisplayChanges(current)) } } diff --git a/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperEffectsTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperEffectsTest.kt index 428aa9d..0956908 100644 --- a/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperEffectsTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperEffectsTest.kt @@ -1,200 +1,31 @@ package com.anthonyla.paperize.domain.model -import com.anthonyla.paperize.core.constants.Constants -import org.junit.Assert.* +import org.junit.Assert.assertEquals import org.junit.Test -/** - * Unit tests for WallpaperEffects domain model - */ class WallpaperEffectsTest { - - // ============================================================ - // Test: hasEffects - // ============================================================ - @Test - fun `hasEffects returns false when all effects disabled`() { - val effects = WallpaperEffects.none() - assertFalse(effects.hasEffects) - } - - @Test - fun `hasEffects returns false when blur enabled but percentage is zero`() { - val effects = WallpaperEffects(enableBlur = true, blurPercentage = 0) - assertFalse(effects.hasEffects) - } - - @Test - fun `hasEffects returns true when blur enabled with non-zero percentage`() { - val effects = WallpaperEffects(enableBlur = true, blurPercentage = 50) - assertTrue(effects.hasEffects) - } - - @Test - fun `hasEffects returns true when darken enabled with non-zero percentage`() { - val effects = WallpaperEffects(enableDarken = true, darkenPercentage = 25) - assertTrue(effects.hasEffects) - } - - @Test - fun `hasEffects returns true when vignette enabled with non-zero percentage`() { - val effects = WallpaperEffects(enableVignette = true, vignettePercentage = 75) - assertTrue(effects.hasEffects) - } - - @Test - fun `hasEffects returns true when grayscale enabled with non-zero percentage`() { - val effects = WallpaperEffects(enableGrayscale = true, grayscalePercentage = 100) - assertTrue(effects.hasEffects) - } - - @Test - fun `hasEffects returns true when multiple effects are enabled`() { - val effects = WallpaperEffects( - enableBlur = true, - blurPercentage = 10, - enableDarken = true, - darkenPercentage = 20 - ) - assertTrue(effects.hasEffects) - } - - @Test - fun `hasEffects ignores interactive effects`() { - val effects = WallpaperEffects( - enableDoubleTap = true, - enableParallax = true, - parallaxIntensity = 100 - ) - assertFalse(effects.hasEffects) - } - - // ============================================================ - // Test: validate() - // ============================================================ - - @Test - fun `validate coerces darkenPercentage above 100 to 100`() { - val effects = WallpaperEffects(darkenPercentage = 150) - val validated = effects.validate() - assertEquals(100, validated.darkenPercentage) - } - - @Test - fun `validate coerces negative darkenPercentage to 0`() { - val effects = WallpaperEffects(darkenPercentage = -50) - val validated = effects.validate() - assertEquals(0, validated.darkenPercentage) - } - - @Test - fun `validate coerces blurPercentage above 100 to 100`() { - val effects = WallpaperEffects(blurPercentage = 200) - val validated = effects.validate() - assertEquals(100, validated.blurPercentage) - } - - @Test - fun `validate coerces negative blurPercentage to 0`() { - val effects = WallpaperEffects(blurPercentage = -10) - val validated = effects.validate() - assertEquals(0, validated.blurPercentage) - } - - @Test - fun `validate coerces vignettePercentage to valid range`() { - val over = WallpaperEffects(vignettePercentage = 120) - val under = WallpaperEffects(vignettePercentage = -5) - - assertEquals(100, over.validate().vignettePercentage) - assertEquals(0, under.validate().vignettePercentage) - } - - @Test - fun `validate coerces grayscalePercentage to valid range`() { - val over = WallpaperEffects(grayscalePercentage = 999) - val under = WallpaperEffects(grayscalePercentage = -1) - - assertEquals(100, over.validate().grayscalePercentage) - assertEquals(0, under.validate().grayscalePercentage) - } - - @Test - fun `validate coerces parallaxIntensity to valid range`() { - val over = WallpaperEffects(parallaxIntensity = 150) - val under = WallpaperEffects(parallaxIntensity = -25) - - assertEquals(100, over.validate().parallaxIntensity) - assertEquals(0, under.validate().parallaxIntensity) - } - - @Test - fun `validate keeps valid values unchanged`() { - val effects = WallpaperEffects( - darkenPercentage = 50, - blurPercentage = 25, - vignettePercentage = 75, - grayscalePercentage = 100, - parallaxIntensity = 60 - ) - - val validated = effects.validate() - - assertEquals(50, validated.darkenPercentage) - assertEquals(25, validated.blurPercentage) - assertEquals(75, validated.vignettePercentage) - assertEquals(100, validated.grayscalePercentage) - assertEquals(60, validated.parallaxIntensity) - } - - @Test - fun `validate handles boundary values correctly`() { - val minEffects = WallpaperEffects( - darkenPercentage = 0, - blurPercentage = 0, - vignettePercentage = 0, - grayscalePercentage = 0, - parallaxIntensity = 0 - ) - val maxEffects = WallpaperEffects( - darkenPercentage = 100, - blurPercentage = 100, - vignettePercentage = 100, - grayscalePercentage = 100, - parallaxIntensity = 100 - ) - - val validatedMin = minEffects.validate() - val validatedMax = maxEffects.validate() - - assertEquals(0, validatedMin.darkenPercentage) - assertEquals(100, validatedMax.darkenPercentage) - } - - // ============================================================ - // Test: Companion object - // ============================================================ - - @Test - fun `default factory creates effects with default values`() { - val effects = WallpaperEffects.default() - - assertFalse(effects.enableBlur) - assertEquals(Constants.DEFAULT_BLUR_PERCENTAGE, effects.blurPercentage) - assertFalse(effects.enableDarken) - assertEquals(Constants.DEFAULT_DARKEN_PERCENTAGE, effects.darkenPercentage) - assertFalse(effects.enableVignette) - assertFalse(effects.enableGrayscale) - assertFalse(effects.enableDoubleTap) - assertFalse(effects.enableParallax) - } - - @Test - fun `none factory creates same as default`() { - val none = WallpaperEffects.none() - val default = WallpaperEffects.default() - - assertEquals(default, none) + fun `validation clamps every percentage and preserves effect toggles`() { + listOf(-1 to 0, 0 to 0, 50 to 50, 100 to 100, 101 to 100).forEach { (input, expected) -> + val effects = WallpaperEffects( + enableBlur = true, + enableParallax = true, + darkenPercentage = input, + blurPercentage = input, + vignettePercentage = input, + grayscalePercentage = input, + parallaxIntensity = input + ) + assertEquals( + effects.copy( + darkenPercentage = expected, + blurPercentage = expected, + vignettePercentage = expected, + grayscalePercentage = expected, + parallaxIntensity = expected + ), + effects.validate() + ) + } } } diff --git a/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperTest.kt deleted file mode 100644 index 14faae2..0000000 --- a/app/src/test/java/com/anthonyla/paperize/domain/model/WallpaperTest.kt +++ /dev/null @@ -1,177 +0,0 @@ -package com.anthonyla.paperize.domain.model - -import com.anthonyla.paperize.core.WallpaperMediaType -import com.anthonyla.paperize.core.WallpaperSourceType -import org.junit.Assert.* -import org.junit.Test - -/** - * Unit tests for Wallpaper domain model - */ -class WallpaperTest { - - // ============================================================ - // Test: displayFileName - // ============================================================ - - // Note: displayFileName uses Uri.decode() which is an Android API - // These tests verify behavior in JVM environment where Uri.decode() returns input unchanged - - @Test - fun `displayFileName returns fileName for simple names`() { - val wallpaper = createWallpaper(fileName = "image.jpg") - // In JVM tests, Uri.decode returns null, so fallback to fileName is used - assertEquals("image.jpg", wallpaper.displayFileName) - } - - @Test - fun `displayFileName handles empty fileName gracefully`() { - val wallpaper = createWallpaper(fileName = "") - assertEquals("", wallpaper.displayFileName) - } - - // ============================================================ - // Test: isFromFolder - // ============================================================ - - @Test - fun `isFromFolder returns true when folderId is set and sourceType is FOLDER`() { - val wallpaper = createWallpaper( - folderId = "folder-123", - sourceType = WallpaperSourceType.FOLDER - ) - assertTrue(wallpaper.isFromFolder) - } - - @Test - fun `isFromFolder returns false when folderId is null`() { - val wallpaper = createWallpaper( - folderId = null, - sourceType = WallpaperSourceType.FOLDER - ) - assertFalse(wallpaper.isFromFolder) - } - - @Test - fun `isFromFolder returns false when sourceType is DIRECT`() { - val wallpaper = createWallpaper( - folderId = "folder-123", - sourceType = WallpaperSourceType.DIRECT - ) - assertFalse(wallpaper.isFromFolder) - } - - // ============================================================ - // Test: extension - // ============================================================ - - @Test - fun `extension extracts jpg extension`() { - val wallpaper = createWallpaper(fileName = "photo.jpg") - assertEquals("jpg", wallpaper.extension) - } - - @Test - fun `extension extracts JPEG extension as lowercase`() { - val wallpaper = createWallpaper(fileName = "photo.JPEG") - assertEquals("jpeg", wallpaper.extension) - } - - @Test - fun `extension returns empty string when no extension`() { - val wallpaper = createWallpaper(fileName = "noextension") - assertEquals("", wallpaper.extension) - } - - @Test - fun `extension handles multiple dots correctly`() { - val wallpaper = createWallpaper(fileName = "my.photo.file.png") - assertEquals("png", wallpaper.extension) - } - - // ============================================================ - // Test: isValidImage - // ============================================================ - - @Test - fun `isValidImage returns true for jpg`() { - assertTrue(createWallpaper(fileName = "image.jpg").isValidImage) - } - - @Test - fun `isValidImage returns true for jpeg`() { - assertTrue(createWallpaper(fileName = "image.jpeg").isValidImage) - } - - @Test - fun `isValidImage returns true for png`() { - assertTrue(createWallpaper(fileName = "image.png").isValidImage) - } - - @Test - fun `isValidImage returns true for webp`() { - assertTrue(createWallpaper(fileName = "image.webp").isValidImage) - } - - @Test - fun `isValidImage returns true for avif`() { - assertTrue(createWallpaper(fileName = "image.avif").isValidImage) - } - - @Test - fun `isValidImage returns false for gif`() { - assertFalse(createWallpaper(fileName = "animation.gif").isValidImage) - } - - @Test - fun `isValidImage returns false for bmp`() { - assertFalse(createWallpaper(fileName = "image.bmp").isValidImage) - } - - @Test - fun `isValidImage returns false for no extension`() { - assertFalse(createWallpaper(fileName = "noext").isValidImage) - } - - @Test - fun `isValidImage is case insensitive`() { - assertTrue(createWallpaper(fileName = "image.PNG").isValidImage) - assertTrue(createWallpaper(fileName = "image.JPG").isValidImage) - } - - // ============================================================ - // Test: Companion object - // ============================================================ - - @Test - fun `empty factory creates wallpaper with default values`() { - val wallpaper = Wallpaper.empty(id = "test-id", albumId = "album-1") - assertEquals("test-id", wallpaper.id) - assertEquals("album-1", wallpaper.albumId) - assertEquals("", wallpaper.uri) - assertEquals("", wallpaper.fileName) - assertEquals(0L, wallpaper.dateModified) - assertNull(wallpaper.folderId) - } - - // ============================================================ - // Helper - // ============================================================ - - private fun createWallpaper( - fileName: String = "test.jpg", - folderId: String? = null, - sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT, - mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE - ) = Wallpaper( - id = "test-id", - albumId = "album-1", - folderId = folderId, - uri = "content://test/$fileName", - fileName = fileName, - dateModified = System.currentTimeMillis(), - displayOrder = 0, - sourceType = sourceType, - mediaType = mediaType - ) -} diff --git a/app/src/test/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCaseTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCaseTest.kt index 2903805..17c33c3 100644 --- a/app/src/test/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCaseTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/domain/usecase/ChangeWallpaperUseCaseTest.kt @@ -2,6 +2,9 @@ package com.anthonyla.paperize.domain.usecase import android.content.Context import android.graphics.Bitmap +import com.anthonyla.paperize.core.EmptyAlbumException +import com.anthonyla.paperize.core.NoValidWallpaperException +import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.core.Result import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.domain.model.PreparedWallpaper @@ -12,25 +15,25 @@ import io.mockk.coVerify import io.mockk.coVerifyOrder import io.mockk.mockk import kotlinx.coroutines.test.runTest +import org.junit.Assert.assertTrue import org.junit.Test class ChangeWallpaperUseCaseTest { private val repository = mockk(relaxed = true) + private val renderer = mockk() private val useCase = ChangeWallpaperUseCase( context = mockk(relaxed = true), wallpaperRepository = repository, - settingsRepository = mockk(relaxed = true) + settingsRepository = mockk(relaxed = true), + renderer = renderer ) @Test fun `complete records current then synchronizes exact queue item`() = runTest { val prepared = preparedWallpaper() coEvery { - repository.getNextWallpaperInQueue(prepared.albumId, ScreenType.LOCK) - } returns null - coEvery { - repository.buildWallpaperQueue(prepared.albumId, ScreenType.LOCK, false) + repository.ensureWallpaperQueue(prepared.albumId, ScreenType.LOCK, false) } returns Result.Success(Unit) useCase.complete(prepared, ScreenType.LOCK) @@ -41,8 +44,7 @@ class ChangeWallpaperUseCaseTest { ScreenType.LOCK, prepared.wallpaperId ) - repository.getNextWallpaperInQueue(prepared.albumId, ScreenType.LOCK) - repository.buildWallpaperQueue(prepared.albumId, ScreenType.LOCK, false) + repository.ensureWallpaperQueue(prepared.albumId, ScreenType.LOCK, false) repository.removeWallpaperFromQueue( prepared.albumId, ScreenType.LOCK, @@ -72,22 +74,55 @@ class ChangeWallpaperUseCaseTest { @Test fun `complete specific records selected item and respects shuffle`() = runTest { coEvery { - repository.getNextWallpaperInQueue("album", ScreenType.HOME) - } returns null - coEvery { - repository.buildWallpaperQueue("album", ScreenType.HOME, true) + repository.ensureWallpaperQueue("album", ScreenType.HOME, true) } returns Result.Success(Unit) useCase.completeSpecific("album", ScreenType.HOME, "selected", shuffle = true) coVerifyOrder { repository.setCurrentWallpaper("album", ScreenType.HOME, "selected") - repository.getNextWallpaperInQueue("album", ScreenType.HOME) - repository.buildWallpaperQueue("album", ScreenType.HOME, true) + repository.ensureWallpaperQueue("album", ScreenType.HOME, true) repository.removeWallpaperFromQueue("album", ScreenType.HOME, "selected") } } + @Test(expected = kotlinx.coroutines.CancellationException::class) + fun `cancelled rendering restores the dequeued item without retrying`() = runTest { + val wallpaper = com.anthonyla.paperize.domain.model.Wallpaper.empty("image", "album") + coEvery { repository.getAndDequeueWallpaper("album", ScreenType.HOME) } returns wallpaper + coEvery { renderer.render(wallpaper, ScreenType.HOME, any()) } throws kotlinx.coroutines.CancellationException() + try { + useCase("album", ScreenType.HOME) + } finally { + coVerify(exactly = 1) { repository.getAndDequeueWallpaper("album", ScreenType.HOME) } + coVerify(exactly = 1) { repository.restoreWallpaperToQueueFront("album", ScreenType.HOME, "image") } + } + } + + @Test + fun `unreadable single image album is not reported as empty`() = runTest { + val wallpaper = com.anthonyla.paperize.domain.model.Wallpaper.empty("image", "album") + var dequeues = 0 + coEvery { repository.getAndDequeueWallpaper("album", ScreenType.HOME) } answers { + if (dequeues++ % 2 == 0) null else wallpaper + } + coEvery { repository.ensureWallpaperQueue("album", ScreenType.HOME, any()) } returns Result.Success(Unit) + coEvery { renderer.render(wallpaper, ScreenType.HOME, any()) } returns null + + assertTrue((useCase("album", ScreenType.HOME) as Result.Error).exception is NoValidWallpaperException) + coVerify(exactly = Constants.MAX_WALLPAPER_LOAD_RETRIES) { renderer.render(wallpaper, ScreenType.HOME, any()) } + } + + @Test + fun `empty album stops after rebuilding once`() = runTest { + coEvery { repository.getAndDequeueWallpaper("album", ScreenType.HOME) } returns null + coEvery { repository.ensureWallpaperQueue("album", ScreenType.HOME, any()) } returns Result.Success(Unit) + + assertTrue((useCase("album", ScreenType.HOME) as Result.Error).exception is EmptyAlbumException) + coVerify(exactly = 1) { repository.ensureWallpaperQueue("album", ScreenType.HOME, any()) } + coVerify(exactly = 0) { renderer.render(any(), any(), any()) } + } + private fun preparedWallpaper() = PreparedWallpaper( bitmap = mockk(relaxed = true), albumId = "album", diff --git a/app/src/test/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCaseTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCaseTest.kt index 24e8394..01fdbbb 100644 --- a/app/src/test/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCaseTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/domain/usecase/ImportWallpapersUseCaseTest.kt @@ -1,82 +1,38 @@ package com.anthonyla.paperize.domain.usecase -import android.content.ContentResolver -import android.content.Context -import android.content.Intent -import android.net.Uri -import androidx.documentfile.provider.DocumentFile import com.anthonyla.paperize.core.Result import com.anthonyla.paperize.core.WallpaperSourceType -import com.anthonyla.paperize.core.util.ScannedImage -import com.anthonyla.paperize.core.util.getFileName -import com.anthonyla.paperize.core.util.scanFolderImages import com.anthonyla.paperize.domain.model.Album import com.anthonyla.paperize.domain.model.Folder -import com.anthonyla.paperize.domain.model.Wallpaper import com.anthonyla.paperize.domain.repository.AlbumRepository +import com.anthonyla.paperize.domain.source.DocumentSource +import com.anthonyla.paperize.domain.source.SourceFolder +import com.anthonyla.paperize.domain.source.SourceImage import io.mockk.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest -import org.junit.After import org.junit.Assert.* -import org.junit.Before import org.junit.Test class ImportWallpapersUseCaseTest { - private val context = mockk() - private val resolver = mockk(relaxed = true) + private val documents = mockk() private val repository = mockk() - private val useCase = ImportWallpapersUseCase(context, repository) - private val album = Album.empty("album") + private val useCase = ImportWallpapersUseCase(documents, repository) - @Before fun setUp() { - every { context.contentResolver } returns resolver - every { repository.getAlbumById("album") } returns flowOf(album) - mockkStatic(Uri::class) - mockkStatic(DocumentFile::class) - mockkStatic("com.anthonyla.paperize.core.util.ExtensionsKt") - } - - @After fun tearDown() = unmockkAll() - - private fun uri(value: String): Uri { - val result = mockk() - every { Uri.parse(value) } returns result - every { result.toString() } returns value - every { result.getFileName(context) } returns "$value.jpg" - return result - } - - @Test fun `import skips duplicates and appends after highest order`() = runTest { - val existing = Wallpaper.empty("existing", "album").copy(uri = "existing", displayOrder = 10) - every { repository.getAlbumById("album") } returns flowOf(album.copy(wallpapers = listOf(existing))) - val newUri = uri("new") - uri("existing") - coEvery { repository.addWallpapersToAlbum(any(), any(), any()) } returns Result.Success(Unit) - - assertTrue(useCase.addImages("album", listOf("existing", "new", "new")) { _, _ -> }) - - coVerify { - repository.addWallpapersToAlbum("album", match { - it.size == 1 && it.single().uri == "new" && it.single().displayOrder == 11 - }, any()) - } - verify(exactly = 1) { resolver.takePersistableUriPermission(newUri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } - } - - @Test fun `already imported images do not write again`() = runTest { - uri("existing") - every { repository.getAlbumById("album") } returns flowOf( - album.copy(wallpapers = listOf(Wallpaper.empty().copy(uri = "existing"))) - ) - assertFalse(useCase.addImages("album", listOf("existing")) { _, _ -> }) - coVerify(exactly = 0) { repository.addWallpapersToAlbum(any(), any(), any()) } + @Test fun `image imports retain permission once and preserve metadata`() = runTest { + coEvery { documents.retainReadPermission("image") } just Runs + coEvery { documents.readImage("image") } returns SourceImage("image", "photo.jpg", 42L) + coEvery { repository.addWallpapersToAlbum(any(), any(), any()) } returns Result.Success(1) + assertTrue(useCase.addImages("album", listOf("image", "image")) { _, _ -> }) + coVerify(exactly = 1) { documents.retainReadPermission("image") } + coVerify { repository.addWallpapersToAlbum("album", match { + it.single().let { image -> image.uri == "image" && image.dateModified == 42L && image.folderId == null } + }, any()) } } @Test fun `permission failure does not save an inaccessible image`() = runTest { - val selected = uri("blocked") - every { resolver.takePersistableUriPermission(selected, any()) } throws SecurityException("No grant") + coEvery { documents.retainReadPermission("blocked") } throws SecurityException("No grant") try { useCase.addImages("album", listOf("blocked")) { _, _ -> } fail("Expected permission error") @@ -84,49 +40,40 @@ class ImportWallpapersUseCaseTest { coVerify(exactly = 0) { repository.addWallpapersToAlbum(any(), any(), any()) } } - @Test fun `folder import keeps scanned metadata and source type`() = runTest { - val tree = uri("tree") - val image = uri("image") - coEvery { tree.scanFolderImages(context, any()) } returns listOf(ScannedImage(image, "photo.png", 42L)) - val document = mockk() - every { DocumentFile.fromTreeUri(context, tree) } returns document - every { document.name } returns "Photos" - coEvery { repository.addFolderToAlbum(any(), any(), any()) } returns Result.Success(Unit) - + @Test fun `folder import keeps metadata and assigns membership`() = runTest { + coEvery { documents.retainReadPermission("tree") } just Runs + every { repository.getAlbumById("album") } returns flowOf(Album.empty("album")) + coEvery { documents.readFolder("tree", any()) } returns SourceFolder("Photos", listOf(SourceImage("image", "photo.png", 42L))) + coEvery { repository.addFolderToAlbum(any(), any(), any()) } returns Result.Success(true) assertTrue(useCase.addFolder("album", "tree", {}, { _, _ -> })) - coVerify { repository.addFolderToAlbum("album", match { folder -> folder.name == "Photos" && folder.wallpapers.single().let { - it.folderId == folder.id && it.sourceType == WallpaperSourceType.FOLDER && + it.folderId == folder.id && it.albumId == "album" && it.sourceType == WallpaperSourceType.FOLDER && it.dateModified == 42L && it.fileName == "photo.png" } }, any()) } } - @Test fun `existing folder restores read access without duplicating it`() = runTest { - val tree = uri("tree") - every { repository.getAlbumById("album") } returns flowOf( - album.copy(folders = listOf(Folder.empty().copy(uri = "tree"))) - ) + @Test fun `existing folder restores access without rescanning`() = runTest { + coEvery { documents.retainReadPermission("tree") } just Runs + every { repository.getAlbumById("album") } returns flowOf(Album.empty("album").copy( + folders = listOf(Folder.empty().copy(uri = "tree")) + )) assertFalse(useCase.addFolder("album", "tree", {}, { _, _ -> })) - verify { resolver.takePersistableUriPermission(tree, Intent.FLAG_GRANT_READ_URI_PERMISSION) } - coVerify(exactly = 0) { tree.scanFolderImages(any(), any()) } - coVerify(exactly = 0) { repository.addFolderToAlbum(any(), any(), any()) } + coVerify { documents.retainReadPermission("tree") } + coVerify(exactly = 0) { documents.readFolder(any(), any()) } } @Test fun `failed and cancelled scans do not save a partial folder`() = runTest { - val tree = uri("tree") + coEvery { documents.retainReadPermission("tree") } just Runs + every { repository.getAlbumById("album") } returns flowOf(Album.empty("album")) for (failure in listOf(java.io.IOException("Unavailable"), CancellationException("Cancelled"))) { - coEvery { tree.scanFolderImages(context, any()) } throws failure + coEvery { documents.readFolder("tree", any()) } throws failure try { useCase.addFolder("album", "tree", {}, { _, _ -> }) fail("Expected scan failure") - } catch (actual: Exception) { - assertEquals(failure.javaClass, actual.javaClass) - assertEquals(failure.message, actual.message) - } + } catch (actual: Exception) { assertSame(failure, actual) } } coVerify(exactly = 0) { repository.addFolderToAlbum(any(), any(), any()) } } - } diff --git a/app/src/test/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCaseTest.kt b/app/src/test/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCaseTest.kt index bbbce5c..dc2915e 100644 --- a/app/src/test/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCaseTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/domain/usecase/RefreshFolderUseCaseTest.kt @@ -1,104 +1,41 @@ package com.anthonyla.paperize.domain.usecase -import android.net.Uri import com.anthonyla.paperize.core.Result -import com.anthonyla.paperize.core.WallpaperSourceType import com.anthonyla.paperize.domain.model.Folder -import com.anthonyla.paperize.domain.model.Wallpaper import com.anthonyla.paperize.domain.repository.AlbumRepository -import com.anthonyla.paperize.domain.repository.WallpaperRepository +import com.anthonyla.paperize.domain.source.DocumentSource +import com.anthonyla.paperize.domain.source.SourceFolder +import com.anthonyla.paperize.domain.source.SourceImage import io.mockk.* import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CompletableDeferred -import kotlinx.coroutines.async -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest -import org.junit.After import org.junit.Assert.* -import org.junit.Before import org.junit.Test -@OptIn(ExperimentalCoroutinesApi::class) class RefreshFolderUseCaseTest { private val albums = mockk() - private val wallpapers = mockk() - private val refresh = RefreshFolderUseCase(albums, wallpapers) - private val tree = mockk() - private val existing = Wallpaper.empty("existing", "album").copy(uri = "existing", displayOrder = 9) - private val folder = MutableStateFlow( - Folder.empty("folder", "album").copy(uri = "tree", wallpapers = listOf(existing)) - ) + private val documents = mockk() + private val refresh = RefreshFolderUseCase(albums, documents) - @Before fun setUp() { - mockkStatic(Uri::class) - every { Uri.parse("tree") } returns tree - every { albums.getFolderById("folder") } returns folder - coEvery { albums.addWallpapersToAlbum(any(), any(), any()) } returns Result.Success(Unit) - } - - @After fun tearDown() = unmockkAll() - - @Test fun `new images append with correct membership and source metadata`() = runTest { - val discovered = Wallpaper.empty("new").copy(uri = "new", sourceType = WallpaperSourceType.FOLDER) - coEvery { wallpapers.scanFolderForWallpapers(tree) } returns Result.Success(listOf(existing, discovered)) + @Test fun `refresh assigns membership and reports actual inserted count`() = runTest { + every { albums.getFolderById("folder") } returns flowOf(Folder.empty("folder", "album").copy(uri = "tree")) + coEvery { documents.readFolder("tree", any()) } returns SourceFolder("Photos", listOf( + SourceImage("existing", "old.png", 1L), SourceImage("new", "new.png", 2L) + )) + coEvery { albums.addWallpapersToAlbum("album", any(), any()) } returns Result.Success(1) assertEquals(Result.Success(1), refresh("folder")) coVerify { albums.addWallpapersToAlbum("album", match { - it.size == 1 && it.single().let { image -> - image.albumId == "album" && image.folderId == "folder" && image.displayOrder == 10 && - image.sourceType == WallpaperSourceType.FOLDER - } + it.size == 2 && it.all { image -> image.albumId == "album" && image.folderId == "folder" } }, any()) } } - @Test fun `unchanged folder avoids unnecessary writes`() = runTest { - coEvery { wallpapers.scanFolderForWallpapers(tree) } returns Result.Success(listOf(existing)) - assertEquals(Result.Success(0), refresh("folder")) - coVerify(exactly = 0) { albums.addWallpapersToAlbum(any(), any(), any()) } - } - - @Test fun `inaccessible folder preserves its current contents`() = runTest { - coEvery { wallpapers.scanFolderForWallpapers(tree) } returns Result.Error(SecurityException("No access")) + @Test fun `failed scan preserves existing data and cancellation propagates`() = runTest { + every { albums.getFolderById("folder") } returns flowOf(Folder.empty("folder", "album").copy(uri = "tree")) + coEvery { documents.readFolder("tree", any()) } throws SecurityException() assertTrue(refresh("folder") is Result.Error) - coVerify(exactly = 0) { albums.addWallpapersToAlbum(any(), any(), any()) } - coVerify(exactly = 0) { albums.removeFolderFromAlbum(any(), any()) } - } - - @Test fun `cancelled refresh propagates cancellation`() = runTest { - coEvery { wallpapers.scanFolderForWallpapers(tree) } throws CancellationException() + coEvery { documents.readFolder("tree", any()) } throws CancellationException() try { refresh("folder"); fail("Expected cancellation") } catch (_: CancellationException) { } coVerify(exactly = 0) { albums.addWallpapersToAlbum(any(), any(), any()) } } - - @Test fun `folder deleted during a scan is not recreated`() = runTest { - coEvery { wallpapers.scanFolderForWallpapers(tree) } coAnswers { - folder.value = null - Result.Success(listOf(Wallpaper.empty("new"))) - } - assertEquals(Result.Success(0), refresh("folder")) - coVerify(exactly = 0) { albums.addWallpapersToAlbum(any(), any(), any()) } - } - - @Test fun `overlapping manual and background refreshes import a discovery once`() = runTest { - val releaseScan = CompletableDeferred() - var scans = 0 - coEvery { wallpapers.scanFolderForWallpapers(tree) } coAnswers { - scans++ - releaseScan.await() - Result.Success(listOf(existing, Wallpaper.empty("new").copy(uri = "new"))) - } - coEvery { albums.addWallpapersToAlbum(any(), any(), any()) } coAnswers { - folder.value = folder.value!!.copy(wallpapers = listOf(existing, Wallpaper.empty("new").copy(uri = "new"))) - Result.Success(Unit) - } - val manual = async { refresh("folder") } - val background = async { refresh("folder") } - runCurrent() - assertEquals(2, scans) - releaseScan.complete(Unit) - assertEquals(Result.Success(1), manual.await()) - assertEquals(Result.Success(0), background.await()) - coVerify(exactly = 1) { albums.addWallpapersToAlbum(any(), any(), any()) } - } } diff --git a/app/src/test/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModelTest.kt new file mode 100644 index 0000000..9fd60e1 --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModelTest.kt @@ -0,0 +1,117 @@ +package com.anthonyla.paperize.presentation.screens.home + +import android.content.Context +import androidx.lifecycle.ViewModelStore +import com.anthonyla.paperize.core.ScreenType +import com.anthonyla.paperize.core.WallpaperMode +import com.anthonyla.paperize.domain.model.AlbumSummary +import com.anthonyla.paperize.domain.model.AppSettings +import com.anthonyla.paperize.domain.model.ScheduleSettings +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.service.worker.WallpaperScheduler +import io.mockk.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.* +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class HomeViewModelTest { + private val settings = mockk() + private val albums = mockk() + private val wallpapers = mockk(relaxed = true) + private val scheduler = mockk(relaxed = true) + private val stored = MutableStateFlow(ScheduleSettings(homeEnabled = true, homeAlbumId = "old")) + private val store = ViewModelStore() + private lateinit var viewModel: HomeViewModel + + @Before fun setUp() { + Dispatchers.setMain(StandardTestDispatcher()) + every { albums.getAlbumSummaries() } returns flowOf(emptyList()) + every { settings.getScheduleSettingsFlow() } returns stored + every { settings.getAppSettingsFlow() } returns flowOf(AppSettings()) + every { settings.getWallpaperModeFlow() } returns flowOf(WallpaperMode.STATIC) + coEvery { settings.getWallpaperMode() } returns WallpaperMode.STATIC + coEvery { settings.getScheduleSettings() } answers { stored.value } + coEvery { settings.updateEnableChanger(any()) } answers { stored.value = stored.value.copy(enableChanger = firstArg()) } + coEvery { settings.updateHomeAlbumId(any()) } answers { stored.value = stored.value.copy(homeAlbumId = firstArg()) } + coEvery { settings.updateScheduleSettings(any<(ScheduleSettings) -> ScheduleSettings>()) } answers { + stored.value = firstArg<(ScheduleSettings) -> ScheduleSettings>()(stored.value) + stored.value + } + every { wallpapers.getCurrentWallpaperFlow(any(), any()) } returns flowOf(null) + viewModel = HomeViewModel(mockk(), albums, mockk(), settings, scheduler, wallpapers) + store.put("home", viewModel) + } + + @After fun tearDown() { + store.clear() + Dispatchers.resetMain() + unmockkAll() + } + + @Test fun `delayed effect edits preserve a newer pause and album selection`() = runTest { + stored.value = stored.value.copy(enableChanger = true) + val draft = stored.value.copy(homeEffects = stored.value.homeEffects.copy(blurPercentage = 60)) + viewModel.updateScheduleSettingsDebounced(draft) + viewModel.toggleWallpaperChanger(false) + runCurrent() + viewModel.selectHomeAlbum(AlbumSummary.empty("new")) + advanceUntilIdle() + + assertFalse(stored.value.enableChanger) + assertEquals("new", stored.value.homeAlbumId) + assertEquals(60, stored.value.homeEffects.blurPercentage) + } + + @Test fun `disabling one screen clears only its current selection`() = runTest { + stored.value = stored.value.copy(lockEnabled = true, lockAlbumId = "lock") + viewModel.updateScheduleSettings(stored.value.copy(homeEnabled = false)) + advanceUntilIdle() + assertNull(stored.value.homeAlbumId) + assertEquals("lock", stored.value.lockAlbumId) + } + + @Test fun `rapid edits keep scheduling side effects in persistence order`() = runTest { + val firstSchedule = CompletableDeferred() + val scheduled = mutableListOf() + coEvery { scheduler.updateSchedules(any(), any(), any()) } coAnswers { + val snapshot = firstArg() + if (!snapshot.enableChanger) firstSchedule.await() + scheduled.add(snapshot.enableChanger) + } + viewModel.updateScheduleSettings(stored.value.copy(homeIntervalMinutes = 45)) + runCurrent() + viewModel.toggleWallpaperChanger(true, onlyIfNotScheduled = true) + runCurrent() + assertFalse(stored.value.enableChanger) + firstSchedule.complete(Unit) + advanceUntilIdle() + assertTrue(stored.value.enableChanger) + assertEquals(listOf(false, true), scheduled) + } + + @Test fun `effect edits do not restart preview subscriptions but album changes do`() = runTest { + backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.currentHomeWallpaperUri.collect() } + runCurrent() + stored.value = stored.value.copy(homeEffects = stored.value.homeEffects.copy(blurPercentage = 60)) + runCurrent() + verify(exactly = 1) { wallpapers.getCurrentWallpaperFlow("old", ScreenType.HOME) } + verify(exactly = 1) { wallpapers.getCurrentWallpaperFlow("old", ScreenType.BOTH) } + + stored.value = stored.value.copy(homeAlbumId = "new") + runCurrent() + verify(exactly = 1) { wallpapers.getCurrentWallpaperFlow("new", ScreenType.HOME) } + verify(exactly = 1) { wallpapers.getCurrentWallpaperFlow("new", ScreenType.BOTH) } + } +} diff --git a/app/src/test/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModelTest.kt b/app/src/test/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModelTest.kt new file mode 100644 index 0000000..634311b --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModelTest.kt @@ -0,0 +1,84 @@ +package com.anthonyla.paperize.presentation.screens.settings + +import android.util.Log +import androidx.lifecycle.ViewModelStore +import com.anthonyla.paperize.core.Result +import com.anthonyla.paperize.core.WallpaperMode +import com.anthonyla.paperize.domain.model.AppSettings +import com.anthonyla.paperize.domain.repository.AlbumRepository +import com.anthonyla.paperize.domain.repository.SettingsRepository +import com.anthonyla.paperize.service.worker.WallpaperScheduler +import io.mockk.* +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.* +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class SettingsViewModelTest { + private val settings = mockk(relaxed = true) + private val albums = mockk() + private val scheduler = mockk(relaxed = true) + private val store = ViewModelStore() + private lateinit var viewModel: SettingsViewModel + + @Before fun setUp() { + Dispatchers.setMain(StandardTestDispatcher()) + mockkStatic(Log::class) + every { Log.e(any(), any(), any()) } returns 0 + every { settings.getAppSettingsFlow() } returns flowOf(AppSettings()) + every { settings.getWallpaperModeFlow() } returns flowOf(WallpaperMode.STATIC) + viewModel = SettingsViewModel(settings, albums, scheduler) + store.put("settings", viewModel) + } + + @After fun tearDown() { + store.clear() + Dispatchers.resetMain() + unmockkAll() + } + + @Test fun `mode switch waits for deletion and persistence before navigating`() = runTest { + val deletion = CompletableDeferred>() + coEvery { albums.deleteAllAlbums() } coAnswers { deletion.await() } + var completed = false + viewModel.switchWallpaperMode(WallpaperMode.LIVE) { completed = true } + runCurrent() + assertTrue(viewModel.isResetting.value) + assertFalse(completed) + viewModel.switchWallpaperMode(WallpaperMode.STATIC) + deletion.complete(Result.Success(Unit)) + advanceUntilIdle() + coVerifyOrder { + settings.updateEnableChanger(false) + scheduler.cancelAllWallpaperChanges() + albums.deleteAllAlbums() + settings.clearScheduleSettings() + settings.updateWallpaperMode(WallpaperMode.LIVE) + } + coVerify(exactly = 1) { albums.deleteAllAlbums() } + assertTrue(completed) + assertFalse(viewModel.isResetting.value) + } + + @Test fun `failed deletion preserves settings and allows retry`() = runTest { + coEvery { albums.deleteAllAlbums() } returns Result.Error(IllegalStateException("Database unavailable")) + var completed = false + viewModel.switchWallpaperMode(WallpaperMode.LIVE) { completed = true } + advanceUntilIdle() + assertTrue(viewModel.resetFailed.value) + assertFalse(completed) + coVerify(exactly = 0) { settings.clearScheduleSettings(); settings.updateWallpaperMode(any()) } + + coEvery { albums.deleteAllAlbums() } returns Result.Success(Unit) + viewModel.resetAllData() + advanceUntilIdle() + assertFalse(viewModel.resetFailed.value) + coVerify(exactly = 1) { settings.clearAllSettings() } + } +} diff --git a/app/src/test/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModelTest.kt b/app/src/test/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModelTest.kt new file mode 100644 index 0000000..c6b8cc7 --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/presentation/screens/sort/SortViewModelTest.kt @@ -0,0 +1,82 @@ +package com.anthonyla.paperize.presentation.screens.sort + +import android.util.Log +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModelStore +import androidx.navigation.toRoute +import com.anthonyla.paperize.core.Result +import com.anthonyla.paperize.domain.model.Album +import com.anthonyla.paperize.domain.repository.AlbumRepository +import com.anthonyla.paperize.presentation.common.navigation.SortRoute +import io.mockk.* +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.test.* +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class SortViewModelTest { + private val albums = mockk() + private val store = ViewModelStore() + private val albumReady = CompletableDeferred() + private lateinit var viewModel: SortViewModel + + @Before fun setUp() { + Dispatchers.setMain(StandardTestDispatcher()) + mockkStatic(Log::class) + every { Log.e(any(), any(), any()) } returns 0 + val savedState = SavedStateHandle() + mockkStatic("androidx.navigation.SavedStateHandleKt") + every { savedState.toRoute() } returns SortRoute("album") + every { albums.getAlbumById("album") } returns flow { emit(albumReady.await()) } + viewModel = SortViewModel(savedState, albums) + store.put("sort", viewModel) + } + + @After fun tearDown() { + store.clear() + Dispatchers.resetMain() + unmockkAll() + } + + @Test fun `save waits for loading and completion and ignores duplicate requests`() = runTest { + viewModel.saveChanges() + runCurrent() + coVerify(exactly = 0) { albums.reorderAlbum(any(), any(), any()) } + albumReady.complete(Album.empty("album")) + runCurrent() + val completion = CompletableDeferred>() + coEvery { albums.reorderAlbum(any(), any(), any()) } coAnswers { completion.await() } + viewModel.saveChanges() + runCurrent() + assertTrue(viewModel.state.value.isSaving) + assertFalse(viewModel.state.value.saved) + viewModel.saveChanges() + completion.complete(Result.Success(Unit)) + advanceUntilIdle() + assertTrue(viewModel.state.value.saved) + assertFalse(viewModel.state.value.isSaving) + coVerify(exactly = 1) { albums.reorderAlbum("album", emptyList(), emptyList()) } + } + + @Test fun `failed save keeps screen open and permits retry`() = runTest { + albumReady.complete(Album.empty("album")) + runCurrent() + coEvery { albums.reorderAlbum(any(), any(), any()) } returns Result.Error(IllegalStateException()) + viewModel.saveChanges() + advanceUntilIdle() + assertFalse(viewModel.state.value.saved) + assertFalse(viewModel.state.value.isSaving) + assertNotNull(viewModel.state.value.error) + coEvery { albums.reorderAlbum(any(), any(), any()) } returns Result.Success(Unit) + viewModel.saveChanges() + advanceUntilIdle() + assertTrue(viewModel.state.value.saved) + assertNull(viewModel.state.value.error) + } +} diff --git a/app/src/test/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtilTest.kt b/app/src/test/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtilTest.kt new file mode 100644 index 0000000..8aa39d9 --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtilTest.kt @@ -0,0 +1,71 @@ +package com.anthonyla.paperize.service.livewallpaper.gl + +import android.opengl.GLES20 +import android.util.Log +import io.mockk.* +import org.junit.After +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +class GLUtilTest { + @Before fun setUp() { + mockkStatic(GLES20::class, Log::class) + every { Log.e(any(), any()) } returns 0 + every { GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER) } returns 11 + every { GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER) } returns 12 + every { GLES20.glShaderSource(any(), any()) } just Runs + every { GLES20.glCompileShader(any()) } just Runs + every { GLES20.glGetShaderiv(any(), any(), any(), any()) } answers { + thirdArg()[0] = 1 + } + every { GLES20.glDeleteShader(any()) } just Runs + every { GLES20.glCreateProgram() } returns 13 + every { GLES20.glAttachShader(any(), any()) } just Runs + every { GLES20.glLinkProgram(any()) } just Runs + every { GLES20.glGetError() } returns GLES20.GL_NO_ERROR + every { GLES20.glDeleteProgram(any()) } just Runs + } + + @After fun tearDown() = unmockkAll() + + @Test fun `fragment compilation failure releases both shaders`() { + every { GLES20.glGetShaderiv(12, GLES20.GL_COMPILE_STATUS, any(), 0) } answers { + thirdArg()[0] = 0 + } + every { GLES20.glGetShaderInfoLog(12) } returns "Invalid shader" + + assertThrows(RuntimeException::class.java) { GLUtil.createProgram("vertex", "fragment") } + + verify(exactly = 1) { GLES20.glDeleteShader(11); GLES20.glDeleteShader(12) } + verify(exactly = 0) { GLES20.glCreateProgram() } + } + + @Test fun `link failure releases the program and both shaders`() { + every { GLES20.glGetProgramiv(13, GLES20.GL_LINK_STATUS, any(), 0) } answers { + thirdArg()[0] = 0 + } + every { GLES20.glGetProgramInfoLog(13) } returns "Incompatible shaders" + + assertThrows(RuntimeException::class.java) { GLUtil.createProgram("vertex", "fragment") } + + verify(exactly = 1) { + GLES20.glDeleteProgram(13) + GLES20.glDeleteShader(11) + GLES20.glDeleteShader(12) + } + } + + @Test fun `attach failure releases the program before linking`() { + every { GLES20.glGetError() } returns GLES20.GL_INVALID_OPERATION + + assertThrows(RuntimeException::class.java) { GLUtil.createProgram("vertex", "fragment") } + + verify(exactly = 1) { + GLES20.glDeleteProgram(13) + GLES20.glDeleteShader(11) + GLES20.glDeleteShader(12) + } + verify(exactly = 0) { GLES20.glLinkProgram(any()) } + } +} diff --git a/app/src/test/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderControllerTest.kt b/app/src/test/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderControllerTest.kt new file mode 100644 index 0000000..b06cfc6 --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderControllerTest.kt @@ -0,0 +1,51 @@ +package com.anthonyla.paperize.service.livewallpaper.renderer + +import com.anthonyla.paperize.core.constants.Constants +import io.mockk.mockk +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import org.junit.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class PaperizeRenderControllerTest { + @Test fun `reload during selection discards the stale loader and selects again`() = runTest { + val uploads = mutableListOf>() + val first = CompletableDeferred() + val stale = mockk() + val current = mockk() + var selections = 0 + val controller = PaperizeRenderController({ loader, skip -> uploads.add(loader to skip) }, backgroundScope) { + if (selections++ == 0) first.await() else current + } + controller.visible = true + controller.reloadCurrentArtwork(immediate = true) + runCurrent() + controller.reloadCurrentArtwork() + first.complete(stale) + runCurrent() + + assertEquals(listOf(current to false), uploads) + } + + @Test fun `hidden debounce waits until visible without selecting twice`() = runTest { + val uploads = mutableListOf>() + val loader = mockk() + val controller = PaperizeRenderController({ loader, skip -> uploads.add(loader to skip) }, backgroundScope) { loader } + controller.visible = true + controller.reloadCurrentArtwork() + runCurrent() + controller.visible = false + advanceTimeBy(Constants.RELOAD_THROTTLE_MS) + runCurrent() + assertTrue(uploads.isEmpty()) + + controller.visible = true + runCurrent() + assertEquals(listOf(loader to false), uploads) + } +} diff --git a/app/src/test/java/com/anthonyla/paperize/service/wallpaper/WallpaperControllerTest.kt b/app/src/test/java/com/anthonyla/paperize/service/wallpaper/WallpaperControllerTest.kt new file mode 100644 index 0000000..ba9904c --- /dev/null +++ b/app/src/test/java/com/anthonyla/paperize/service/wallpaper/WallpaperControllerTest.kt @@ -0,0 +1,110 @@ +package com.anthonyla.paperize.service.wallpaper + +import android.app.WallpaperManager +import android.content.Context +import android.graphics.Bitmap +import com.anthonyla.paperize.core.EmptyAlbumException +import com.anthonyla.paperize.core.Result +import com.anthonyla.paperize.core.ScreenType +import com.anthonyla.paperize.domain.model.PreparedWallpaper +import com.anthonyla.paperize.domain.model.ScheduleSettings +import com.anthonyla.paperize.domain.repository.SettingsRepository +import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase +import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase +import io.mockk.* +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.runTest +import org.junit.Assert.* +import org.junit.Test +import java.io.IOException + +class WallpaperControllerTest { + private val manager = mockk() + private val prepare = mockk(relaxed = true) + private val render = mockk() + private val settingsRepository = mockk(relaxed = true) + private val controller = WallpaperController(mockk(), manager, prepare, render, settingsRepository) + private val settings = ScheduleSettings(homeAlbumId = "album", lockAlbumId = "album") + private val bitmap = mockk(relaxed = true) + private val prepared = PreparedWallpaper(bitmap, "album", ScreenType.HOME, "image", false) + + @Test fun `matching screens use one write and commit both only after acceptance`() = runTest { + coEvery { prepare("album", ScreenType.HOME) } returns Result.Success(prepared) + every { manager.setBitmap(bitmap, null, true, 3) } returns 1 + assertEquals(WallpaperChangeOutcome(changed = true), controller.change(ScreenType.BOTH, settings)) + coVerifyOrder { + manager.setBitmap(bitmap, null, true, 3) + prepare.complete(prepared, ScreenType.HOME) + prepare.complete(prepared, ScreenType.LOCK) + bitmap.recycle() + } + coVerify(exactly = 0) { prepare.restore(any()) } + } + + @Test fun `platform rejection restores prepared item and releases bitmap`() = runTest { + coEvery { prepare("album", ScreenType.HOME) } returns Result.Success(prepared) + every { manager.setBitmap(bitmap, null, true, 1) } returns 0 + try { controller.change(ScreenType.HOME, settings); fail("Expected rejection") } catch (_: IOException) { } + coVerify(exactly = 1) { prepare.restore(prepared) } + coVerify(exactly = 0) { prepare.complete(any(), any()) } + verify(exactly = 1) { bitmap.recycle() } + } + + @Test fun `failed lock write preserves successful home commit`() = runTest { + val lockBitmap = mockk(relaxed = true) + coEvery { prepare("album", ScreenType.HOME) } returns Result.Success(prepared) + coEvery { render("album", ScreenType.LOCK, "image") } returns Result.Success(lockBitmap) + every { manager.setBitmap(bitmap, null, true, 1) } returns 1 + every { manager.setBitmap(lockBitmap, null, true, 2) } throws IOException("Rejected") + try { + controller.change(ScreenType.BOTH, settings.copy(homeScrollingEnabled = true)) + fail("Expected rejection") + } catch (_: IOException) { } + coVerify(exactly = 1) { prepare.complete(prepared, ScreenType.HOME) } + coVerify(exactly = 0) { prepare.complete(prepared, ScreenType.LOCK) } + coVerify(exactly = 0) { prepare.restore(any()) } + verify { bitmap.recycle(); lockBitmap.recycle() } + } + + @Test fun `cancellation after platform acceptance still records the applied wallpaper`() = runTest { + coEvery { prepare("album", ScreenType.HOME) } returns Result.Success(prepared) + lateinit var change: Job + every { manager.setBitmap(bitmap, null, true, 1) } answers { change.cancel(); 1 } + change = launch { controller.change(ScreenType.HOME, settings) } + change.join() + assertTrue(change.isCancelled) + coVerify(exactly = 1) { prepare.complete(prepared, ScreenType.HOME) } + coVerify(exactly = 0) { prepare.restore(any()) } + verify { bitmap.recycle() } + } + + @Test fun `empty home album does not disable a valid lock album`() = runTest { + val active = settings.copy(lockAlbumId = "lock", enableChanger = true, homeEnabled = true, lockEnabled = true) + coEvery { prepare("album", ScreenType.HOME) } returns Result.Error(EmptyAlbumException("Empty")) + val lock = prepared.copy(albumId = "lock", screenType = ScreenType.LOCK) + coEvery { prepare("lock", ScreenType.LOCK) } returns Result.Success(lock) + every { manager.setBitmap(bitmap, null, true, 2) } returns 1 + assertEquals(WallpaperChangeOutcome(changed = true, emptyAlbum = true), controller.change(ScreenType.BOTH, active)) + coVerify { settingsRepository.clearEmptyAlbumSelection("album", ScreenType.HOME) } + } + @Test fun `specific selection commits both screens without advancing a queue`() = runTest { + coEvery { render("album", ScreenType.HOME, "selected") } returns Result.Success(bitmap) + every { manager.setBitmap(bitmap, null, true, 3) } returns 1 + controller.applySpecific("album", "selected", ScreenType.BOTH, settings) + coVerify(exactly = 0) { prepare(any(), any()) } + coVerify { prepare.completeSpecific("album", ScreenType.HOME, "selected", false) } + coVerify { prepare.completeSpecific("album", ScreenType.LOCK, "selected", false) } + verify { bitmap.recycle() } + } + + @Test fun `reapplying a readable current image does not consume the next item`() = runTest { + coEvery { render("album", ScreenType.HOME, null) } returns Result.Success(bitmap) + every { manager.setBitmap(bitmap, null, true, 1) } returns 1 + assertTrue(controller.reapply(ScreenType.HOME, settings).changed) + coVerify(exactly = 0) { prepare(any(), any()) } + coVerify(exactly = 0) { prepare.complete(any(), any()) } + verify { bitmap.recycle() } + } + +} diff --git a/app/src/test/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerTest.kt b/app/src/test/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerTest.kt index c17901b..f8a2f71 100644 --- a/app/src/test/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerTest.kt +++ b/app/src/test/java/com/anthonyla/paperize/service/worker/WallpaperSchedulerTest.kt @@ -23,12 +23,14 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import kotlinx.coroutines.test.runTest class WallpaperSchedulerTest { private val context = mockk() private val workManager = mockk() private val operation = mockk() private val enqueued = mutableListOf>() + private val cancelled = mutableListOf() private lateinit var scheduler: WallpaperScheduler @Before @@ -41,12 +43,37 @@ class WallpaperSchedulerTest { enqueued += Triple(firstArg(), secondArg(), thirdArg()) operation } + every { workManager.cancelUniqueWork(any()) } answers { + cancelled += firstArg() + operation + } scheduler = WallpaperScheduler(context) } @After fun tearDown() = unmockkAll() + @Test fun `missing required album cancels every schedule including refresh`() = runTest { + scheduler.updateSchedules( + ScheduleSettings(enableChanger = true, homeEnabled = true, lockEnabled = true, homeAlbumId = "home"), + WallpaperMode.STATIC + ) + assertTrue(enqueued.isEmpty()) + assertEquals(setOf(Constants.WORK_NAME_HOME, Constants.WORK_NAME_LOCK, Constants.WORK_NAME_BOTH, + Constants.WORK_NAME_LIVE, Constants.WORK_NAME_REFRESH), cancelled.toSet()) + } + + @Test fun `short live intervals cancel static jobs and keep only library refresh`() = runTest { + scheduler.updateSchedules( + ScheduleSettings(enableChanger = true, liveAlbumId = "live", liveIntervalMinutes = 1), + WallpaperMode.LIVE, onlyIfNotScheduled = true + ) + assertEquals(Constants.WORK_NAME_REFRESH, enqueued.single().first) + assertEquals(ExistingPeriodicWorkPolicy.KEEP, enqueued.single().second) + assertEquals(setOf(Constants.WORK_NAME_HOME, Constants.WORK_NAME_LOCK, Constants.WORK_NAME_BOTH, + Constants.WORK_NAME_LIVE), cancelled.toSet()) + } + @Test fun `manual resets defer the next run for a full interval for every target`() { val intervalMillis = TimeUnit.MINUTES.toMillis(60) @@ -86,6 +113,36 @@ class WallpaperSchedulerTest { assertTrue(request.workSpec.calculateNextRunTime() <= System.currentTimeMillis() + minimumMillis) } + @Test + fun `manual lock reset honors the shared interval even with a stale independent value`() { + scheduler.resetAfterManualChange( + ScreenType.LOCK, + ScheduleSettings( + enableChanger = true, separateSchedules = false, + homeEnabled = true, lockEnabled = true, homeAlbumId = "home", lockAlbumId = "lock", + homeIntervalMinutes = 30, lockIntervalMinutes = 90 + ), + WallpaperMode.STATIC + ) + val (name, _, request) = enqueued.single() + assertEquals(Constants.WORK_NAME_LOCK, name) + assertEquals(TimeUnit.MINUTES.toMillis(30), request.workSpec.intervalDuration) + } + + @Test + fun `lock-only reset uses the interval shown by the single picker`() { + scheduler.resetAfterManualChange( + ScreenType.LOCK, + ScheduleSettings( + enableChanger = true, separateSchedules = true, + homeEnabled = false, lockEnabled = true, lockAlbumId = "lock", + homeIntervalMinutes = 30, lockIntervalMinutes = 90 + ), + WallpaperMode.STATIC + ) + assertEquals(TimeUnit.MINUTES.toMillis(30), enqueued.single().third.workSpec.intervalDuration) + } + @Test fun `manual home reset delays only its active independent schedule`() { val before = System.currentTimeMillis() diff --git a/build.gradle.kts b/build.gradle.kts index 168296e..5325fe1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,22 +1,7 @@ -import org.gradle.kotlin.dsl.libs - -buildscript { - repositories { - google() - mavenCentral() - } -} - plugins { alias(libs.plugins.androidApplication) apply false - alias(libs.plugins.androidLibrary) apply false - alias(libs.plugins.kotlinAndroid) apply false alias(libs.plugins.kotlinCompose) apply false alias(libs.plugins.hiltAndroid) apply false alias(libs.plugins.ksp) apply false alias(libs.plugins.kotlinSerialization) apply false - alias(libs.plugins.androidTest) apply false } - - - diff --git a/gradle.properties b/gradle.properties index 2e7e7ed..aa9dbb3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,24 +1,5 @@ -# Project-wide Gradle settings. -# IDE (e.g. Android Studio) users: -# Gradle settings configured through the IDE *will override* -# any settings specified in this file. -# For more details on how to configure your build environment visit -# http://www.gradle.org/docs/current/userguide/build_environment.html -# Specifies the JVM arguments used for the daemon process. -# The setting is particularly useful for tweaking memory settings. org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 -# When configured, Gradle will run in incubating parallel mode. -# This option should only be used with decoupled projects. More details, visit -# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects -# org.gradle.parallel=true -# AndroidX package structure to make it clearer which packages are bundled with the -# Android operating system, and which are packaged with your app's APK -# https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true -# Kotlin code style for this project: "official" or "obsolete": kotlin.code.style=official -# Enables namespacing of each library's R class so that its R class includes only the -# resources declared in the library itself and none from the library's dependencies, -# thereby reducing the size of the R class for that library android.nonTransitiveRClass=true -org.gradle.configuration-cache=true \ No newline at end of file +org.gradle.configuration-cache=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 5268169..0c1f4e6 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -7,14 +7,12 @@ material = "1.14.0" coil = "3.6.2" [libraries] -accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version = "0.37.3" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version = "1.13.0" } androidx-animation = { module = "androidx.compose.animation:animation" } androidx-compose-bom = { module = "androidx.compose:compose-bom", version = "2026.08.00" } androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.19.0" } androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version = "1.2.0" } androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version = "1.2.1" } -androidx-datastore = { module = "androidx.datastore:datastore", version = "1.2.1" } androidx-documentfile = { module = "androidx.documentfile:documentfile", version = "1.1.0" } androidx-espresso-core = { module = "androidx.test.espresso:espresso-core", version = "3.7.0" } androidx-exifinterface = { module = "androidx.exifinterface:exifinterface", version = "1.4.2" } @@ -26,7 +24,6 @@ androidx-junit = { module = "androidx.test.ext:junit", version = "1.3.0" } androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version = "2.11.0" } androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version = "2.11.0" } androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version = "2.11.0" } -androidx-material = { module = "androidx.compose.material:material" } androidx-material-icons-extended = { module = "androidx.compose.material:material-icons-extended" } # v4 uses Material 3 expressive APIs that are not available in the stable 1.4 line. # Keep this known-good alpha pinned until the expressive API reaches stable. @@ -53,18 +50,12 @@ junit = { module = "junit:junit", version = "4.13.2" } mockk = { module = "io.mockk:mockk", version = "1.14.11" } kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version = "1.11.0" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version = "1.11.0" } -lazycolumnscrollbar = { module = "com.github.nanihadesuka:LazyColumnScrollbar", version = "2.2.0" } -lottie-compose = { module = "com.airbnb.android:lottie-compose", version = "6.7.1" } -toolbar-compose = { module = "me.onebone:toolbar-compose", version = "2.3.5" } zoomable = { module = "net.engawapg.lib:zoomable", version = "2.13.0" } reorderable = { group = "sh.calvin.reorderable", name = "reorderable", version = "3.1.0" } [plugins] androidApplication = { id = "com.android.application", version.ref = "androidGradlePlugin" } -androidLibrary = { id = "com.android.library", version.ref = "androidGradlePlugin" } -kotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } kotlinCompose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } hiltAndroid = { id = "com.google.dagger.hilt.android", version.ref = "hilt" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } kotlinSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } -androidTest = { id = "com.android.test", version.ref = "androidGradlePlugin" }