From bc26d3c75f018c2b33f498c5a1c7da3f286cf69e Mon Sep 17 00:00:00 2001 From: Anthonyy232 Date: Wed, 25 Mar 2026 22:19:03 -0700 Subject: [PATCH] fix: more bug fixes --- app/build.gradle.kts | 21 +- .../paperize/core/constants/Constants.kt | 7 +- .../anthonyla/paperize/core/di/AppModule.kt | 11 +- .../core/util/BrightnessCalculator.kt | 22 +- .../paperize/core/util/QueueBuilder.kt | 21 -- .../paperize/core/util/WallpaperUtil.kt | 271 +++++++++++----- .../data/database/PaperizeDatabase.kt | 6 +- .../data/database/dao/WallpaperCurrentDao.kt | 29 ++ .../data/database/dao/WallpaperDao.kt | 20 ++ .../data/database/dao/WallpaperQueueDao.kt | 36 +-- .../entities/WallpaperCurrentEntity.kt | 45 +++ .../data/datastore/PreferencesManager.kt | 31 +- .../repository/WallpaperRepositoryImpl.kt | 90 +++--- .../paperize/domain/model/AppSettings.kt | 4 +- .../domain/repository/WallpaperRepository.kt | 13 +- .../domain/usecase/ChangeWallpaperUseCase.kt | 86 +++-- .../domain/usecase/ReapplyEffectsUseCase.kt | 85 +++++ .../domain/usecase/RefreshAlbumUseCase.kt | 6 - .../common/components/SettingsComponents.kt | 296 +----------------- .../screens/album_view/AlbumViewScreen.kt | 55 +++- .../screens/album_view/AlbumViewViewModel.kt | 16 +- .../screens/folder_view/FolderViewScreen.kt | 37 +-- .../presentation/screens/home/HomeScreen.kt | 25 +- .../screens/home/HomeViewModel.kt | 56 +--- .../screens/library/LibraryScreen.kt | 14 +- .../screens/library/components/AlbumItem.kt | 21 +- .../screens/settings/SettingsScreen.kt | 16 +- .../screens/sort/SortViewScreen.kt | 11 +- .../screens/startup/StartupScreen.kt | 32 +- .../storage/StoragePermissionScreen.kt | 21 +- .../screens/wallpaper/WallpaperScreen.kt | 22 +- .../components/AlbumSelectionBottomSheet.kt | 21 +- .../wallpaper/components/SettingSwitch.kt | 4 +- .../components/SettingSwitchWithSlider.kt | 6 +- .../components/TimeIntervalPicker.kt | 29 +- .../wallpaper_view/WallpaperViewScreen.kt | 8 +- .../wallpaper/WallpaperChangeService.kt | 118 +++++++ .../service/worker/WallpaperChangeWorker.kt | 74 ++++- app/src/main/res/values/strings.xml | 59 +--- .../paperize/core/util/QueueBuilderTest.kt | 62 ---- gradle/libs.versions.toml | 26 +- settings.gradle.kts | 3 + 42 files changed, 937 insertions(+), 899 deletions(-) create mode 100644 app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperCurrentEntity.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/domain/usecase/ReapplyEffectsUseCase.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 496c0fc..d70b245 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,6 +1,7 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + plugins { alias(libs.plugins.androidApplication) - alias(libs.plugins.kotlinAndroid) alias(libs.plugins.kotlinCompose) alias(libs.plugins.hiltAndroid) alias(libs.plugins.ksp) @@ -57,12 +58,6 @@ android { targetCompatibility = JavaVersion.VERSION_17 } - kotlin { - compilerOptions { - jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 - } - } - buildFeatures { compose = true viewBinding = true @@ -74,19 +69,15 @@ android { generateLocaleConfig = true } - buildToolsVersion = "35.0.1" dependenciesInfo { includeInApk = false includeInBundle = false } +} - applicationVariants.all { - this.outputs - .map { it as com.android.build.gradle.internal.api.ApkVariantOutputImpl } - .forEach { output -> - val apkName = "paperize-v${this.versionName}.apk" - output.outputFileName = apkName - } +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) } } 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 7004eb2..09bbb0c 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 @@ -6,7 +6,7 @@ package com.anthonyla.paperize.core.constants object Constants { // Database const val DATABASE_NAME = "paperize_database" - const val DATABASE_VERSION = 2 // v2: Added mediaType and crop fields to WallpaperEntity + const val DATABASE_VERSION = 3 // v3: Added wallpaper_current table for reapply-effects support // DataStore const val PREFERENCES_NAME = "paperize_preferences" @@ -17,6 +17,7 @@ object Constants { // Services const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER" + const val ACTION_REAPPLY_EFFECTS = "com.anthonyla.paperize.ACTION_REAPPLY_EFFECTS" const val ACTION_RELOAD_WALLPAPER = "com.anthonyla.paperize.ACTION_RELOAD_WALLPAPER" // WorkManager @@ -195,10 +196,6 @@ object PreferenceKeys { const val LOCK_SCALING_TYPE = "lock_scaling_type" const val LIVE_SCALING_TYPE = "live_scaling_type" - // Current wallpapers - const val CURRENT_HOME_WALLPAPER_ID = "current_home_wallpaper_id" - const val CURRENT_LOCK_WALLPAPER_ID = "current_lock_wallpaper_id" - // Behavior const val ADAPTIVE_BRIGHTNESS = "adaptive_brightness" 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 78608ce..e6f2671 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 @@ -7,6 +7,7 @@ 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 @@ -70,6 +71,11 @@ object AppModule { fun provideWallpaperQueueDao(database: PaperizeDatabase): WallpaperQueueDao = database.wallpaperQueueDao() + @Provides + @Singleton + fun provideWallpaperCurrentDao(database: PaperizeDatabase): WallpaperCurrentDao = + database.wallpaperCurrentDao() + /** * Provide PreferencesManager */ @@ -97,8 +103,9 @@ object AppModule { fun provideWallpaperRepository( @ApplicationContext context: Context, wallpaperDao: WallpaperDao, - wallpaperQueueDao: WallpaperQueueDao - ): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao) + wallpaperQueueDao: WallpaperQueueDao, + wallpaperCurrentDao: WallpaperCurrentDao + ): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao, wallpaperCurrentDao) @Provides @Singleton 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 c7ce44a..dcca9d3 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 @@ -1,7 +1,6 @@ package com.anthonyla.paperize.core.util import android.graphics.Bitmap -import androidx.core.graphics.get import com.anthonyla.paperize.core.constants.Constants /** @@ -23,18 +22,27 @@ object BrightnessCalculator { } /** - * Calculate brightness estimate of bitmap (0.0 - 1.0) - * Uses luminance calculation based on RGB values. + * 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). */ 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 var pixelCount = 0 - for (x in 0 until bitmap.width step sampleSize) { - for (y in 0 until bitmap.height step sampleSize) { - val pixel = bitmap[x, y] - totalLuminance += calculateLuminance(pixel) + for (y in 0 until h step sampleSize) { + bitmap.getPixels(rowBuffer, 0, w, 0, y, w, 1) + for (x in 0 until w step sampleSize) { + totalLuminance += calculateLuminance(rowBuffer[x]) pixelCount++ } } 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 6150e9e..d043b3b 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 @@ -27,27 +27,6 @@ object QueueBuilder { return wallpaperIds.shuffled() } - /** - * Check if queue positions need normalization - * Positions need normalization if they have gaps (e.g., 0, 2, 4 instead of 0, 1, 2) - * @param positions Current queue positions - * @return True if normalization is needed, false otherwise - */ - fun needsNormalization(positions: List): Boolean { - if (positions.isEmpty()) return false - val sorted = positions.sorted() - return sorted.indices.any { sorted[it] != it } - } - - /** - * Normalize queue positions to be sequential starting from 0 - * @param positions Current queue positions (may have gaps) - * @return Normalized positions (0, 1, 2, ...) - */ - fun normalizePositions(positions: List): List { - return positions.indices.toList() - } - /** * Merge existing queue with new wallpapers while preserving existing order * Used when new wallpapers are added to an album during shuffle mode 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 8d2ecdd..b6a572d 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 @@ -46,44 +46,6 @@ import com.anthonyla.paperize.core.WallpaperMediaType private const val TAG = "WallpaperUtil" -/** - * Get the dimensions of the image from the URI - */ -fun Uri.getImageDimensions(context: Context): Size? { - // Try EXIF first - try { - context.contentResolver.openInputStream(this)?.use { inputStream -> - val exif = ExifInterface(inputStream) - val width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0) - val height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0) - if (width > 0 && height > 0) { - return Size(width, height) - } - } - } catch (e: Exception) { - Log.w(TAG, "Error reading EXIF dimensions for $this, falling back: $e") - } - - // Fallback to BitmapFactory - try { - context.contentResolver.openInputStream(this)?.use { inputStream -> - val options = BitmapFactory.Options().apply { - inJustDecodeBounds = true - } - BitmapFactory.decodeStream(inputStream, null, options) - if (options.outWidth > 0 && options.outHeight > 0) { - return Size(options.outWidth, options.outHeight) - } - } - } catch (e: Exception) { - Log.e(TAG, "Error getting image dimensions with BitmapFactory for $this: $e") - return null - } - - Log.w(TAG, "Could not get image dimensions for $this") - return null -} - /** * Get EXIF orientation from URI */ @@ -179,8 +141,12 @@ fun getDeviceScreenSize(context: Context): Size { } /** - * Retrieve a bitmap from a URI that is scaled down to the device's screen size - * Now with EXIF orientation support + * 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, @@ -189,26 +155,12 @@ fun retrieveBitmap( height: Int, scaling: ScalingType = ScalingType.FIT ): Bitmap? { - val imageSize = wallpaperUri.getImageDimensions(context) ?: return null - if (imageSize.width <= 0 || imageSize.height <= 0) { - Log.e(TAG, "Invalid image dimensions from URI: $imageSize") - return null - } - - val sampleSize = if (scaling == ScalingType.NONE) { - 1 - } else { - calculateInSampleSize(imageSize, width, height) - } - - // ImageDecoder auto-applies EXIF orientation and its info.size returns post-EXIF dimensions. - // We must NOT call applyExifOrientation on the ImageDecoder result — it would double-rotate. - // BitmapFactory does NOT auto-apply EXIF, so applyExifOrientation is needed only for that path. + // 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. var decodedWithImageDecoder = false val bitmap = try { val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri) val result = ImageDecoder.decodeBitmap(source) { decoder, info, _ -> - // info.size is the post-EXIF (display) size — use it for correct aspect-ratio math val srcWidth = info.size.width val srcHeight = info.size.height val (targetWidth, targetHeight) = when (scaling) { @@ -222,7 +174,6 @@ fun retrieveBitmap( } ScalingType.STRETCH -> Pair(width, height) ScalingType.NONE -> { - // Cap at 2× screen size to prevent OOM on very large source images val maxWidth = width * 2 val maxHeight = height * 2 if (srcWidth > maxWidth || srcHeight > maxHeight) { @@ -233,7 +184,6 @@ fun retrieveBitmap( } } } - decoder.setTargetSize(targetWidth, targetHeight) decoder.isMutableRequired = true decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE @@ -243,16 +193,23 @@ fun retrieveBitmap( } catch (e: Exception) { Log.w(TAG, "ImageDecoder failed, falling back to BitmapFactory: $e") try { - context.contentResolver.openInputStream(wallpaperUri)?.use { inputStream -> - val options = BitmapFactory.Options().apply { + // 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) + if (scaling == ScalingType.NONE || opts.outWidth <= 0 || opts.outHeight <= 0) 1 + else calculateInSampleSize(Size(opts.outWidth, opts.outHeight), width, height) + } ?: 1 + context.contentResolver.openInputStream(wallpaperUri)?.use { stream -> + BitmapFactory.decodeStream(stream, null, BitmapFactory.Options().apply { inSampleSize = sampleSize inMutable = true inPreferredConfig = Bitmap.Config.ARGB_8888 - } - BitmapFactory.decodeStream(inputStream, null, options) + }) } - } catch (e: OutOfMemoryError) { - Log.e(TAG, "OOM during BitmapFactory fallback for $wallpaperUri: $e") + } catch (oom: OutOfMemoryError) { + Log.e(TAG, "OOM during BitmapFactory fallback for $wallpaperUri: $oom") null } } catch (e: OutOfMemoryError) { @@ -543,6 +500,12 @@ 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, @@ -554,41 +517,195 @@ fun processBitmap( vignettePercent: Int = 0, 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, + hasDarken, darkenPercent, + hasBlur, blurPercent, + hasVignette, vignettePercent, + hasGrayscale, grayscalePercent + ) + } catch (e: Exception) { + Log.w(TAG, "GPU effects pipeline failed, falling back to CPU: $e") + } catch (e: OutOfMemoryError) { + Log.w(TAG, "OOM in GPU effects pipeline, falling back to CPU: $e") + } + + // CPU fallback + return processBitmapCpu( + source, + hasDarken, darkenPercent, + hasBlur, blurPercent, + hasVignette, vignettePercent, + hasGrayscale, grayscalePercent + ) +} + +/** + * GPU-accelerated effects pipeline. + * + * Chains darken, blur, and grayscale as [RenderEffect]s on a single [RenderNode], + * draws the vignette overlay on the same canvas, and reads back the result once. + */ +private fun processBitmapGpu( + source: Bitmap, + hasDarken: Boolean, darkenPercent: Int, + hasBlur: Boolean, blurPercent: Int, + hasVignette: Boolean, vignettePercent: Int, + hasGrayscale: Boolean, grayscalePercent: Int +): Bitmap { + val w = source.width + val h = source.height + + val imageReader = ImageReader.newInstance( + w, h, PixelFormat.RGBA_8888, 1, + HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT + ) + val renderNode = RenderNode("EffectsChain") + val hardwareRenderer = HardwareRenderer() + + try { + hardwareRenderer.setSurface(imageReader.surface) + hardwareRenderer.setContentRoot(renderNode) + renderNode.setPosition(0, 0, w, h) + + // --- Build chained RenderEffect (darken → blur → grayscale) --- + var effect: RenderEffect? = null + + if (hasDarken) { + val factor = (100 - darkenPercent.coerceIn(0, 100)) / 100f + val cm = ColorMatrix().apply { setScale(factor, factor, factor, 1f) } + val darkenEffect = RenderEffect.createColorFilterEffect(ColorMatrixColorFilter(cm)) + effect = darkenEffect + } + + if (hasBlur) { + val radius = (blurPercent.coerceIn(0, 100) / 100f) * Constants.MAX_BLUR_RADIUS + val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP) + effect = if (effect != null) { + RenderEffect.createChainEffect(blurEffect, effect) + } else { + blurEffect + } + } + + if (hasGrayscale) { + val factor = grayscalePercent.coerceIn(0, 100) / 100f + val cm = ColorMatrix().apply { setSaturation(1 - factor) } + val gsEffect = RenderEffect.createColorFilterEffect(ColorMatrixColorFilter(cm)) + effect = if (effect != null) { + RenderEffect.createChainEffect(gsEffect, effect) + } else { + gsEffect + } + } + + if (effect != null) { + 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) + } + + 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() + } + } finally { + image.close() + } + } finally { + hardwareRenderer.destroy() + renderNode.discardDisplayList() + imageReader.close() + } +} + +/** + * CPU fallback: applies effects sequentially (original implementation). + */ +private fun processBitmapCpu( + source: Bitmap, + hasDarken: Boolean, darkenPercent: Int, + hasBlur: Boolean, blurPercent: Int, + hasVignette: Boolean, vignettePercent: Int, + hasGrayscale: Boolean, grayscalePercent: Int ): Bitmap { var result = source - // Apply effects in order, respecting enable flags - // Recycle intermediate bitmaps to prevent memory leaks - - // Darken modifies in-place for mutable bitmaps, no need to track previous - if (enableDarken && darkenPercent > 0) { + if (hasDarken) { result = darkenBitmap(result, darkenPercent) } - // Blur always creates a new bitmap - if (enableBlur && blurPercent > 0) { + if (hasBlur) { val previous = result result = blurBitmap(result, blurPercent) - // Recycle the previous one if different from source if (result !== previous && previous !== source) { previous.recycle() } } - - if (enableVignette && vignettePercent > 0) { + if (hasVignette) { val previous = result result = vignetteBitmap(result, vignettePercent) - // Vignette modifies in-place for mutable bitmaps, may create copy for immutable if (result !== previous && previous !== source) { previous.recycle() } } - if (enableGrayscale && grayscalePercent > 0) { + if (hasGrayscale) { val previous = result result = grayscaleBitmap(result, grayscalePercent) - // Grayscale modifies in-place for mutable bitmaps, may create copy for immutable if (result !== previous && previous !== source) { previous.recycle() } 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 e8aa059..474952a 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 @@ -6,10 +6,12 @@ import androidx.room.TypeConverters import com.anthonyla.paperize.data.database.converters.TypeConverters as PaperizeTypeConverters 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.database.entities.AlbumEntity import com.anthonyla.paperize.data.database.entities.FolderEntity +import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity import com.anthonyla.paperize.data.database.entities.WallpaperEntity import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity import com.anthonyla.paperize.core.constants.Constants @@ -32,7 +34,8 @@ import com.anthonyla.paperize.core.constants.Constants AlbumEntity::class, WallpaperEntity::class, FolderEntity::class, - WallpaperQueueEntity::class + WallpaperQueueEntity::class, + WallpaperCurrentEntity::class ], version = Constants.DATABASE_VERSION, exportSchema = true @@ -43,4 +46,5 @@ abstract class PaperizeDatabase : RoomDatabase() { abstract fun wallpaperDao(): WallpaperDao abstract fun folderDao(): FolderDao abstract fun wallpaperQueueDao(): WallpaperQueueDao + abstract fun wallpaperCurrentDao(): WallpaperCurrentDao } 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 new file mode 100644 index 0000000..6d5b669 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperCurrentDao.kt @@ -0,0 +1,29 @@ +package com.anthonyla.paperize.data.database.dao + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import com.anthonyla.paperize.core.ScreenType +import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity +import com.anthonyla.paperize.data.database.entities.WallpaperEntity + +@Dao +interface WallpaperCurrentDao { + + /** + * Return the wallpaper entity that was last applied for this album/screen, + * or null if none has been recorded yet (or if it was deleted via CASCADE). + */ + @Query(""" + SELECT w.* FROM wallpapers w + INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId + WHERE wc.albumId = :albumId AND wc.screenType = :screenType + LIMIT 1 + """) + suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? + + /** 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 383e4f3..7e17c2c 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 @@ -121,4 +121,24 @@ 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 } + +/** 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 2fd62d2..019a2a4 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 @@ -8,7 +8,6 @@ import androidx.room.Transaction import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.data.database.entities.WallpaperEntity import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity -import kotlinx.coroutines.flow.Flow /** * Data Access Object for Wallpaper Queue operations @@ -55,15 +54,17 @@ interface WallpaperQueueDao { @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 AND wallpaperId = :wallpaperId - AND queuePosition = ( - SELECT MIN(queuePosition) - FROM wallpaper_queue - WHERE albumId = :albumId AND screenType = :screenType - ) """) suspend fun deleteQueueItem(albumId: String, screenType: ScreenType, wallpaperId: String) @@ -78,29 +79,6 @@ interface WallpaperQueueDao { """) suspend fun deleteFirstQueueItem(albumId: String, screenType: ScreenType) - /** - * Normalize queue positions to be sequential starting from 0 - * This fixes gaps created by CASCADE deletes when wallpapers are removed - * Called after every dequeue to ensure queue integrity - */ - @Transaction - suspend fun normalizeQueuePositions(albumId: String, screenType: ScreenType) { - val items = getQueueItems(albumId, screenType) - if (items.isEmpty()) return - - // Check if normalization is needed (positions should be 0, 1, 2, ...) - // Use indexed access instead of indexOf() for O(n) instead of O(n²) - val needsNormalization = items.indices.any { items[it].queuePosition != it } - if (!needsNormalization) return - - // Rebuild queue with normalized positions - clearQueue(albumId, screenType) - val normalizedItems = items.mapIndexed { index, item -> - item.copy(queuePosition = index) - } - insertQueueItems(normalizedItems) - } - /** * Clear queue for album and screen type */ 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 new file mode 100644 index 0000000..b2d0b23 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperCurrentEntity.kt @@ -0,0 +1,45 @@ +package com.anthonyla.paperize.data.database.entities + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.ForeignKey +import androidx.room.Index +import com.anthonyla.paperize.core.ScreenType + +/** + * Room entity tracking the last-applied wallpaper per (album, screen). + * + * A CASCADE on both FKs means: if the album or wallpaper is deleted the entry + * disappears automatically — the service will then fall back to a normal queue + * advance instead of reapplying a stale URI. + */ +@Entity( + tableName = "wallpaper_current", + primaryKeys = ["albumId", "screenType"], + foreignKeys = [ + ForeignKey( + entity = AlbumEntity::class, + parentColumns = ["id"], + childColumns = ["albumId"], + onDelete = ForeignKey.CASCADE + ), + ForeignKey( + entity = WallpaperEntity::class, + parentColumns = ["id"], + childColumns = ["wallpaperId"], + onDelete = ForeignKey.CASCADE + ) + ], + 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/datastore/PreferencesManager.kt b/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt index 8b48b23..ad44721 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 @@ -36,7 +36,7 @@ private val Context.dataStore: DataStore by preferencesDataStore( */ @Singleton class PreferencesManager @Inject constructor( - private val context: Context + context: Context ) { private val dataStore = context.dataStore @@ -48,9 +48,7 @@ class PreferencesManager @Inject constructor( 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, - currentHomeWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)], - currentLockWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)] + firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true ) } @@ -59,9 +57,7 @@ class PreferencesManager @Inject constructor( 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, - currentHomeWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)], - currentLockWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)] + firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true ) } @@ -75,12 +71,6 @@ class PreferencesManager @Inject constructor( prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = settings.dynamicTheming prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = settings.animate prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = settings.firstLaunch - settings.currentHomeWallpaperId?.let { - prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)] = it - } - settings.currentLockWallpaperId?.let { - prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)] = it - } } } @@ -468,17 +458,6 @@ class PreferencesManager @Inject constructor( } as T } - fun getValueFlow(key: String, defaultValue: T): Flow = dataStore.data.map { prefs -> - @Suppress("UNCHECKED_CAST") - 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 @@ -543,10 +522,6 @@ class PreferencesManager @Inject constructor( prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)) prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)) - // Clear current wallpapers - prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)) - prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)) - // Clear adaptive brightness prefs.remove(booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)) } 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 31de76e..a6c06d8 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 @@ -11,8 +11,10 @@ import com.anthonyla.paperize.core.WallpaperSourceType import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.core.util.generateId import com.anthonyla.paperize.core.util.isValid +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.database.entities.WallpaperCurrentEntity import com.anthonyla.paperize.data.mapper.toDomainModel import com.anthonyla.paperize.data.mapper.toDomainModels import com.anthonyla.paperize.data.mapper.toEntity @@ -20,7 +22,6 @@ 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.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -35,7 +36,8 @@ import java.util.concurrent.ConcurrentHashMap class WallpaperRepositoryImpl @Inject constructor( @param:ApplicationContext private val context: Context, private val wallpaperDao: WallpaperDao, - private val wallpaperQueueDao: WallpaperQueueDao + private val wallpaperQueueDao: WallpaperQueueDao, + private val wallpaperCurrentDao: WallpaperCurrentDao ) : WallpaperRepository { private val contentResolver: ContentResolver = context.contentResolver @@ -165,35 +167,55 @@ class WallpaperRepositoryImpl @Inject constructor( return mutex.withLock { try { - val wallpapers = wallpaperDao.getWallpapersByAlbum(albumId).first() - - // If shuffle is enabled, check if there's an existing queue for another screen type - // with the same album to maintain synchronized order - val otherScreenType = if (shuffle) { - when (screenType) { - ScreenType.HOME -> ScreenType.LOCK - ScreenType.LOCK -> ScreenType.HOME - ScreenType.BOTH -> null - ScreenType.LIVE -> null - } + // 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 otherScreenQueueIds = otherScreenType?.let { + 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 { - wallpaperQueueDao.getQueueItems(albumId, it) - .map { queueItem -> queueItem.wallpaperId } + val otherQueueIsEmpty = wallpaperQueueDao + .getQueueItems(albumId, otherScreenType).isEmpty() + if (otherQueueIsEmpty) { + wallpaperQueueDao.rebuildQueue(albumId, otherScreenType, wallpaperIds) + } } catch (_: Exception) { - null + // Best-effort: if pre-population fails the other screen will build its + // own queue on demand via mergeWithExistingQueue } } - val wallpaperIds = com.anthonyla.paperize.core.util.QueueBuilder.buildQueue( - wallpapers = wallpapers.toDomainModels(), - shuffle = shuffle, - otherScreenQueue = otherScreenQueueIds - ) - - wallpaperQueueDao.rebuildQueue(albumId, screenType, wallpaperIds) Result.Success(Unit) } catch (e: Exception) { Result.Error(e) @@ -227,18 +249,14 @@ class WallpaperRepositoryImpl @Inject constructor( } } - override suspend fun normalizeAllQueuesForAlbum(albumId: String): Result { - return try { - // Normalize queue positions for each active screen type - // This fixes gaps in queue positions caused by CASCADE deletes - // Note: BOTH queue is intentionally excluded — it is never populated or consumed - wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.HOME) - wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LOCK) - wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LIVE) - Result.Success(Unit) - } catch (e: Exception) { - Result.Error(e) - } + + override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? = + wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel() + + override suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String) { + wallpaperCurrentDao.upsertCurrentWallpaper( + WallpaperCurrentEntity(albumId = albumId, screenType = screenType, wallpaperId = wallpaperId) + ) } override suspend fun scanFolderForWallpapers(folderUri: Uri): Result> { 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 a0c1f4a..6288f49 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 @@ -7,9 +7,7 @@ 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, - val currentHomeWallpaperId: String? = null, - val currentLockWallpaperId: String? = null + val firstLaunch: Boolean = true ) { companion object { fun default() = AppSettings() 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 2d7359a..5db7c6c 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 @@ -98,11 +98,16 @@ interface WallpaperRepository { suspend fun clearQueuesForAlbum(albumId: String): Result /** - * Normalize queue positions for all queues (HOME and LOCK) of an album - * Fixes gaps in queue positions caused by CASCADE deletes when wallpapers are removed - * Ensures positions are sequential (0, 1, 2, ...) without gaps + * 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 normalizeAllQueuesForAlbum(albumId: String): Result + suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? + + /** + * 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 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 243f5c2..15adf1a 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 @@ -10,7 +10,6 @@ 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.getDeviceScreenSize -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.domain.repository.SettingsRepository @@ -85,53 +84,52 @@ class ChangeWallpaperUseCase @Inject constructor( } val uri = candidate.uri.toUri() - if (uri.isValid(context.contentResolver)) { - // Try to load and process the bitmap - try { - val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling) - if (bitmap != null) { - // retrieveBitmap already applies scaling via ImageDecoder.setTargetSize - // Apply effects directly to the retrieved bitmap + // Skip the isValid() pre-check — retrieveBitmap returns null on failure, + // which is handled below. Avoiding the extra contentResolver.query() saves + // one round-trip per wallpaper on the hot path. + try { + val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling) + if (bitmap != null) { + var processedBitmap = 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 + ) - var 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() - } - - // Apply adaptive brightness - if (settings.adaptiveBrightness) { - val previousBitmap = processedBitmap - processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap) - if (processedBitmap !== previousBitmap) { - previousBitmap.recycle() - } - } - - finalBitmap = processedBitmap - } else { - // File exists but failed to decode (corrupted) - wallpaperRepository.deleteWallpaper(candidate.id) - maxRetries-- + if (processedBitmap !== bitmap) { + bitmap.recycle() } - } catch (_: Exception) { - // Error during processing, skip this wallpaper - wallpaperRepository.deleteWallpaper(candidate.id) + + if (settings.adaptiveBrightness) { + val previousBitmap = processedBitmap + processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap) + if (processedBitmap !== previousBitmap) { + previousBitmap.recycle() + } + } + + finalBitmap = processedBitmap + + try { + wallpaperRepository.setCurrentWallpaper(albumId, screenType, candidate.id) + } catch (e: Exception) { + android.util.Log.w("ChangeWallpaperUseCase", "Failed to record current wallpaper", e) + } + } else { + // null bitmap — file temporarily inaccessible; skip this cycle. + // Do NOT delete the wallpaper permanently — a transient storage or + // permission issue should not remove it from the user's album. + // RefreshAlbumUseCase is responsible for pruning truly invalid URIs. maxRetries-- } - } else { - // URI invalid - wallpaperRepository.deleteWallpaper(candidate.id) + } catch (_: Exception) { + // Error during bitmap processing; skip this wallpaper this cycle. maxRetries-- } } 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 new file mode 100644 index 0000000..7f417b2 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/ReapplyEffectsUseCase.kt @@ -0,0 +1,85 @@ +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.getDeviceScreenSize +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.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 +) { + suspend operator fun invoke(albumId: String, screenType: ScreenType): Result { + return try { + val current = wallpaperRepository.getCurrentWallpaper(albumId, screenType) + ?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries))) + + val settings = settingsRepository.getScheduleSettings() + val screenSize = getDeviceScreenSize(context) + + 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 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) + ?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries))) + + var 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) { + Result.Error(e) + } + } +} 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 index 5fffcc0..d3dbaa3 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshAlbumUseCase.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/usecase/RefreshAlbumUseCase.kt @@ -31,14 +31,8 @@ class RefreshAlbumUseCase @Inject constructor( totalRemoved += wallpapersResult.data } - // If wallpapers were removed, normalize queue positions to fix gaps from CASCADE deletes if (totalRemoved > 0) { - // Refresh album cover after validation (in case cover wallpaper was removed) albumRepository.refreshAlbumCover(albumId) - - // Normalize both HOME and LOCK queues to fix position gaps - // CASCADE deletes may leave gaps in queue positions (e.g., 0, 2, 4 instead of 0, 1, 2) - wallpaperRepository.normalizeAllQueuesForAlbum(albumId) } // Return error if either operation failed 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 290bacd..6add226 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,6 +2,7 @@ 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 @@ -11,8 +12,6 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.Shape import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @@ -24,11 +23,11 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing @Composable fun SettingSwitchItem( title: String, - description: String? = null, checked: Boolean, onCheckedChange: (Boolean) -> Unit, modifier: Modifier = Modifier, - enabled: Boolean = true + description: String? = null, + enabled: Boolean = true, ) { Card( modifier = modifier @@ -39,7 +38,10 @@ fun SettingSwitchItem( ), shape = MaterialTheme.shapes.medium ) { - Column(modifier = Modifier.padding(AppSpacing.large)) { + Column(modifier = Modifier + .padding(AppSpacing.large) + .semantics(mergeDescendants = true) {} + ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, @@ -77,290 +79,6 @@ fun SettingSwitchItem( } } -/** - * Setting item with a slider - Enhanced with better surface layering - */ -@Composable -fun SettingSliderItem( - title: String, - description: String? = null, - value: Float, - onValueChange: (Float) -> Unit, - valueRange: ClosedFloatingPointRange, - steps: Int = 0, - valueLabel: String? = null, - modifier: Modifier = Modifier, - enabled: Boolean = true -) { - Card( - modifier = modifier.fillMaxWidth(), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ), - shape = MaterialTheme.shapes.medium - ) { - Column(modifier = Modifier.padding(AppSpacing.large)) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column( - modifier = Modifier.weight(1f) - ) { - Text( - text = title, - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - if (description != null) { - Spacer(modifier = Modifier.height(AppSpacing.extraSmall)) - Text( - text = description, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - } - if (valueLabel != null) { - Text( - text = valueLabel, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.primary, - fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - } - - Spacer(modifier = Modifier.height(AppSpacing.small)) - - Slider( - value = value, - onValueChange = onValueChange, - valueRange = valueRange, - steps = steps, - enabled = enabled - ) - } - } -} - -/** - * Setting item with a switch and slider combined - Enhanced with better surface layering - */ -@Composable -fun SettingSwitchWithSliderItem( - title: String, - description: String? = null, - checked: Boolean, - onCheckedChange: (Boolean) -> Unit, - sliderValue: Float, - onSliderValueChange: (Float) -> Unit, - valueRange: ClosedFloatingPointRange, - steps: Int = 0, - valueLabel: String? = null, - modifier: Modifier = Modifier -) { - Card( - modifier = modifier.fillMaxWidth(), - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ), - shape = MaterialTheme.shapes.medium - ) { - Column(modifier = Modifier.padding(AppSpacing.large)) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column( - modifier = Modifier.weight(1f) - ) { - Text( - text = title, - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - if (description != null) { - Spacer(modifier = Modifier.height(AppSpacing.extraSmall)) - Text( - text = description, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - } - Spacer(modifier = Modifier.width(AppSpacing.large)) - Switch( - checked = checked, - onCheckedChange = onCheckedChange - ) - } - - if (checked) { - Spacer(modifier = Modifier.height(AppSpacing.large)) - - if (valueLabel != null) { - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.End - ) { - Text( - text = valueLabel, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.primary, - fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - Spacer(modifier = Modifier.height(AppSpacing.extraSmall)) - } - - Slider( - value = sliderValue, - onValueChange = onSliderValueChange, - valueRange = valueRange, - steps = steps - ) - } - } - } -} - -/** - * Setting clickable item - Enhanced with better surface layering - */ -@Composable -fun SettingClickableItem( - title: String, - description: String? = null, - onClick: () -> Unit, - modifier: Modifier = Modifier, - enabled: Boolean = true, - trailingContent: @Composable (() -> Unit)? = null -) { - Card( - onClick = onClick, - modifier = modifier.fillMaxWidth(), - enabled = enabled, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ), - shape = MaterialTheme.shapes.medium - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically - ) { - Column( - modifier = Modifier.weight(1f) - ) { - Text( - text = title, - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - if (description != null) { - Spacer(modifier = Modifier.height(AppSpacing.extraSmall)) - Text( - text = description, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 3, - overflow = TextOverflow.Ellipsis - ) - } - } - if (trailingContent != null) { - Spacer(modifier = Modifier.width(AppSpacing.large)) - trailingContent() - } - } - } -} - -/** - * Interactive list item with dynamic corner radius animation - * Inspired by Material 3 Expressive design with press feedback - * - * @param headlineContent Main content for the headline - * @param supportingContent Optional supporting text content - * @param leadingContent Optional leading icon or content - * @param trailingContent Optional trailing content (e.g., arrow, switch) - * @param onClick Click handler - * @param items Total number of items in list (for contextual styling) - * @param index Current item index (for contextual styling) - * @param enabled Whether the item is enabled - * @param modifier Modifier for the item - */ -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun InteractiveListItem( - headlineContent: @Composable () -> Unit, - modifier: Modifier = Modifier, - supportingContent: (@Composable () -> Unit)? = null, - leadingContent: (@Composable () -> Unit)? = null, - trailingContent: (@Composable () -> Unit)? = null, - onClick: () -> Unit = {}, - items: Int = 1, - index: Int = 0, - enabled: Boolean = true -) { - val interactionSource = remember { MutableInteractionSource() } - val isPressed by interactionSource.collectIsPressedAsState() - - // Dynamic corner radius based on press state and position - val cornerRadius by animateDpAsState( - targetValue = when { - isPressed -> 40.dp // Large radius when pressed - items == 1 -> 20.dp // Single item gets medium radius - index == 0 || index == items - 1 -> 20.dp // First/last items - else -> 4.dp // Middle items get small radius - }, - label = "corner_radius_animation" - ) - - Surface( - onClick = onClick, - modifier = modifier.clip(RoundedCornerShape(cornerRadius)), - enabled = enabled, - interactionSource = interactionSource, - color = MaterialTheme.colorScheme.surfaceContainer, - contentColor = MaterialTheme.colorScheme.onSurface - ) { - ListItem( - headlineContent = headlineContent, - supportingContent = supportingContent, - leadingContent = leadingContent, - trailingContent = trailingContent, - colors = ListItemDefaults.colors( - containerColor = MaterialTheme.colorScheme.surfaceContainer, - headlineColor = MaterialTheme.colorScheme.onSurface, - supportingColor = MaterialTheme.colorScheme.onSurfaceVariant, - leadingIconColor = MaterialTheme.colorScheme.onSurfaceVariant, - trailingIconColor = MaterialTheme.colorScheme.onSurfaceVariant - ) - ) - } -} - /** * Elevated interactive card with dynamic corner radius * Perfect for cards in lists or grids with press feedback 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 8765859..4eddad5 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 @@ -1,10 +1,12 @@ package com.anthonyla.paperize.presentation.screens.album_view import android.content.Intent -import android.net.Uri import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Arrangement @@ -17,10 +19,9 @@ import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState -import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -28,7 +29,9 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.stringResource +import android.net.Uri +import com.anthonyla.paperize.R import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.presentation.common.components.AddAlbumAnimatedFab @@ -45,21 +48,20 @@ fun AlbumViewScreen( onBackClick: () -> Unit, onNavigateToFolder: (String) -> Unit, onNavigateToWallpaperView: (String, String) -> Unit, - onNavigateToSort: () -> Unit, modifier: Modifier = Modifier, viewModel: AlbumViewViewModel = hiltViewModel() ) { val context = LocalContext.current val lazyListState = rememberLazyGridState() - val album by viewModel.album.collectAsState() - val folders by viewModel.folders.collectAsState() - val wallpapers by viewModel.wallpapers.collectAsState() + val album by viewModel.album.collectAsStateWithLifecycle() + val folders by viewModel.folders.collectAsStateWithLifecycle() + val wallpapers by viewModel.wallpapers.collectAsStateWithLifecycle() // Selection state - val selectedWallpapers by viewModel.selectedWallpapers.collectAsState() - val selectedFolders by viewModel.selectedFolders.collectAsState() - val isSelectionMode by viewModel.isSelectionMode.collectAsState() + val selectedWallpapers by viewModel.selectedWallpapers.collectAsStateWithLifecycle() + val selectedFolders by viewModel.selectedFolders.collectAsStateWithLifecycle() + val isSelectionMode by viewModel.isSelectionMode.collectAsStateWithLifecycle() val selectedCount = selectedWallpapers.size + selectedFolders.size // Check if all items are selected @@ -67,6 +69,7 @@ fun AlbumViewScreen( val allSelected = selectedCount == totalItemsCount && totalItemsCount > 0 var showSortSheet by rememberSaveable { mutableStateOf(false) } + var showDeleteAlbumDialog by rememberSaveable { mutableStateOf(false) } var sortOption by rememberSaveable { mutableStateOf(SortOption.DATE_ADDED_DESC) } // Handle back press when in selection mode @@ -112,7 +115,7 @@ fun AlbumViewScreen( uris.forEach { uri -> try { context.contentResolver.takePersistableUriPermission(uri, takeFlags) - } catch (e: Exception) { + } catch (_: Exception) { // Handle permission failure } } @@ -129,7 +132,7 @@ fun AlbumViewScreen( try { context.contentResolver.takePersistableUriPermission(it, takeFlags) viewModel.addFolder(it.toString()) - } catch (e: Exception) { + } catch (_: Exception) { // Handle permission failure } } @@ -143,8 +146,8 @@ fun AlbumViewScreen( selectedCount = selectedCount, allSelected = allSelected, onBackClick = onBackClick, - onSortClick = onNavigateToSort, - onDeleteAlbum = { viewModel.deleteAlbum(); onBackClick() }, + onSortClick = { showSortSheet = true }, + onDeleteAlbum = { showDeleteAlbumDialog = true }, onSelectAll = { if (allSelected) viewModel.clearSelection() else viewModel.selectAll() }, onDeleteSelected = { viewModel.deleteSelected() }, onClearSelection = { viewModel.clearSelection() } @@ -244,4 +247,26 @@ fun AlbumViewScreen( onDismiss = { showSortSheet = false } ) } + + // Delete Album Confirmation Dialog + if (showDeleteAlbumDialog) { + AlertDialog( + onDismissRequest = { showDeleteAlbumDialog = false }, + title = { Text(stringResource(R.string.delete_album_question)) }, + text = { Text(stringResource(R.string.are_you_sure_you_want_to_delete_this)) }, + confirmButton = { + TextButton( + onClick = { + viewModel.deleteAlbum() + onBackClick() + } + ) { Text(stringResource(R.string.confirm)) } + }, + dismissButton = { + TextButton(onClick = { showDeleteAlbumDialog = false }) { + Text(stringResource(R.string.cancel)) + } + } + ) + } } 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 522a349..e8adcc0 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 @@ -99,8 +99,11 @@ class AlbumViewViewModel @Inject constructor( ) } when (val result = albumRepository.addWallpapersToAlbum(albumId, wallpapers)) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { + is com.anthonyla.paperize.core.Result.Success -> { + // Clear queues so the new wallpapers are included on the next cycle + wallpaperRepository.clearQueuesForAlbum(albumId) + } + is com.anthonyla.paperize.core.Result.Error -> { Log.e(TAG, "Error adding wallpapers to album", result.exception) } is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } @@ -144,9 +147,12 @@ class AlbumViewViewModel @Inject constructor( ) when (val result = albumRepository.addFolderToAlbum(albumId, folder)) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - Log.e(TAG, "Error adding folder to album", result.exception) + is com.anthonyla.paperize.core.Result.Success -> { + // Clear queues so the new folder's wallpapers are included on the next cycle + wallpaperRepository.clearQueuesForAlbum(albumId) + } + is com.anthonyla.paperize.core.Result.Error -> { + Log.e(TAG, "Error adding folder to album", result.exception) } is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } } 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 a789f2b..240c4df 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 @@ -1,7 +1,7 @@ package com.anthonyla.paperize.presentation.screens.folder_view + import com.anthonyla.paperize.core.constants.Constants -import androidx.activity.compose.BackHandler import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Arrangement @@ -16,14 +16,13 @@ import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable -import androidx.compose.runtime.collectAsState +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import com.anthonyla.paperize.presentation.screens.album_view.components.SortBottomSheet import com.anthonyla.paperize.presentation.screens.album_view.components.SortOption @@ -41,8 +40,8 @@ fun FolderViewScreen( ) { val lazyListState = rememberLazyGridState() - val folder by viewModel.folder.collectAsState() - val wallpapers by viewModel.wallpapers.collectAsState() + val folder by viewModel.folder.collectAsStateWithLifecycle() + val wallpapers by viewModel.wallpapers.collectAsStateWithLifecycle() var showSortSheet by rememberSaveable { mutableStateOf(false) } var sortOption by rememberSaveable { mutableStateOf(SortOption.DATE_ADDED_DESC) } @@ -59,8 +58,6 @@ fun FolderViewScreen( } } - BackHandler { onBackClick() } - Scaffold( topBar = { FolderViewTopBar( @@ -83,28 +80,22 @@ fun FolderViewScreen( items = sortedWallpapers, key = { wallpaper -> wallpaper.id } ) { wallpaper -> - val itemModifier = remember { - Modifier - .fillMaxWidth() - .aspectRatio(9f / 16f) - .then( - Modifier.animateItem( - placementSpec = tween( - durationMillis = Constants.ANIMATION_DURATION_LONG_MS, - delayMillis = 0, - easing = FastOutSlowInEasing - ) - ) - ) - } - WallpaperItem( wallpaperUri = wallpaper.uri, isSelected = false, isSelectionMode = false, onClick = { onNavigateToWallpaperView(wallpaper.uri, wallpaper.fileName) }, onLongClick = { /* No selection in folder view */ }, - modifier = itemModifier + modifier = Modifier + .fillMaxWidth() + .aspectRatio(9f / 16f) + .animateItem( + placementSpec = tween( + durationMillis = Constants.ANIMATION_DURATION_LONG_MS, + delayMillis = 0, + easing = FastOutSlowInEasing + ) + ) ) } } 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 782cfba..bbaf23a 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 @@ -1,11 +1,8 @@ package com.anthonyla.paperize.presentation.screens.home -import com.anthonyla.paperize.core.constants.Constants import android.app.WallpaperManager import android.content.ComponentName import android.content.Intent -import androidx.activity.compose.rememberLauncherForActivityResult -import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize @@ -24,14 +21,11 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf -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.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource @@ -39,7 +33,6 @@ import androidx.compose.ui.text.font.FontWeight import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import com.anthonyla.paperize.R import com.anthonyla.paperize.core.WallpaperMode -import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.presentation.screens.home.components.HomeTopBar import com.anthonyla.paperize.presentation.screens.home.components.getTabItems import com.anthonyla.paperize.presentation.screens.library.LibraryScreen @@ -54,11 +47,11 @@ fun HomeScreen( modifier: Modifier = Modifier, viewModel: HomeViewModel = hiltViewModel() ) { - val albums by viewModel.albums.collectAsState() - val scheduleSettings by viewModel.scheduleSettings.collectAsState() - val appSettings by viewModel.appSettings.collectAsState() - val wallpaperMode by viewModel.wallpaperMode.collectAsState() - val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsState() + val albums by viewModel.albums.collectAsStateWithLifecycle() + val scheduleSettings by viewModel.scheduleSettings.collectAsStateWithLifecycle() + val appSettings by viewModel.appSettings.collectAsStateWithLifecycle() + val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle() + val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsStateWithLifecycle() val coroutineScope = rememberCoroutineScope() val context = LocalContext.current @@ -114,7 +107,7 @@ fun HomeScreen( state = pagerState, beyondViewportPageCount = 1 ) { index -> - when (index.coerceIn(tabItems.indices)) { + when (index) { 0 -> { if (wallpaperMode == null) { Box(modifier = Modifier.fillMaxSize()) @@ -181,12 +174,12 @@ fun HomeScreen( ) } context.startActivity(intent) - } catch (e: Exception) { + } catch (_: Exception) { // Fallback: Open general wallpaper settings try { val fallbackIntent = Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER) context.startActivity(fallbackIntent) - } catch (e2: Exception) { + } 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 b6e370f..b171a2b 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 @@ -1,5 +1,4 @@ package com.anthonyla.paperize.presentation.screens.home -import com.anthonyla.paperize.core.constants.Constants import android.content.Context import android.content.Intent @@ -7,13 +6,12 @@ import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.anthonyla.paperize.core.ScreenType +import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.core.util.isPaperizeLiveWallpaperActive -import com.anthonyla.paperize.domain.model.Album 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.DeleteAlbumUseCase import com.anthonyla.paperize.domain.usecase.GetAlbumSummariesUseCase import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService import com.anthonyla.paperize.service.worker.WallpaperScheduler @@ -34,7 +32,6 @@ class HomeViewModel @Inject constructor( @param:ApplicationContext private val context: Context, getAlbumSummariesUseCase: GetAlbumSummariesUseCase, private val createAlbumUseCase: CreateAlbumUseCase, - private val deleteAlbumUseCase: DeleteAlbumUseCase, private val settingsRepository: SettingsRepository, private val wallpaperScheduler: WallpaperScheduler, private val wallpaperRepository: com.anthonyla.paperize.domain.repository.WallpaperRepository @@ -127,36 +124,6 @@ class HomeViewModel @Inject constructor( } } - fun deleteAlbum(albumId: String) { - viewModelScope.launch { - // Atomically clear album selections if they match (prevents race conditions) - val wasCleared = settingsRepository.clearAlbumSelectionsIfMatches(albumId) - - // Disable changer if albums were cleared and no albums remain selected - if (wasCleared) { - val settings = settingsRepository.getScheduleSettings() - // Check appropriate album IDs based on wallpaper mode - val shouldDisable = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) { - settings.liveAlbumId == null - } else { - settings.homeAlbumId == null && settings.lockAlbumId == null - } - if (shouldDisable) { - toggleWallpaperChanger(false) - } - } - - // Delete the album - when (val result = deleteAlbumUseCase(albumId)) { - is com.anthonyla.paperize.core.Result.Success -> { /* Success */ } - is com.anthonyla.paperize.core.Result.Error -> { - Log.e(TAG, "Error deleting album", result.exception) - } - is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ } - } - } - } - fun selectHomeAlbum(album: AlbumSummary?) { viewModelScope.launch { // Use atomic update to prevent race conditions with selectLockAlbum() @@ -376,11 +343,12 @@ class HomeViewModel @Inject constructor( val screenToggleChanged = currentSettings.homeEnabled != settings.homeEnabled || currentSettings.lockEnabled != settings.lockEnabled - // If screen toggles changed, clear all album selections + // 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) { settings.copy( - homeAlbumId = null, - lockAlbumId = null + homeAlbumId = if (!settings.homeEnabled) null else settings.homeAlbumId, + lockAlbumId = if (!settings.lockEnabled) null else settings.lockAlbumId ) } else { settings @@ -441,10 +409,10 @@ class HomeViewModel @Inject constructor( validated.homeAlbumId == validated.lockAlbumId && !validated.separateSchedules if (isSynced) { - changeWallpaperNow(ScreenType.BOTH) + reapplyEffectsNow(ScreenType.BOTH) } else { - if (homeActive) changeWallpaperNow(ScreenType.HOME) - if (lockActive) changeWallpaperNow(ScreenType.LOCK) + if (homeActive) reapplyEffectsNow(ScreenType.HOME) + if (lockActive) reapplyEffectsNow(ScreenType.LOCK) } } } @@ -458,6 +426,14 @@ class HomeViewModel @Inject constructor( context.startForegroundService(intent) } + fun reapplyEffectsNow(screenType: ScreenType) { + val intent = Intent(context, WallpaperChangeService::class.java).apply { + action = WallpaperChangeService.ACTION_REAPPLY_EFFECTS + putExtra(WallpaperChangeService.EXTRA_SCREEN_TYPE, screenType.name) + } + context.startForegroundService(intent) + } + private fun scheduleAlarms(settings: ScheduleSettings, onlyIfNotScheduled: Boolean = false) { // Check if we're in LIVE mode if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) { 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 bec04b3..4b79097 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,14 +23,12 @@ 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.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.presentation.common.components.AddAlbumDialog @@ -47,7 +45,8 @@ fun LibraryScreen( ) { val lazyListState = rememberLazyGridState() var showAddAlbumDialog by rememberSaveable { mutableStateOf(false) } - var albumNameError by remember { mutableStateOf(null) } + var albumNameError by rememberSaveable { mutableStateOf(null) } + val albumNameExistsError = stringResource(R.string.album_name_exists_error) Scaffold( modifier = modifier.fillMaxSize(), @@ -102,7 +101,9 @@ fun LibraryScreen( } else { LazyVerticalGrid( state = lazyListState, - modifier = Modifier.fillMaxSize(), + modifier = Modifier + .fillMaxSize() + .padding(paddingValues), columns = GridCells.Adaptive(AppGrid.itemMinSize), contentPadding = PaddingValues(AppSpacing.gridPadding), horizontalArrangement = Arrangement.Start @@ -119,9 +120,8 @@ fun LibraryScreen( } if (showAddAlbumDialog) { - val errorMessageString = stringResource(R.string.album_name_exists_error) AddAlbumDialog( - onDismiss = { + onDismiss = { showAddAlbumDialog = false albumNameError = null }, @@ -129,7 +129,7 @@ fun LibraryScreen( // Check if album with this name already exists val isDuplicate = albums.any { it.name.equals(name, ignoreCase = true) } if (isDuplicate) { - albumNameError = errorMessageString + albumNameError = albumNameExistsError } else { onCreateAlbum(name) showAddAlbumDialog = false 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 e9d3fce..41ecc22 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 @@ -5,7 +5,6 @@ import com.anthonyla.paperize.presentation.theme.AppShapes import com.anthonyla.paperize.presentation.theme.AppBorderWidths import android.content.Context -import android.net.Uri import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement @@ -20,15 +19,17 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.PhotoAlbum -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults 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.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 @@ -37,6 +38,7 @@ 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.request.ImageRequest import coil3.size.Size @@ -54,8 +56,11 @@ fun AlbumItem( modifier: Modifier = Modifier ) { val context = LocalContext.current - val showCoverUri by remember(album.coverUri) { - mutableStateOf(!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri)) + var showCoverUri by remember(album.coverUri) { mutableStateOf(false) } + LaunchedEffect(album.coverUri) { + showCoverUri = withContext(Dispatchers.IO) { + !album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri) + } } InteractiveCard( @@ -87,7 +92,7 @@ fun AlbumItem( if (showCoverUri) { AsyncImage( model = ImageRequest.Builder(context) - .data(Uri.parse(album.coverUri)) + .data(album.coverUri!!.toUri()) .size(Size(400, 400)) // Limit size for performance .build(), contentDescription = album.name, @@ -126,9 +131,9 @@ fun AlbumItem( private fun isValidUri(context: Context, uriString: String?): Boolean { if (uriString.isNullOrEmpty()) return false return try { - val uri = Uri.parse(uriString) + val uri = uriString.toUri() context.contentResolver.openInputStream(uri)?.use { true } ?: false - } catch (e: Exception) { + } catch (_: Exception) { false } } 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 f019791..c510f64 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 @@ -17,17 +17,17 @@ 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.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.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.text.style.TextOverflow import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.common.components.SettingSwitchItem import com.anthonyla.paperize.presentation.theme.AppSpacing -import com.anthonyla.paperize.core.util.BatteryOptimizationUtil import com.anthonyla.paperize.core.util.BatteryOptimizationUtil.isIgnoringBatteryOptimizations import com.anthonyla.paperize.core.util.BatteryOptimizationUtil.requestIgnoreBatteryOptimizations @@ -42,15 +42,15 @@ fun SettingsScreen( modifier: Modifier = Modifier, viewModel: SettingsViewModel = hiltViewModel() ) { - val appSettings by viewModel.appSettings.collectAsState() - val wallpaperMode by viewModel.wallpaperMode.collectAsState() + val appSettings by viewModel.appSettings.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 var isIgnoringBatteryOptimizations by remember { - mutableStateOf(BatteryOptimizationUtil.isIgnoringBatteryOptimizations(context)) + mutableStateOf(isIgnoringBatteryOptimizations(context)) } // Refresh battery optimization status when returning to the screen @@ -58,7 +58,7 @@ fun SettingsScreen( DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) { - isIgnoringBatteryOptimizations = BatteryOptimizationUtil.isIgnoringBatteryOptimizations(context) + isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations(context) } } lifecycleOwner.lifecycle.addObserver(observer) @@ -250,8 +250,8 @@ fun SettingsScreen( if (!isIgnoringBatteryOptimizations) { Button( - onClick = { - BatteryOptimizationUtil.requestIgnoreBatteryOptimizations(context) + onClick = { + requestIgnoreBatteryOptimizations(context) } ) { Text(stringResource(R.string.check_status)) 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 6a3c22d..7d45075 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 @@ -22,7 +22,6 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Close @@ -43,10 +42,10 @@ 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.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -130,7 +129,7 @@ fun SortViewScreen( AnimatedContent( modifier = Modifier.fillMaxSize(), targetState = !expandedFolderId.isNullOrEmpty(), - label = "", + label = "sort_view_content", ) { targetState -> with(this@SharedTransitionLayout) { if (!targetState) { @@ -155,7 +154,7 @@ fun SortViewScreen( ReorderableItem( state = reorderableLazyListStateFolder, key = folder.uri - ) { isDragging -> + ) { _ -> val interactionSource = remember { MutableInteractionSource() } Card( modifier = Modifier @@ -234,7 +233,7 @@ fun SortViewScreen( ReorderableItem( reorderableLazyListStateWallpaper, key = wallpaper.uri - ) { isDragging -> + ) { _ -> val interactionSource = remember { MutableInteractionSource() } Card( modifier = Modifier @@ -357,7 +356,7 @@ fun SortViewScreen( ReorderableItem( reorderableFolderWallpapersState, key = wallpaper.uri - ) { isDragging -> + ) { _ -> val interactionSource = remember { MutableInteractionSource() } Card( modifier = Modifier 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 8a34941..9cd63c8 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,7 +1,7 @@ package com.anthonyla.paperize.presentation.screens.startup -import android.graphics.Bitmap import android.graphics.Canvas +import androidx.core.graphics.createBitmap import androidx.appcompat.content.res.AppCompatResources import com.anthonyla.paperize.presentation.components.OnboardingLayout import androidx.compose.foundation.BorderStroke @@ -48,24 +48,28 @@ fun StartupScreen( ) { val context = LocalContext.current val appIcon = remember { - val drawable = AppCompatResources.getDrawable(context, R.mipmap.ic_launcher_round)!! - val size = 192 // Use a fixed high resolution size - val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888) - val canvas = Canvas(bitmap) - drawable.setBounds(0, 0, size, size) - drawable.draw(canvas) - bitmap.asImageBitmap() + 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 } OnboardingLayout( title = stringResource(R.string.app_name), modifier = modifier, iconContent = { - Image( - bitmap = appIcon, - contentDescription = null, - modifier = Modifier.size(100.dp) - ) + if (appIcon != null) { + Image( + bitmap = appIcon, + contentDescription = null, + modifier = Modifier.size(100.dp) + ) + } }, content = { Column( @@ -91,7 +95,7 @@ fun StartupScreen( colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) ), - border = androidx.compose.foundation.BorderStroke( + border = BorderStroke( width = 1.dp, color = MaterialTheme.colorScheme.outlineVariant ) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt index a6f7fbf..66f53af 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt @@ -4,13 +4,8 @@ import com.anthonyla.paperize.presentation.components.OnboardingLayout import com.anthonyla.paperize.core.util.PermissionUtil import android.content.Intent -import android.net.Uri -import android.os.Build -import android.os.Environment import android.provider.Settings 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.Folder import androidx.compose.material3.* @@ -18,14 +13,14 @@ import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.compose.LocalLifecycleOwner 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.net.toUri import com.anthonyla.paperize.R -import com.anthonyla.paperize.core.constants.Constants +import androidx.compose.ui.unit.dp import com.anthonyla.paperize.presentation.theme.AppSpacing /** @@ -39,18 +34,18 @@ fun StoragePermissionScreen( ) { val context = LocalContext.current var permissionGranted by remember { mutableStateOf(PermissionUtil.hasStoragePermission()) } + val lifecycleOwner = LocalLifecycleOwner.current // Check permission status on resume (when user returns from settings) - DisposableEffect(Unit) { + DisposableEffect(lifecycleOwner) { val listener = object : DefaultLifecycleObserver { override fun onResume(owner: LifecycleOwner) { permissionGranted = PermissionUtil.hasStoragePermission() } } - val lifecycleOwner = context as? LifecycleOwner - lifecycleOwner?.lifecycle?.addObserver(listener) + lifecycleOwner.lifecycle.addObserver(listener) onDispose { - lifecycleOwner?.lifecycle?.removeObserver(listener) + lifecycleOwner.lifecycle.removeObserver(listener) } } @@ -118,7 +113,7 @@ fun StoragePermissionScreen( onClick = { if (!PermissionUtil.hasStoragePermission()) { val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply { - data = Uri.parse("package:${context.packageName}") + data = "package:${context.packageName}".toUri() } context.startActivity(intent) } else { 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 be35e02..8139413 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 @@ -43,9 +43,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import com.anthonyla.paperize.R import com.anthonyla.paperize.core.ScalingType -import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.WallpaperMode -import com.anthonyla.paperize.domain.model.Album import com.anthonyla.paperize.domain.model.AlbumSummary import com.anthonyla.paperize.domain.model.AppSettings import com.anthonyla.paperize.domain.model.ScheduleSettings @@ -77,7 +75,7 @@ fun WallpaperScreen( ) { var showAlbumSelectionSheet by rememberSaveable { mutableStateOf(false) } var albumSelectionContext by rememberSaveable { mutableStateOf(AlbumSelectionContext.BOTH) } - var showEmptyAlbumWarning by remember { mutableStateOf(false) } + var showEmptyAlbumWarning by rememberSaveable { mutableStateOf(false) } // Settings debouncing var pendingSettings by remember { mutableStateOf(null) } @@ -165,9 +163,10 @@ fun WallpaperScreen( stringResource(R.string.none) ) - var selectedScalingIndex by rememberSaveable { + val scalingTypeFromSettings = if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType + var selectedScalingIndex by remember(scalingTypeFromSettings) { mutableIntStateOf( - when (if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType) { + when (scalingTypeFromSettings) { ScalingType.FILL -> 0 ScalingType.FIT -> 1 ScalingType.STRETCH -> 2 @@ -364,7 +363,8 @@ fun WallpaperScreen( modifier = Modifier .fillMaxWidth() .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically ) { Column(modifier = Modifier.weight(1f)) { Text( @@ -374,12 +374,14 @@ fun WallpaperScreen( 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.bodySmall, + style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis @@ -388,7 +390,7 @@ fun WallpaperScreen( Icon( imageVector = Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant + tint = MaterialTheme.colorScheme.primary ) } } @@ -519,7 +521,7 @@ fun WallpaperScreen( title = stringResource(R.string.interval_text), minutes = scheduleSettings.homeIntervalMinutes, onMinutesChange = { minutes -> - onUpdateScheduleSettings( + updateSettingsDebounced( scheduleSettings.copy( homeIntervalMinutes = minutes, lockIntervalMinutes = minutes @@ -1083,8 +1085,6 @@ fun WallpaperScreen( } } } - // Dismiss the bottom sheet after selection - showAlbumSelectionSheet = false }, onDismiss = { showAlbumSelectionSheet = false } ) 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 dd29ea4..b199e71 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 @@ -4,7 +4,6 @@ import com.anthonyla.paperize.presentation.theme.AppBorderWidths import com.anthonyla.paperize.core.constants.Constants import android.content.Context -import android.net.Uri import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement @@ -20,7 +19,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.PhotoAlbum @@ -33,9 +31,13 @@ import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState 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 kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -44,7 +46,7 @@ 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.compose.ui.unit.dp +import androidx.core.net.toUri import coil3.compose.AsyncImage import coil3.request.ImageRequest import coil3.size.Size @@ -118,8 +120,11 @@ private fun AlbumSelectionItem( modifier: Modifier = Modifier ) { val context = LocalContext.current - val showCoverUri by remember(album.coverUri) { - mutableStateOf(!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri)) + var showCoverUri by remember(album.coverUri) { mutableStateOf(false) } + LaunchedEffect(album.coverUri) { + showCoverUri = withContext(Dispatchers.IO) { + !album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri) + } } Row( @@ -146,7 +151,7 @@ private fun AlbumSelectionItem( if (showCoverUri) { AsyncImage( model = ImageRequest.Builder(context) - .data(Uri.parse(album.coverUri)) + .data(album.coverUri!!.toUri()) .size(Size(Constants.LIST_THUMBNAIL_SIZE, Constants.LIST_THUMBNAIL_SIZE)) // Small thumbnail for list item .build(), contentDescription = album.name, @@ -197,9 +202,9 @@ private fun AlbumSelectionItem( private fun isValidUri(context: Context, uriString: String?): Boolean { if (uriString.isNullOrEmpty()) return false return try { - val uri = Uri.parse(uriString) + val uri = uriString.toUri() context.contentResolver.openInputStream(uri)?.use { true } ?: false - } catch (e: Exception) { + } catch (_: Exception) { false } } 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 index 68373cc..780d110 100644 --- 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 @@ -20,6 +20,7 @@ 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 @@ -46,7 +47,8 @@ fun SettingSwitch( Row( modifier = Modifier .fillMaxWidth() - .padding(AppSpacing.large), + .padding(AppSpacing.large) + .semantics(mergeDescendants = true) {}, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitchWithSlider.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitchWithSlider.kt index b2cd9f0..3c2d56b 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitchWithSlider.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/components/SettingSwitchWithSlider.kt @@ -21,9 +21,9 @@ import androidx.compose.runtime.setValue 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.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppSpacing import kotlin.math.roundToInt @@ -64,7 +64,9 @@ fun SettingSwitchWithSlider( ) { // Header with title and switch Row( - modifier = Modifier.fillMaxWidth(), + modifier = Modifier + .fillMaxWidth() + .semantics(mergeDescendants = true) {}, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { 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 b8190bf..38b97a9 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 @@ -4,10 +4,8 @@ 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.padding -import androidx.compose.foundation.layout.width import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField @@ -21,13 +19,11 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.presentation.theme.AppSpacing @@ -60,8 +56,8 @@ fun TimeIntervalPicker( 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 - var lastChangeTimestamp by remember { mutableStateOf(0L) } + // Debounce state - tracks when user last made a change; reset when external `minutes` prop changes + var lastChangeTimestamp by remember(minutes) { mutableStateOf(0L) } // Debounced update - only fires after user stops typing LaunchedEffect(dayValue, hourValue, minuteValue, lastChangeTimestamp) { @@ -170,27 +166,28 @@ fun TimeIntervalPicker( @Composable private fun formatIntervalComposable(minutes: Int): String { val minUnit = stringResource(R.string.time_unit_min) - val hourUnit = pluralStringResource(R.plurals.time_unit_hours, 1) - val hoursUnit = pluralStringResource(R.plurals.time_unit_hours, 2) - val dayUnit = pluralStringResource(R.plurals.time_unit_days, 1) - val daysUnit = pluralStringResource(R.plurals.time_unit_days, 2) return when { minutes < Constants.MINUTES_PER_HOUR -> "$minutes $minUnit" minutes < Constants.MINUTES_PER_DAY -> { - val hours = minutes / Constants.MINUTES_PER_HOUR + val h = minutes / Constants.MINUTES_PER_HOUR val remainingMins = minutes % Constants.MINUTES_PER_HOUR - if (remainingMins == 0) "$hours ${if (hours > 1) hoursUnit else hourUnit}" - else "$hours ${if (hours > 1) hoursUnit else hourUnit} $remainingMins $minUnit" + val hUnit = pluralStringResource(R.plurals.time_unit_hours, h) + if (remainingMins == 0) "$h $hUnit" + else "$h $hUnit $remainingMins $minUnit" } else -> { - val days = minutes / Constants.MINUTES_PER_DAY + val d = minutes / Constants.MINUTES_PER_DAY val remainingMinutes = minutes % Constants.MINUTES_PER_DAY val remainingHours = remainingMinutes / Constants.MINUTES_PER_HOUR val finalMins = remainingMinutes % Constants.MINUTES_PER_HOUR + val dUnit = pluralStringResource(R.plurals.time_unit_days, d) buildString { - append("$days ${if (days > 1) daysUnit else dayUnit}") - if (remainingHours > 0) append(" $remainingHours ${if (remainingHours > 1) hoursUnit else hourUnit}") + append("$d $dUnit") + if (remainingHours > 0) { + val hUnit = pluralStringResource(R.plurals.time_unit_hours, remainingHours) + append(" $remainingHours $hUnit") + } if (finalMins > 0) append(" $finalMins $minUnit") } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_view/WallpaperViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_view/WallpaperViewScreen.kt index 56bb519..f222d33 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_view/WallpaperViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_view/WallpaperViewScreen.kt @@ -1,8 +1,6 @@ package com.anthonyla.paperize.presentation.screens.wallpaper_view -import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding @@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.requiredSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.BottomAppBar -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -30,7 +27,6 @@ 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 com.anthonyla.paperize.R import com.anthonyla.paperize.presentation.theme.AppSpacing import net.engawapg.lib.zoomable.rememberZoomState @@ -46,8 +42,6 @@ fun WallpaperViewScreen( ) { val zoomState = rememberZoomState() - BackHandler { onBackClick() } - Scaffold( modifier = modifier.fillMaxSize(), topBar = { @@ -56,7 +50,7 @@ fun WallpaperViewScreen( containerColor = Color.Transparent ), title = { - if (zoomState.scale == 1f) { + if (zoomState.scale <= 1.01f) { Text( text = wallpaperName, color = MaterialTheme.colorScheme.surfaceBright, 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 95f7970..00b83d7 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 @@ -16,7 +16,9 @@ import com.anthonyla.paperize.core.EmptyAlbumException import com.anthonyla.paperize.core.ScreenType import com.anthonyla.paperize.core.constants.Constants 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 dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.CoroutineScope @@ -40,6 +42,12 @@ class WallpaperChangeService : Service() { @Inject lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase + @Inject + lateinit var reapplyEffectsUseCase: ReapplyEffectsUseCase + + @Inject + lateinit var wallpaperRepository: WallpaperRepository + @Inject lateinit var settingsRepository: SettingsRepository @@ -51,6 +59,7 @@ class WallpaperChangeService : Service() { companion object { private const val TAG = "WallpaperChangeService" const val ACTION_CHANGE_WALLPAPER = Constants.ACTION_CHANGE_WALLPAPER + const val ACTION_REAPPLY_EFFECTS = Constants.ACTION_REAPPLY_EFFECTS const val EXTRA_SCREEN_TYPE = Constants.EXTRA_SCREEN_TYPE private const val ERROR_NOTIFICATION_ID = Constants.NOTIFICATION_ID + 1 @@ -89,6 +98,12 @@ class WallpaperChangeService : Service() { } ?: ScreenType.BOTH handleChangeWallpaper(screenType, startId) } + ACTION_REAPPLY_EFFECTS -> { + val screenType = intent.getStringExtra(EXTRA_SCREEN_TYPE)?.let { + ScreenType.fromString(it) + } ?: ScreenType.BOTH + handleReapplyEffects(screenType, startId) + } } return START_NOT_STICKY @@ -158,6 +173,28 @@ class WallpaperChangeService : Service() { ) Log.d(TAG, "Same wallpaper set for both screens") + + // Keep LOCK queue in sync with HOME so that if the user later + // switches to separate schedules, both screens continue from + // the same queue position rather than LOCK restarting at 0. + try { + val homeCurrentId = wallpaperRepository + .getCurrentWallpaper(homeAlbumId, ScreenType.HOME)?.id + if (homeCurrentId != null) { + // Ensure LOCK queue exists (first run in synced mode) + if (wallpaperRepository.getNextWallpaperInQueue( + homeAlbumId, ScreenType.LOCK) == null) { + wallpaperRepository.buildWallpaperQueue( + homeAlbumId, ScreenType.LOCK, settings.shuffleEnabled) + } + wallpaperRepository.getAndDequeueWallpaper( + homeAlbumId, ScreenType.LOCK) + wallpaperRepository.setCurrentWallpaper( + homeAlbumId, ScreenType.LOCK, homeCurrentId) + } + } catch (e: Exception) { + Log.w(TAG, "Failed to sync LOCK queue in BOTH mode", e) + } } catch (e: Exception) { Log.e(TAG, "Error setting wallpaper for both screens", e) } finally { @@ -265,6 +302,87 @@ class WallpaperChangeService : Service() { } } + /** + * Reapply current effects to the last-applied wallpaper without advancing the queue. + * Falls back to a normal queue advance if no current wallpaper is recorded. + */ + private fun handleReapplyEffects(screenType: ScreenType, startId: Int) { + serviceScope.launch { + wallpaperChangeMutex.withLock { + try { + val settings = settingsRepository.getScheduleSettings() + when (screenType) { + ScreenType.HOME -> { + val albumId = settings.homeAlbumId ?: run { + Log.w(TAG, "No home album selected for reapply"); return@withLock + } + reapplyHome(albumId) + } + ScreenType.LOCK -> { + val albumId = settings.lockAlbumId ?: run { + Log.w(TAG, "No lock album selected for reapply"); return@withLock + } + reapplyLock(albumId) + } + ScreenType.BOTH -> { + val homeAlbumId = settings.homeAlbumId + val lockAlbumId = settings.lockAlbumId + if (homeAlbumId != null) reapplyHome(homeAlbumId) + if (lockAlbumId != null) reapplyLock(lockAlbumId) + } + ScreenType.LIVE -> Unit // handled by live wallpaper service + } + stopSelf(startId) + } catch (e: Exception) { + Log.e(TAG, "Error reapplying effects", e) + stopSelf(startId) + } + } + } + } + + private suspend fun reapplyHome(albumId: String) { + val result = reapplyEffectsUseCase(albumId, ScreenType.HOME) + result.onSuccess { bitmap -> + try { + if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.isRecycled) { + throw IllegalStateException("Invalid bitmap for reapply") + } + wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_SYSTEM) + Log.d(TAG, "Home effects reapplied successfully") + } catch (e: Exception) { + Log.e(TAG, "Error setting home wallpaper during reapply", e) + } finally { + bitmap.recycle() + } + }.onError { error -> + // Current wallpaper not recorded yet — fall back to normal queue advance + Log.w(TAG, "Reapply failed for home, falling back to change: ${error.message}") + changeHomeWallpaper(albumId) + } + } + + private suspend fun reapplyLock(albumId: String) { + val result = reapplyEffectsUseCase(albumId, ScreenType.LOCK) + result.onSuccess { bitmap -> + try { + if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.isRecycled) { + throw IllegalStateException("Invalid bitmap for reapply") + } + wallpaperManager.setBitmap(bitmap, null, true, WallpaperManager.FLAG_LOCK) + Log.d(TAG, "Lock effects reapplied successfully") + } catch (e: Exception) { + Log.e(TAG, "Error setting lock wallpaper during reapply", e) + } finally { + bitmap.recycle() + } + }.onError { error -> + // Current wallpaper not recorded yet — fall back to normal queue advance + Log.w(TAG, "Reapply failed for lock, falling back to change: ${error.message}") + changeLockWallpaper(albumId) + } + } + private fun createNotification(): Notification { val intent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity( 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 053c5e6..7d8918b 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 @@ -6,9 +6,11 @@ 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.ScreenType import com.anthonyla.paperize.core.constants.Constants import com.anthonyla.paperize.domain.repository.SettingsRepository +import com.anthonyla.paperize.domain.repository.WallpaperRepository import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase import dagger.assisted.Assisted import dagger.assisted.AssistedInject @@ -26,7 +28,8 @@ class WallpaperChangeWorker @AssistedInject constructor( @Assisted private val context: Context, @Assisted workerParams: WorkerParameters, private val changeWallpaperUseCase: ChangeWallpaperUseCase, - private val settingsRepository: SettingsRepository + private val settingsRepository: SettingsRepository, + private val wallpaperRepository: WallpaperRepository ) : CoroutineWorker(context, workerParams) { companion object { @@ -79,7 +82,7 @@ class WallpaperChangeWorker @AssistedInject constructor( ScreenType.HOME -> { val homeAlbumId = settings.homeAlbumId if (homeAlbumId != null) { - changeHomeWallpaper(homeAlbumId, wallpaperManager) + changeHomeWallpaper(homeAlbumId, settings, wallpaperManager) } else { Log.w(TAG, "No home album selected") } @@ -87,7 +90,7 @@ class WallpaperChangeWorker @AssistedInject constructor( ScreenType.LOCK -> { val lockAlbumId = settings.lockAlbumId if (lockAlbumId != null) { - changeLockWallpaper(lockAlbumId, wallpaperManager) + changeLockWallpaper(lockAlbumId, settings, wallpaperManager) } else { Log.w(TAG, "No lock album selected") } @@ -127,6 +130,27 @@ class WallpaperChangeWorker @AssistedInject constructor( ) Log.d(TAG, "Both screens wallpaper changed successfully") + + // Keep LOCK queue in sync with HOME so that if the user later + // switches to separate schedules, both screens continue from + // the same queue position rather than LOCK restarting at 0. + try { + val homeCurrentId = wallpaperRepository + .getCurrentWallpaper(albumId, ScreenType.HOME)?.id + if (homeCurrentId != null) { + if (wallpaperRepository.getNextWallpaperInQueue( + albumId, ScreenType.LOCK) == null) { + wallpaperRepository.buildWallpaperQueue( + albumId, ScreenType.LOCK, settings.shuffleEnabled) + } + wallpaperRepository.getAndDequeueWallpaper( + albumId, ScreenType.LOCK) + wallpaperRepository.setCurrentWallpaper( + albumId, ScreenType.LOCK, homeCurrentId) + } + } catch (e: Exception) { + Log.w(TAG, "Failed to sync LOCK queue in BOTH mode", e) + } } catch (e: Exception) { Log.e(TAG, "Error setting wallpaper for both screens", e) throw e @@ -134,8 +158,18 @@ class WallpaperChangeWorker @AssistedInject constructor( bitmap.recycle() } }.onError { error -> - Log.e(TAG, "Error getting wallpaper bitmap for both screens", error) - throw error + if (error is EmptyAlbumException) { + Log.w(TAG, "Album is empty for BOTH screens — disabling changer") + val updatedSettings = settings.copy( + homeAlbumId = null, + lockAlbumId = null, + enableChanger = false + ) + settingsRepository.updateScheduleSettings(updatedSettings) + } else { + Log.e(TAG, "Error getting wallpaper bitmap for both screens", error) + throw error + } } } else { Log.w(TAG, "No album selected for synchronized mode") @@ -144,7 +178,7 @@ class WallpaperChangeWorker @AssistedInject constructor( } } - private suspend fun changeHomeWallpaper(albumId: String, wallpaperManager: WallpaperManager) { + private suspend fun changeHomeWallpaper(albumId: String, settings: com.anthonyla.paperize.domain.model.ScheduleSettings, wallpaperManager: WallpaperManager) { val result = changeWallpaperUseCase(albumId, ScreenType.HOME) result.onSuccess { bitmap -> try { @@ -173,12 +207,21 @@ class WallpaperChangeWorker @AssistedInject constructor( bitmap.recycle() } }.onError { error -> - Log.e(TAG, "Error getting home wallpaper bitmap", error) - throw error + if (error is EmptyAlbumException) { + Log.w(TAG, "Home album is empty — disabling home screen") + val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null + settingsRepository.updateScheduleSettings(settings.copy( + homeAlbumId = null, + enableChanger = if (lockStillActive) settings.enableChanger else false + )) + } else { + Log.e(TAG, "Error getting home wallpaper bitmap", error) + throw error + } } } - private suspend fun changeLockWallpaper(albumId: String, wallpaperManager: WallpaperManager) { + private suspend fun changeLockWallpaper(albumId: String, settings: com.anthonyla.paperize.domain.model.ScheduleSettings, wallpaperManager: WallpaperManager) { val result = changeWallpaperUseCase(albumId, ScreenType.LOCK) result.onSuccess { bitmap -> try { @@ -207,8 +250,17 @@ class WallpaperChangeWorker @AssistedInject constructor( bitmap.recycle() } }.onError { error -> - Log.e(TAG, "Error getting lock wallpaper bitmap", error) - throw error + if (error is EmptyAlbumException) { + Log.w(TAG, "Lock album is empty — disabling lock screen") + val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null + settingsRepository.updateScheduleSettings(settings.copy( + lockAlbumId = null, + enableChanger = if (homeStillActive) settings.enableChanger else false + )) + } else { + Log.e(TAG, "Error getting lock wallpaper bitmap", error) + throw error + } } } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0c17f21..4e7a46e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -6,8 +6,7 @@ Wallpaper Library Back - Add images - Add folder + Add folder Add album Enter the name of the album Album Name @@ -19,32 +18,17 @@ Currently selected album Agree Welcome - Notifications - 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 - - %d minute - %d minutes - - - %d hour - %d hours - - - %d day - %d days - - %1$s selected + %1$s selected Please read and agree to the following privacy notice to use the app. Privacy Notice - Delete these? - Are you sure you want to delete these wallpapers? - Are you sure you want to delete this? + Are you sure you want to delete this? Delete album? Animation Increase visual appeal @@ -55,8 +39,7 @@ Click here to view our privacy policy Appearance About - wallpapers - + %d wallpaper %d wallpapers @@ -72,8 +55,7 @@ Empty Album This album has no wallpapers. Please add wallpapers to the album before selecting it. OK - %1$s%% - Fill + Fill Fit Stretch Brightness Effect @@ -83,12 +65,7 @@ Show interval sliders Time Interval Blur Effect - Paperize is running - Next wallpaper change: %1$s - Theme - Wallpaper Changer - Enable Wallpaper Changer - Lock + Lock Vignette Effect None Gray Filter @@ -98,8 +75,7 @@ Shuffle Days Hours - Minutes - Change the image brightness + Change the image brightness Add blur to the image Darken the edges of the image Make the colors grayscale @@ -111,8 +87,7 @@ Wallpaper moves with screen scroll Paperize Live Wallpaper Dynamic wallpapers with effects and interactive features - Note: Visual effects (blur, darken, vignette, grayscale) apply to all wallpapers in live mode. - Adaptive Brightness + Adaptive Brightness Adjust brightness based on dark/light mode Randomly shuffle the wallpapers Changing wallpaper… @@ -170,10 +145,8 @@ Mins Total: min - hour - day - + Wallpaper change notifications No wallpapers in album Wallpaper changer has been disabled because the album is empty. @@ -181,17 +154,12 @@ Failed to build wallpaper queue Could not find a valid wallpaper after retries - Failed to load wallpaper image - + Parallax effect may not work with your OEM or launcher. - - %d item - %d items - - + hour hours @@ -216,8 +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. - \nTap \'Open Wallpaper Picker\' below to select Paperize from the list of available live wallpapers. - Open Wallpaper Picker + Open Wallpaper Picker Later 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 04177e6..3f64346 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 @@ -88,68 +88,6 @@ class QueueBuilderTest { assertFalse("Shuffle should produce different orders", allSame) } - // ============================================================ - // Test: needsNormalization - // ============================================================ - - @Test - fun `needsNormalization returns false for empty list`() { - assertFalse(QueueBuilder.needsNormalization(emptyList())) - } - - @Test - fun `needsNormalization returns false for sequential positions`() { - assertFalse(QueueBuilder.needsNormalization(listOf(0, 1, 2, 3))) - } - - @Test - fun `needsNormalization returns true for positions with gaps`() { - assertTrue(QueueBuilder.needsNormalization(listOf(0, 2, 4))) - } - - @Test - fun `needsNormalization returns true for positions not starting at 0`() { - assertTrue(QueueBuilder.needsNormalization(listOf(1, 2, 3))) - } - - @Test - fun `needsNormalization returns false for out of order but contiguous positions`() { - // [2, 0, 1] when sorted becomes [0, 1, 2] - no gaps, so no normalization needed - assertFalse(QueueBuilder.needsNormalization(listOf(2, 0, 1))) - } - - @Test - fun `needsNormalization returns false for single item at 0`() { - assertFalse(QueueBuilder.needsNormalization(listOf(0))) - } - - @Test - fun `needsNormalization returns true for single item not at 0`() { - assertTrue(QueueBuilder.needsNormalization(listOf(5))) - } - - // ============================================================ - // Test: normalizePositions - // ============================================================ - - @Test - fun `normalizePositions creates sequential indices`() { - val normalized = QueueBuilder.normalizePositions(listOf(0, 2, 5)) - assertEquals(listOf(0, 1, 2), normalized) - } - - @Test - fun `normalizePositions handles empty list`() { - val normalized = QueueBuilder.normalizePositions(emptyList()) - assertTrue(normalized.isEmpty()) - } - - @Test - fun `normalizePositions handles already normalized`() { - val normalized = QueueBuilder.normalizePositions(listOf(0, 1, 2)) - assertEquals(listOf(0, 1, 2), normalized) - } - // ============================================================ // Test: mergeWithExistingQueueDeterministic // ============================================================ diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index a1b54e5..02bfedb 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,7 +1,7 @@ [versions] -androidGradlePlugin = "8.13.2" +androidGradlePlugin = "9.1.0" kotlin = "2.3.20" -hilt = "2.58" +hilt = "2.59.2" ksp = "2.3.6" material = "1.13.0" coil = "3.4.0" @@ -10,7 +10,7 @@ coil = "3.4.0" 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", version = "1.10.6" } -androidx-compose-bom = { module = "androidx.compose:compose-bom", version = "2025.12.01" } +androidx-compose-bom = { module = "androidx.compose:compose-bom", version = "2026.03.01" } androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.18.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" } @@ -18,28 +18,28 @@ 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" } -androidx-foundation = { module = "androidx.compose.foundation:foundation", version = "1.10.5" } +androidx-foundation = { module = "androidx.compose.foundation:foundation", version = "1.10.6" } androidx-hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version = "1.3.0" } androidx-hilt-work = { module = "androidx.hilt:hilt-work", version = "1.3.0" } androidx-hilt-compiler = { module = "androidx.hilt:hilt-compiler", version = "1.3.0" } androidx-junit = { module = "androidx.test.ext:junit", version = "1.3.0" } androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version = "2.10.0" } androidx-lifecycle-runtime-ktx = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version = "2.10.0" } -androidx-material = { module = "androidx.compose.material:material", version = "1.10.5" } +androidx-material = { module = "androidx.compose.material:material", version = "1.10.6" } androidx-material-icons-extended = { module = "androidx.compose.material:material-icons-extended", version = "1.7.8" } -androidx-material3 = { module = "androidx.compose.material3:material3", version = "1.5.0-alpha15" } +androidx-material3 = { module = "androidx.compose.material3:material3", version = "1.5.0-alpha16" } androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version = "2.9.7" } androidx-profileinstaller = { module = "androidx.profileinstaller:profileinstaller", version = "1.4.1" } androidx-room-ktx = { module = "androidx.room:room-ktx", version = "2.8.4" } androidx-room-compiler = { module = "androidx.room:room-compiler", version = "2.8.4" } androidx-room-runtime = { module = "androidx.room:room-runtime", version = "2.8.4" } -androidx-ui = { module = "androidx.compose.ui:ui", version = "1.10.5" } -androidx-ui-graphics = { module = "androidx.compose.ui:ui-graphics", version = "1.10.5" } -androidx-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version = "1.10.5" } -androidx-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest", version = "1.10.5" } -androidx-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version = "1.10.5" } -androidx-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version = "1.10.5" } -androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version = "2.11.1" } +androidx-ui = { module = "androidx.compose.ui:ui", version = "1.10.6" } +androidx-ui-graphics = { module = "androidx.compose.ui:ui-graphics", version = "1.10.6" } +androidx-ui-test-junit4 = { module = "androidx.compose.ui:ui-test-junit4", version = "1.10.6" } +androidx-ui-test-manifest = { module = "androidx.compose.ui:ui-test-manifest", version = "1.10.6" } +androidx-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version = "1.10.6" } +androidx-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version = "1.10.6" } +androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version = "2.11.2" } coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" } coil-network-okhttp = { module = "io.coil-kt.coil3:coil-network-okhttp", version.ref = "coil" } coil-gif = { module = "io.coil-kt.coil3:coil-gif", version.ref = "coil" } diff --git a/settings.gradle.kts b/settings.gradle.kts index 3b2655a..417f4b7 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -5,6 +5,9 @@ pluginManagement { gradlePluginPortal() } } +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} @Suppress("UnstableApiUsage") dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)