continue rewrite

This commit is contained in:
Anthonyy232 authored and Anthony La committed 2025-12-21 18:30:23 -08:00
1 parent 391bbb6bc0
commit 318ba07ed5
73 files changed
+2792 -1405

No files matched your search

+3 -7
View File
@@ -7,11 +7,12 @@
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<!-- Features -->
@@ -54,16 +55,11 @@
</intent-filter>
</activity>
<!-- Wallpaper Service -->
<service
android:name=".service.wallpaper.WallpaperChangeService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="Wallpaper changer" />
</service>
android:foregroundServiceType="dataSync" />
<!-- Broadcast Receivers -->
<receiver
@@ -12,6 +12,7 @@ import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.service.worker.AlbumRefreshWorker
import com.anthonyla.paperize.core.util.DataResetManager
import dagger.hilt.android.HiltAndroidApp
import javax.inject.Inject
@@ -30,6 +31,10 @@ class PaperizeApplication : Application(), Configuration.Provider {
override fun onCreate() {
super.onCreate()
// Perform one-time data reset for major version upgrades (e.g., v3 -> v4)
// Must run before any other initialization that accesses DB/preferences
DataResetManager.performResetIfNeeded(this)
// Create notification channel (minSdk is 31, so always supported)
createNotificationChannel()
@@ -10,7 +10,7 @@ package com.anthonyla.paperize.core
*/
enum class WallpaperMediaType {
/**
* Image files: JPEG, PNG, WEBP, AVIF
* Image files: JPEG, PNG, WEBP, AVIF, HEIC, HEIF, BMP, GIF, TIFF
* Supported in both static and live wallpaper modes
*/
IMAGE;
@@ -20,7 +20,14 @@ enum class WallpaperMediaType {
*/
val supportedExtensions: Set<String>
get() = when (this) {
IMAGE -> setOf("jpg", "jpeg", "png", "webp", "avif")
IMAGE -> setOf(
"jpg", "jpeg", "png", "webp", "avif",
"heic", "heif", // HEIC/HEIF - Apple's high efficiency format
"bmp", // Bitmap - legacy but still used
"gif", // GIF - mostly for static images (first frame used)
"tiff", "tif", // TIFF - high quality archival format
"svg" // SVG - vector graphics (rasterized for wallpaper)
)
}
/**
@@ -25,10 +25,12 @@ object Constants {
const val WORK_NAME_HOME = "wallpaper_change_home"
const val WORK_NAME_LOCK = "wallpaper_change_lock"
const val WORK_NAME_BOTH = "wallpaper_change_both"
const val WORK_NAME_LIVE = "wallpaper_change_live"
const val WORK_NAME_REFRESH = "album_refresh"
const val WORK_TAG_HOME = "wallpaper_change_home_tag"
const val WORK_TAG_LOCK = "wallpaper_change_lock_tag"
const val WORK_TAG_BOTH = "wallpaper_change_both_tag"
const val WORK_TAG_LIVE = "wallpaper_change_live_tag"
const val WORK_TAG_REFRESH = "album_refresh_tag"
const val WORK_TAG_IMMEDIATE = "immediate_change"
const val MAX_WORK_RETRY_ATTEMPTS = 3
@@ -41,8 +43,15 @@ object Constants {
const val DEFAULT_DARKEN_PERCENTAGE = 0
const val DEFAULT_VIGNETTE_PERCENTAGE = 0
const val DEFAULT_PARALLAX_INTENSITY = 50
const val DEFAULT_GRAYSCALE_PERCENTAGE = 0
const val MAX_EFFECT_PERCENTAGE = 100
const val SLIDER_EFFECT_STEPS = 99
const val HOME_SCREEN_ENTRY_DELAY_MS = 50L
const val HOME_SCREEN_SLIDE_OFFSET_DIVISOR = 20
const val GL_TEXTURE_SIZE_LIMIT = 4096 // Safe for API 31+ (all support at least 4096)
const val DIALOG_MESSAGE_MAX_LINES = 10
const val MIN_EFFECT_PERCENTAGE = 0
const val FLOW_SUBSCRIPTION_TIMEOUT_MS = 5000L
// Scheduling
const val MIN_INTERVAL_MINUTES = 15
@@ -56,6 +65,11 @@ object Constants {
const val SETTINGS_DEBOUNCE_MS = 2000L // Debounce for settings changes before persisting
const val WALLPAPER_CHANGE_DEBOUNCE_MS = 2000L
const val WALLPAPER_ASPECT_RATIO = 9f / 16f // Standard phone aspect ratio
const val GRID_THUMBNAIL_WIDTH = 300
const val GRID_THUMBNAIL_HEIGHT = 500
const val LIST_THUMBNAIL_SIZE = 150
const val PREVIEW_THUMBNAIL_WIDTH = 600
const val PREVIEW_THUMBNAIL_HEIGHT = 1200
// Time conversion
const val MINUTES_PER_HOUR = 60
@@ -98,6 +112,19 @@ object Constants {
// File types
val SUPPORTED_IMAGE_EXTENSIONS = setOf("jpg", "jpeg", "png", "webp", "avif")
// Renderer
/** Crossfade animation duration in milliseconds - consistent across all refresh rates */
const val CROSSFADE_DURATION_MS = 750f
const val RELOAD_THROTTLE_MS = 250L
const val BLUR_MIN_THRESHOLD = 0.01f
const val PERCENTAGE_DIVISOR = 100f
const val GL_ES_VERSION = 2
const val SURFACE_POLL_INTERVAL_MS = 50L
// Wallpaper loading
const val MAX_WALLPAPER_LOAD_RETRIES = 10
const val MAX_QUEUE_REBUILD_ATTEMPTS = 2
}
/**
@@ -127,6 +154,7 @@ object PreferenceKeys {
const val HOME_DARKEN = "home_darken"
const val HOME_ENABLE_VIGNETTE = "home_enable_vignette"
const val HOME_VIGNETTE = "home_vignette"
const val HOME_ENABLE_GRAYSCALE = "home_enable_grayscale"
const val HOME_GRAYSCALE = "home_grayscale"
// Effects - Lock
@@ -136,6 +164,7 @@ object PreferenceKeys {
const val LOCK_DARKEN = "lock_darken"
const val LOCK_ENABLE_VIGNETTE = "lock_enable_vignette"
const val LOCK_VIGNETTE = "lock_vignette"
const val LOCK_ENABLE_GRAYSCALE = "lock_enable_grayscale"
const val LOCK_GRAYSCALE = "lock_grayscale"
// Interactive Effects - Home (live wallpaper mode only)
@@ -150,20 +179,24 @@ object PreferenceKeys {
// Live Wallpaper Mode Settings
const val LIVE_ALBUM_ID = "live_album_id"
const val LIVE_INTERVAL_MINUTES = "live_interval_minutes"
const val LIVE_ENABLE_BLUR = "live_enable_blur"
const val LIVE_BLUR = "live_blur"
const val LIVE_ENABLE_DARKEN = "live_enable_darken"
const val LIVE_DARKEN = "live_darken"
const val LIVE_ENABLE_VIGNETTE = "live_enable_vignette"
const val LIVE_VIGNETTE = "live_vignette"
const val LIVE_ENABLE_GRAYSCALE = "live_enable_grayscale"
const val LIVE_GRAYSCALE = "live_grayscale"
const val LIVE_ENABLE_DOUBLE_TAP = "live_enable_double_tap"
const val LIVE_ENABLE_CHANGE_ON_SCREEN_ON = "live_enable_change_on_screen_on"
const val LIVE_ENABLE_PARALLAX = "live_enable_parallax"
const val LIVE_PARALLAX_INTENSITY = "live_parallax_intensity"
// Scaling
const val HOME_SCALING_TYPE = "home_scaling_type"
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"
@@ -88,8 +88,9 @@ object AppModule {
database: PaperizeDatabase,
albumDao: AlbumDao,
wallpaperDao: WallpaperDao,
folderDao: FolderDao
): AlbumRepository = AlbumRepositoryImpl(context, database, albumDao, wallpaperDao, folderDao)
folderDao: FolderDao,
wallpaperRepository: dagger.Lazy<WallpaperRepository>
): AlbumRepository = AlbumRepositoryImpl(context, database, albumDao, wallpaperDao, folderDao, wallpaperRepository)
@Provides
@Singleton
@@ -0,0 +1,48 @@
package com.anthonyla.paperize.core.util
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
/**
* Utility for handling battery optimization (Doze mode) exclusion
*/
object BatteryOptimizationUtil {
private const val TAG = "BatteryOptimizationUtil"
/**
* Check if the app is currently excluded from battery optimizations
*/
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
}
/**
* Request the user to exclude the app from battery optimizations
* Opens the system battery optimization settings page
*/
fun requestIgnoreBatteryOptimizations(context: Context) {
try {
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
data = Uri.parse("package:${context.packageName}")
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(intent)
} catch (e: Exception) {
Log.e(TAG, "Error requesting battery optimization exclusion", e)
// Fallback: open general battery optimization settings
try {
val fallbackIntent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
context.startActivity(fallbackIntent)
} catch (e2: Exception) {
Log.e(TAG, "Error opening battery optimization settings", e2)
}
}
}
}
@@ -0,0 +1,130 @@
package com.anthonyla.paperize.core.util
import android.content.Context
import android.util.Log
import java.io.File
/**
* Manages one-time data reset for major version upgrades.
*
* Uses a separate preferences file (version_prefs) to track reset status,
* ensuring the flag survives the data wipe itself.
*/
object DataResetManager {
private const val TAG = "DataResetManager"
/**
* Version tracking preferences - stored separately from main app prefs
* so it survives the data wipe.
*/
private const val VERSION_PREFS_NAME = "version_prefs"
private const val KEY_LAST_RESET_VERSION = "last_reset_version"
/**
* Target reset version - increment this for future major version upgrades
* that require a complete data wipe.
*
* Version 4 = v4.0.0 release (complete app rewrite)
*/
private const val TARGET_RESET_VERSION = 4
/**
* Database and DataStore names to clear (must match Constants)
*/
private const val DATABASE_NAME = "paperize_database"
private const val DATASTORE_NAME = "paperize_preferences.preferences_pb"
/**
* Performs a complete data reset if needed for the current app version.
*
* This should be called at the very start of Application.onCreate(),
* before any other initialization occurs.
*
* @return true if a reset was performed, false otherwise
*/
fun performResetIfNeeded(context: Context): Boolean {
val versionPrefs = context.getSharedPreferences(VERSION_PREFS_NAME, Context.MODE_PRIVATE)
val lastResetVersion = versionPrefs.getInt(KEY_LAST_RESET_VERSION, 0)
if (lastResetVersion >= TARGET_RESET_VERSION) {
Log.d(TAG, "No reset needed (last=$lastResetVersion, target=$TARGET_RESET_VERSION)")
return false
}
Log.w(TAG, "Performing data reset: upgrading from version $lastResetVersion to $TARGET_RESET_VERSION")
try {
// 1. Delete Room database files
deleteDatabase(context)
// 2. Delete DataStore file
deleteDataStore(context)
// 3. Update version after successful wipe
versionPrefs.edit()
.putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION)
.apply()
Log.i(TAG, "Data reset completed successfully")
return true
} catch (e: Exception) {
Log.e(TAG, "Error during data reset", e)
// Still mark as reset to avoid infinite reset loops on corrupted data
versionPrefs.edit()
.putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION)
.apply()
return false
}
}
/**
* Deletes Room database and all related files (WAL, SHM, journal)
*/
private fun deleteDatabase(context: Context) {
val dbPath = context.getDatabasePath(DATABASE_NAME)
val dbDir = dbPath.parentFile
if (dbDir != null && dbDir.exists()) {
// Delete main database file and all related files
val filesToDelete = listOf(
DATABASE_NAME,
"$DATABASE_NAME-wal",
"$DATABASE_NAME-shm",
"$DATABASE_NAME-journal"
)
for (fileName in filesToDelete) {
val file = File(dbDir, fileName)
if (file.exists()) {
val deleted = file.delete()
Log.d(TAG, "Deleted $fileName: $deleted")
}
}
}
// Also use Context.deleteDatabase for good measure
val deleted = context.deleteDatabase(DATABASE_NAME)
Log.d(TAG, "Context.deleteDatabase result: $deleted")
}
/**
* Deletes DataStore preferences file
*/
private fun deleteDataStore(context: Context) {
val dataStoreFile = File(context.filesDir, "datastore/$DATASTORE_NAME")
if (dataStoreFile.exists()) {
val deleted = dataStoreFile.delete()
Log.d(TAG, "Deleted DataStore file: $deleted")
}
// Also delete the datastore directory if empty
val dataStoreDir = File(context.filesDir, "datastore")
if (dataStoreDir.exists() && dataStoreDir.isDirectory) {
val files = dataStoreDir.listFiles()
if (files.isNullOrEmpty()) {
dataStoreDir.delete()
}
}
}
}
@@ -10,10 +10,22 @@ import java.util.UUID
* URI extensions
*/
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
// Basic scheme check - we only handle content URIs
if (scheme != "content") return false
return try {
contentResolver.openInputStream(this)?.use { true } ?: false
// Optimization: Use query to check existence/accessibility without opening the file
// This is significantly faster and less likely to hang on slow cloud providers
contentResolver.query(this, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
cursor.moveToFirst()
} ?: false
} catch (e: Exception) {
false
// Fallback to opening the stream if the provider doesn't support the specific query
try {
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
} catch (e2: Exception) {
false
}
}
}
@@ -0,0 +1,33 @@
package com.anthonyla.paperize.core.util
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import androidx.core.content.ContextCompat
object PermissionUtil {
fun hasNotificationPermission(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
} else {
true
}
}
fun hasStoragePermission(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Environment.isExternalStorageManager()
} else {
// For older versions, we might check READ_EXTERNAL_STORAGE, but the app flow seems to rely on MANAGE for All Files Access
// Stick to the existing logic which uses Environment.isExternalStorageManager()
Environment.isExternalStorageManager()
}
}
}
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.core.util
import com.anthonyla.paperize.core.constants.Constants
import android.app.WallpaperManager
import android.content.Context
@@ -203,7 +204,26 @@ fun retrieveBitmap(
val bitmap = try {
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSampleSize(sampleSize)
val (targetWidth, targetHeight) = when (scaling) {
ScalingType.FILL -> {
// Calculate scale to cover target dimensions
val widthRatio = width.toFloat() / imageSize.width
val heightRatio = height.toFloat() / imageSize.height
val scale = maxOf(widthRatio, heightRatio)
Pair((imageSize.width * scale).fastRoundToInt(), (imageSize.height * scale).fastRoundToInt())
}
ScalingType.FIT -> {
// Calculate scale to fit inside target dimensions
val widthRatio = width.toFloat() / imageSize.width
val heightRatio = height.toFloat() / imageSize.height
val scale = minOf(widthRatio, heightRatio)
Pair((imageSize.width * scale).fastRoundToInt(), (imageSize.height * scale).fastRoundToInt())
}
ScalingType.STRETCH -> Pair(width, height)
ScalingType.NONE -> Pair(imageSize.width, imageSize.height)
}
decoder.setTargetSize(targetWidth, targetHeight)
decoder.isMutableRequired = true
// Use high quality when possible
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
@@ -218,6 +238,9 @@ fun retrieveBitmap(
}
BitmapFactory.decodeStream(inputStream, null, options)
}
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM during retrieveBitmap for $wallpaperUri: $e")
null
}
// Handle EXIF orientation
@@ -243,37 +266,55 @@ private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bi
} catch (e: Exception) {
Log.e(TAG, "Error applying EXIF orientation: $e")
source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM applying EXIF orientation: $e")
source
}
}
/**
* Scale a bitmap using the fit method
* The bitmap will fit into the given dimensions while maintaining aspect ratio
*/
/**
* Scale a bitmap using the fit method
* The bitmap will fit into the given dimensions while maintaining aspect ratio
*/
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
if (source.width == width && source.height == height) {
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
Log.w(TAG, "Invalid dimensions for fitBitmap: source=${source.width}x${source.height}, target=${width}x${height}")
return source
}
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
Log.w(TAG, "Invalid dimensions for fitBitmap, returning source.")
if (source.width == width && source.height == height) {
return source
}
return try {
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val scale = width.toFloat() / source.width
val scaleX = width.toFloat() / source.width
val scaleY = height.toFloat() / source.height
// Use the smaller scale factor to ensure the entire image fits within the target dimensions
val scale = minOf(scaleX, scaleY)
val scaledSourceWidth = source.width * scale
val scaledSourceHeight = source.height * scale
val xOffset = (width - scaledSourceWidth) / 2f
val yOffset = (height - scaledSourceHeight) / 2f
val matrix = Matrix().apply {
postScale(scale, scale)
postTranslate(0f, yOffset)
postTranslate(xOffset, yOffset)
}
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
bitmap
} catch (e: Exception) {
Log.e(TAG, "Error fitting bitmap: $e")
source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM fitting bitmap: $e")
source
}
}
@@ -281,6 +322,10 @@ fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
* Scale a bitmap using the fill method (crop to fill dimensions)
*/
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
Log.w(TAG, "Invalid dimensions for fillBitmap: source=${source.width}x${source.height}, target=${width}x${height}")
return source
}
if (source.width == width && source.height == height) {
return source
}
@@ -313,6 +358,9 @@ fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
} catch (e: Exception) {
Log.e(TAG, "Error filling bitmap: $e")
source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM filling bitmap: $e")
source
}
}
@@ -320,6 +368,10 @@ fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
* Stretch the bitmap to fit the given dimensions
*/
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
Log.w(TAG, "Invalid dimensions for stretchBitmap: source=${source.width}x${source.height}, target=${width}x${height}")
return source
}
if (source.width == width && source.height == height) {
return source
}
@@ -337,21 +389,26 @@ fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
} catch (e: Exception) {
Log.e(TAG, "Error stretching bitmap: $e")
source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM stretching bitmap: $e")
source
}
}
/**
* Darken the bitmap by a certain percentage
* @param brightnessToRetainPercent 0-100 (0 is darkest, 100 is original)
* @param darkenPercent 0-100 (0 is original brightness, 100 is completely dark/black)
*/
fun darkenBitmap(source: Bitmap, brightnessToRetainPercent: Int): Bitmap {
fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap {
if (!source.isMutable) {
Log.w(TAG, "darkenBitmap received an immutable bitmap. Returning a copy.")
Log.w(TAG, "darkenBitmap received an immutable bitmap. Creating a mutable copy.")
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
return darkenBitmap(mutableCopy, brightnessToRetainPercent)
source.recycle()
return darkenBitmap(mutableCopy, darkenPercent)
}
val targetBrightnessFactor = brightnessToRetainPercent.coerceIn(0, 100) / 100f
// Convert darkenPercent to brightness factor (invert)
val targetBrightnessFactor = (100 - darkenPercent.coerceIn(0, 100)) / 100f
if (targetBrightnessFactor >= 1.0f) {
return source
}
@@ -375,7 +432,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
return source
}
val maxBlurRadius = 25.0f
val maxBlurRadius = Constants.MAX_BLUR_RADIUS
val radius = (clampedPercent / 100.0f) * maxBlurRadius
val imageReader = ImageReader.newInstance(
@@ -387,7 +444,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
val renderNode = RenderNode("BlurEffect")
val hardwareRenderer = HardwareRenderer()
var resultBitmap: Bitmap?
var resultBitmap: Bitmap? = null
try {
hardwareRenderer.setSurface(imageReader.surface)
hardwareRenderer.setContentRoot(renderNode)
@@ -418,16 +475,23 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, true)
?: throw IllegalStateException("Failed to copy hardware bitmap to software bitmap")
hardwareBitmap.recycle()
hardwareBuffer.close()
image.close()
} catch (e: Exception) {
Log.e(TAG, "Error blurring bitmap: $e")
return source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM blurring bitmap: $e")
return source
} finally {
hardwareRenderer.destroy()
renderNode.discardDisplayList()
imageReader.close()
}
return resultBitmap
return resultBitmap ?: throw IllegalStateException("Blur operation failed - resultBitmap is null")
}
/**
@@ -444,24 +508,25 @@ fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
if (percent <= 0) return source
if (!source.isMutable) {
Log.w(TAG, "vignetteBitmap received an immutable bitmap. Returning a copy.")
Log.w(TAG, "vignetteBitmap received an immutable bitmap. Creating a mutable copy.")
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
source.recycle()
return vignetteBitmap(mutableCopy, percent)
}
return try {
val canvas = Canvas(source)
val dim = if (source.width < source.height) source.height else source.width
val rad = (dim * (1 - (percent.coerceIn(0, 100) / 150f))).coerceAtLeast(0.1f)
val rad = (dim * (1 - (percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))).coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
val centerX = source.width / 2f
val centerY = source.height / 2f
val colors = intArrayOf(
Color.TRANSPARENT,
Color.argb((0.1f * 255).toInt(), 0, 0, 0),
Color.argb((0.8f * 255).toInt(), 0, 0, 0)
Color.argb((Constants.VIGNETTE_INNER_ALPHA * 255).toInt(), 0, 0, 0),
Color.argb((Constants.VIGNETTE_OUTER_ALPHA * 255).toInt(), 0, 0, 0)
)
val pos = floatArrayOf(0f, 0.7f, 1f)
val pos = Constants.VIGNETTE_GRADIENT_POSITIONS
val vignettePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
shader = RadialGradient(
@@ -474,6 +539,9 @@ fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
} catch (e: Exception) {
Log.e(TAG, "Error applying vignette: $e")
source
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM applying vignette: $e")
source
}
}
@@ -484,8 +552,9 @@ fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
if (percent <= 0) return source
if (!source.isMutable) {
Log.w(TAG, "grayscaleBitmap received an immutable bitmap. Returning a copy.")
Log.w(TAG, "grayscaleBitmap received an immutable bitmap. Creating a mutable copy.")
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
source.recycle()
return grayscaleBitmap(mutableCopy, percent)
}
@@ -505,7 +574,7 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
*/
fun calculateBitmapBrightness(bitmap: Bitmap): Float {
// Sample pixels to estimate brightness (sampling for performance)
val sampleSize = 10
val sampleSize = Constants.BRIGHTNESS_SAMPLE_SIZE
var totalLuminance = 0.0
var pixelCount = 0
@@ -517,7 +586,7 @@ fun calculateBitmapBrightness(bitmap: Bitmap): Float {
val b = Color.blue(pixel) / 255.0
// Calculate relative luminance using ITU-R BT.709 standard
val luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
val luminance = Constants.LUMINANCE_RED * r + Constants.LUMINANCE_GREEN * g + Constants.LUMINANCE_BLUE * b
totalLuminance += luminance
pixelCount++
}
@@ -539,6 +608,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
if (!source.isMutable) {
Log.w(TAG, "adjustBitmapBrightness received an immutable bitmap. Returning a copy.")
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
source.recycle() // Recycle source to prevent memory leak
return adjustBitmapBrightness(mutableCopy, brightnessFactor)
}
@@ -560,17 +630,52 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
* @param source Source bitmap
* @return Adjusted bitmap (or original if no adjustment needed)
*/
/**
* Get adaptive brightness multiplier factor based on system dark/light mode
*
* @param context Application context
* @param brightness Current image brightness (0.0 to 1.0)
* @return Multiplier factor to apply to colors
*/
fun getAdaptiveBrightnessMultiplier(context: Context, brightness: Float): Float {
val isDarkMode = (context.resources.configuration.uiMode and
android.content.res.Configuration.UI_MODE_NIGHT_MASK) == android.content.res.Configuration.UI_MODE_NIGHT_YES
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
// Avoid issues with very dark items
if (brightness < 0.01f) return 1.0f
return when {
// In dark mode with very bright image: darken it
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
// In light mode with very dark image: brighten it
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
// No adjustment needed
else -> 1.0f
}
}
fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
val isDarkMode = (context.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
val currentBrightness = calculateBitmapBrightness(source)
// Thresholds from WallYou
val lightBrightnessMin = 0.8f
val darkBrightnessMax = 0.3f
val targetBrightnessDark = 0.7f
val targetBrightnessLight = 0.4f
// Thresholds from WallYou
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
// Avoid division by zero or very small numbers
if (currentBrightness < 0.01f) {
Log.d(TAG, "Image is too dark for adaptive brightness adjustment (brightness: $currentBrightness)")
return source
}
return when {
// In dark mode with very bright image: darken it
@@ -622,27 +727,28 @@ fun processBitmap(
grayscalePercent: Int = 0
): Bitmap {
var result = source
var previous: Bitmap
// 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) {
previous = result
result = darkenBitmap(result, 100 - darkenPercent)
// Darken modifies in-place for mutable bitmaps, no need to recycle
result = darkenBitmap(result, darkenPercent)
}
// Blur always creates a new bitmap
if (enableBlur && blurPercent > 0) {
previous = result
val previous = result
result = blurBitmap(result, blurPercent)
// Blur always creates a new bitmap, recycle the previous one if different
// Recycle the previous one if different from source
if (result !== previous && previous !== source) {
previous.recycle()
}
}
if (enableVignette && vignettePercent > 0) {
previous = result
val previous = result
result = vignetteBitmap(result, vignettePercent)
// Vignette modifies in-place for mutable bitmaps, may create copy for immutable
if (result !== previous && previous !== source) {
@@ -651,7 +757,7 @@ fun processBitmap(
}
if (enableGrayscale && grayscalePercent > 0) {
previous = result
val previous = result
result = grayscaleBitmap(result, grayscalePercent)
// Grayscale modifies in-place for mutable bitmaps, may create copy for immutable
if (result !== previous && previous !== source) {
@@ -717,6 +823,7 @@ fun isPaperizeLiveWallpaperActive(context: Context): Boolean {
return try {
// If we are checking from within the service itself (e.g. preview mode), we are active
if (context is com.anthonyla.paperize.service.livewallpaper.PaperizeLiveWallpaperService) {
Log.d(TAG, "isPaperizeLiveWallpaperActive: called from service context, returning true")
return true
}
@@ -725,6 +832,7 @@ fun isPaperizeLiveWallpaperActive(context: Context): Boolean {
// If wallpaperInfo is null, user has a static wallpaper (not a live wallpaper)
if (wallpaperInfo == null) {
Log.d(TAG, "isPaperizeLiveWallpaperActive: wallpaperInfo is null (static wallpaper), returning false")
return false
}
@@ -735,9 +843,10 @@ fun isPaperizeLiveWallpaperActive(context: Context): Boolean {
)
val isPaperize = wallpaperInfo.component == expectedComponent
Log.d(TAG, "isPaperizeLiveWallpaperActive: current=${wallpaperInfo.component}, expected=$expectedComponent, match=$isPaperize")
isPaperize
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error checking live wallpaper status", e)
Log.e(TAG, "Error checking live wallpaper status", e)
false
}
}
@@ -8,6 +8,7 @@ import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
import kotlinx.coroutines.flow.Flow
@@ -16,6 +17,24 @@ import kotlinx.coroutines.flow.Flow
*/
@Dao
interface AlbumDao {
/**
* Get all album summaries (lightweight metadata + counts)
* Efficiently handles large libraries by avoiding loading all wallpaper objects
*/
@Query("""
SELECT
a.id,
a.name,
a.coverUri,
a.createdAt,
a.modifiedAt,
(SELECT COUNT(*) FROM wallpapers w WHERE w.albumId = a.id) as wallpaperCount,
(SELECT COUNT(*) FROM folders f WHERE f.albumId = a.id) as folderCount
FROM albums a
ORDER BY a.modifiedAt DESC
""")
fun getAlbumSummaries(): Flow<List<AlbumSummaryEntity>>
/**
* Get all albums with their wallpapers and folders
*/
@@ -32,6 +32,12 @@ interface WallpaperDao {
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
suspend fun getWallpapersByAlbumSync(albumId: String): List<WallpaperEntity>
/**
* Get wallpapers for an album (paginated for memory-intensive operations)
*/
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC LIMIT :limit OFFSET :offset")
suspend fun getWallpapersByAlbumPaged(albumId: String, limit: Int, offset: Int): List<WallpaperEntity>
/**
* Get direct wallpapers for an album (synchronous for transactions)
*/
@@ -109,4 +115,10 @@ interface WallpaperDao {
*/
@Query("DELETE FROM wallpapers WHERE uri IN (:uris)")
suspend fun deleteWallpapersByUris(uris: List<String>)
/**
* Get total wallpaper count for an album
*/
@Query("SELECT COUNT(*) FROM wallpapers WHERE albumId = :albumId")
suspend fun getWallpaperCountByAlbum(albumId: String): Int
}
@@ -37,11 +37,8 @@ interface WallpaperQueueDao {
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? {
val wallpaper = getNextWallpaperInQueue(albumId, screenType)
if (wallpaper != null) {
// Delete the first item
deleteFirstQueueItem(albumId, screenType)
// Normalize positions to fix any gaps from CASCADE deletes
// This ensures positions are always 0, 1, 2, 3... without gaps
normalizeQueuePositions(albumId, screenType)
// Delete specifically the item we just retrieved to ensure atomicity
deleteQueueItem(albumId, screenType, wallpaper.id)
}
return wallpaper
}
@@ -58,6 +55,18 @@ interface WallpaperQueueDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertQueueItems(items: List<WallpaperQueueEntity>)
@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)
@Query("""
DELETE FROM wallpaper_queue
WHERE albumId = :albumId AND screenType = :screenType
@@ -0,0 +1,14 @@
package com.anthonyla.paperize.data.database.entities
/**
* Entity for holding lightweight album summary query results
*/
data class AlbumSummaryEntity(
val id: String,
val name: String,
val coverUri: String?,
val wallpaperCount: Int,
val folderCount: Int,
val createdAt: Long,
val modifiedAt: Long
)
@@ -127,8 +127,11 @@ class PreferencesManager @Inject constructor(
?: Constants.DEFAULT_INTERVAL_MINUTES,
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
?: Constants.DEFAULT_INTERVAL_MINUTES,
liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
?: Constants.DEFAULT_INTERVAL_MINUTES,
homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
homeEffects = WallpaperEffects(
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
@@ -136,7 +139,8 @@ class PreferencesManager @Inject constructor(
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: false,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
@@ -148,11 +152,26 @@ class PreferencesManager @Inject constructor(
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: false,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
),
liveEffects = WallpaperEffects(
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] ?: false,
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] ?: 0,
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] ?: false,
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
enableChangeOnScreenOn = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
),
adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
)
}
@@ -171,8 +190,11 @@ class PreferencesManager @Inject constructor(
?: Constants.DEFAULT_INTERVAL_MINUTES,
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
?: Constants.DEFAULT_INTERVAL_MINUTES,
liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
?: Constants.DEFAULT_INTERVAL_MINUTES,
homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
homeEffects = WallpaperEffects(
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
@@ -180,7 +202,8 @@ class PreferencesManager @Inject constructor(
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: false,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
@@ -192,7 +215,8 @@ class PreferencesManager @Inject constructor(
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: false,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
@@ -204,8 +228,10 @@ class PreferencesManager @Inject constructor(
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: false,
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
enableChangeOnScreenOn = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
),
@@ -237,8 +263,10 @@ class PreferencesManager @Inject constructor(
}
prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)] = settings.homeIntervalMinutes
prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)] = settings.lockIntervalMinutes
prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)] = settings.liveIntervalMinutes
prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)] = settings.homeScalingType.name
prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)] = settings.lockScalingType.name
prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)] = settings.liveScalingType.name
// Home effects
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] = settings.homeEffects.enableBlur
@@ -247,7 +275,8 @@ class PreferencesManager @Inject constructor(
prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] = settings.homeEffects.darkenPercentage
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] = settings.homeEffects.enableVignette
prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] = settings.homeEffects.vignettePercentage
prefs[booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] = settings.homeEffects.enableGrayscale
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] = settings.homeEffects.enableGrayscale
prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] = settings.homeEffects.grayscalePercentage
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] = settings.homeEffects.enableDoubleTap
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] = settings.homeEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] = settings.homeEffects.parallaxIntensity
@@ -259,14 +288,12 @@ class PreferencesManager @Inject constructor(
prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] = settings.lockEffects.darkenPercentage
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] = settings.lockEffects.enableVignette
prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] = settings.lockEffects.vignettePercentage
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] = settings.lockEffects.enableGrayscale
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] = settings.lockEffects.enableGrayscale
prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] = settings.lockEffects.grayscalePercentage
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] = settings.lockEffects.enableDoubleTap
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] = settings.lockEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] = settings.lockEffects.parallaxIntensity
// Note: Don't clear live effects here - they're written below and clearing them causes data loss
// Live effects are now written atomically below
// Live effects
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] = settings.liveEffects.enableBlur
prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] = settings.liveEffects.blurPercentage
@@ -274,8 +301,10 @@ class PreferencesManager @Inject constructor(
prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] = settings.liveEffects.darkenPercentage
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] = settings.liveEffects.enableVignette
prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] = settings.liveEffects.vignettePercentage
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] = settings.liveEffects.enableGrayscale
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] = settings.liveEffects.enableGrayscale
prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] = settings.liveEffects.grayscalePercentage
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] = settings.liveEffects.enableDoubleTap
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON)] = settings.liveEffects.enableChangeOnScreenOn
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] = settings.liveEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] = settings.liveEffects.parallaxIntensity
@@ -337,6 +366,7 @@ class PreferencesManager @Inject constructor(
dataStore.edit { prefs ->
val homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)]
val lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)]
val liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)]
// Clear home album if it matches
if (homeAlbumId == albumId) {
@@ -349,6 +379,12 @@ class PreferencesManager @Inject constructor(
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
wasCleared = true
}
// Clear live album if it matches
if (liveAlbumId == albumId) {
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
wasCleared = true
}
}
return wasCleared
}
@@ -456,6 +492,7 @@ class PreferencesManager @Inject constructor(
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES))
// Clear home effects
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR))
@@ -464,7 +501,8 @@ class PreferencesManager @Inject constructor(
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_DARKEN))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_VIGNETTE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY))
@@ -476,7 +514,8 @@ class PreferencesManager @Inject constructor(
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_DARKEN))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY))
@@ -488,14 +527,17 @@ class PreferencesManager @Inject constructor(
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_DARKEN))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY))
// Clear scaling
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE))
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE))
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE))
// Clear current wallpapers
prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID))
@@ -30,14 +30,13 @@ fun Album.toEntity(): AlbumEntity = AlbumEntity(
)
fun AlbumWithDetails.toDomainModel(): Album {
val domainWallpapers = wallpapers
.filter { it.folderId == null } // Only direct wallpapers
.map { it.toDomainModel() }
// Optimization: Group wallpapers by folderId once to avoid repeated filtering
val wallpapersByFolder = wallpapers.groupBy { it.folderId }
val domainWallpapers = wallpapersByFolder[null]?.map { it.toDomainModel() } ?: emptyList()
val domainFolders = folders.map { folderEntity ->
val folderWallpapers = wallpapers
.filter { it.folderId == folderEntity.id }
.map { it.toDomainModel() }
val folderWallpapers = wallpapersByFolder[folderEntity.id]?.map { it.toDomainModel() } ?: emptyList()
folderEntity.toDomainModel(folderWallpapers)
}
@@ -50,3 +49,17 @@ fun AlbumWithDetails.toDomainModel(): Album {
fun List<AlbumEntity>.toDomainModels(): List<Album> = map { it.toDomainModel() }
fun List<AlbumWithDetails>.toDomainModelsFromRelations(): List<Album> = map { it.toDomainModel() }
fun com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity.toDomainModel(): com.anthonyla.paperize.domain.model.AlbumSummary =
com.anthonyla.paperize.domain.model.AlbumSummary(
id = id,
name = name,
coverUri = coverUri,
wallpaperCount = wallpaperCount,
folderCount = folderCount,
createdAt = createdAt,
modifiedAt = modifiedAt
)
fun List<com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity>.toDomainModelsFromSummaries(): List<com.anthonyla.paperize.domain.model.AlbumSummary> =
map { it.toDomainModel() }
@@ -13,9 +13,11 @@ import com.anthonyla.paperize.data.database.dao.WallpaperDao
import com.anthonyla.paperize.data.database.entities.AlbumEntity
import com.anthonyla.paperize.data.mapper.toDomainModel
import com.anthonyla.paperize.data.mapper.toDomainModelsFromRelations
import com.anthonyla.paperize.data.mapper.toDomainModelsFromSummaries
import com.anthonyla.paperize.data.mapper.toEntities
import com.anthonyla.paperize.data.mapper.toEntity
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.AlbumRepository
@@ -37,9 +39,13 @@ class AlbumRepositoryImpl @Inject constructor(
private val database: PaperizeDatabase,
private val albumDao: AlbumDao,
private val wallpaperDao: WallpaperDao,
private val folderDao: FolderDao
private val folderDao: FolderDao,
private val wallpaperRepository: dagger.Lazy<com.anthonyla.paperize.domain.repository.WallpaperRepository>
) : AlbumRepository {
override fun getAlbumSummaries(): Flow<List<AlbumSummary>> =
albumDao.getAlbumSummaries().map { it.toDomainModelsFromSummaries() }
override fun getAllAlbums(): Flow<List<Album>> =
albumDao.getAllAlbumsWithDetails().map { it.toDomainModelsFromRelations() }
@@ -79,7 +85,10 @@ class AlbumRepositoryImpl @Inject constructor(
override suspend fun deleteAlbum(albumId: String): Result<Unit> {
return try {
albumDao.deleteAlbumById(albumId)
database.withTransaction {
albumDao.deleteAlbumById(albumId)
wallpaperRepository.get().clearQueuesForAlbum(albumId)
}
Result.Success(Unit)
} catch (e: Exception) {
Result.Error(e)
@@ -226,7 +235,10 @@ class AlbumRepositoryImpl @Inject constructor(
override suspend fun deleteAllAlbums(): Result<Unit> {
return try {
albumDao.deleteAllAlbums()
database.withTransaction {
albumDao.deleteAllAlbums()
wallpaperRepository.get().clearAllQueues()
}
Result.Success(Unit)
} catch (e: Exception) {
Result.Error(e)
@@ -116,16 +116,23 @@ class WallpaperRepositoryImpl @Inject constructor(
override suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result<Int> {
return try {
val wallpapers = wallpaperDao.getWallpapersByAlbum(albumId).first()
val invalidUris = wallpapers
.filter { !Uri.parse(it.uri).isValid(contentResolver) }
.map { it.uri }
val totalCount = wallpaperDao.getWallpaperCountByAlbum(albumId)
var totalRemoved = 0
val batchSize = 100 // Process in smaller batches to avoid memory spikes
if (invalidUris.isNotEmpty()) {
wallpaperDao.deleteWallpapersByUris(invalidUris)
for (offset in 0 until totalCount step batchSize) {
val wallpapers = wallpaperDao.getWallpapersByAlbumPaged(albumId, batchSize, offset)
val invalidUris = wallpapers
.filter { !Uri.parse(it.uri).isValid(contentResolver) }
.map { it.uri }
if (invalidUris.isNotEmpty()) {
wallpaperDao.deleteWallpapersByUris(invalidUris)
totalRemoved += invalidUris.size
}
}
Result.Success(invalidUris.size)
Result.Success(totalRemoved)
} catch (e: Exception) {
Result.Error(e)
}
@@ -212,6 +219,13 @@ class WallpaperRepositoryImpl @Inject constructor(
override suspend fun clearQueuesForAlbum(albumId: String): Result<Unit> {
return try {
wallpaperQueueDao.clearAllQueues(albumId)
// Prune mutexes for this album to prevent memory leak
// Keys are either albumId (shuffled) or $albumId:$screenType (sequential)
queueRebuildMutexes.keys.filter { it.startsWith(albumId) }.forEach {
queueRebuildMutexes.remove(it)
}
Result.Success(Unit)
} catch (e: Exception) {
Result.Error(e)
@@ -220,11 +234,12 @@ class WallpaperRepositoryImpl @Inject constructor(
override suspend fun normalizeAllQueuesForAlbum(albumId: String): Result<Unit> {
return try {
// Normalize both HOME and LOCK queues for this album
// Normalize all queue types for this album
// This fixes gaps in queue positions caused by CASCADE deletes
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.HOME)
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LOCK)
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LIVE)
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.BOTH)
Result.Success(Unit)
} catch (e: Exception) {
Result.Error(e)
@@ -236,27 +251,8 @@ class WallpaperRepositoryImpl @Inject constructor(
val documentFile = DocumentFile.fromTreeUri(context, folderUri)
?: return Result.Error(Exception("Invalid folder URI"))
val wallpapers = documentFile.listFiles()
.filter { it.isFile && it.name?.let { name -> isImageFile(name) } == true }
.mapNotNull { file ->
try {
val uri = file.uri.toString()
val fileName = file.name ?: return@mapNotNull null
val dateModified = file.lastModified()
Wallpaper(
id = generateId(),
albumId = "", // Will be set when adding to album
folderId = null, // Will be set when adding to folder
uri = uri,
fileName = fileName,
dateModified = dateModified,
sourceType = WallpaperSourceType.FOLDER
)
} catch (e: Exception) {
null
}
}
val wallpapers = mutableListOf<Wallpaper>()
scanDirectoryRecursive(documentFile, wallpapers)
Result.Success(wallpapers)
} catch (e: Exception) {
@@ -264,8 +260,39 @@ class WallpaperRepositoryImpl @Inject constructor(
}
}
private fun scanDirectoryRecursive(directory: DocumentFile, result: MutableList<Wallpaper>) {
directory.listFiles().forEach { file ->
if (file.isDirectory) {
scanDirectoryRecursive(file, result)
} else if (file.isFile && file.name?.let { name -> isImageFile(name) } == true) {
try {
val uri = file.uri.toString()
val fileName = file.name ?: return@forEach
val dateModified = file.lastModified()
result.add(
Wallpaper(
id = generateId(),
albumId = "",
folderId = null,
uri = uri,
fileName = fileName,
dateModified = dateModified,
sourceType = WallpaperSourceType.FOLDER
)
)
} catch (e: Exception) {
// Skip failed items
}
}
}
}
private fun isImageFile(fileName: String): Boolean {
val extension = fileName.substringAfterLast('.', "").lowercase()
return extension in Constants.SUPPORTED_IMAGE_EXTENSIONS
}
override suspend fun isWallpaperInAlbum(albumId: String, uri: String): Boolean =
wallpaperDao.getWallpaperByUri(uri)?.let { it.albumId == albumId } ?: false
}
@@ -0,0 +1,34 @@
package com.anthonyla.paperize.domain.model
/**
* Lightweight summary of an Album for list displays.
* Prevents loading potentially thousands of Wallpaper objects into memory
* when just displaying a list of albums.
*/
data class AlbumSummary(
val id: String,
val name: String,
val coverUri: String?,
val wallpaperCount: Int,
val folderCount: Int,
val createdAt: Long,
val modifiedAt: Long
) {
/**
* Check if album is empty without a full object load
*/
val isEmpty: Boolean
get() = wallpaperCount == 0
companion object {
fun empty(id: String = "", name: String = "") = AlbumSummary(
id = id,
name = name,
coverUri = null,
wallpaperCount = 0,
folderCount = 0,
createdAt = System.currentTimeMillis(),
modifiedAt = System.currentTimeMillis()
)
}
}
@@ -16,11 +16,13 @@ data class ScheduleSettings(
val lockAlbumId: String? = null,
val homeIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
val lockIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
val liveIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
val homeScalingType: ScalingType = ScalingType.FILL,
val lockScalingType: ScalingType = ScalingType.FILL,
val homeEffects: WallpaperEffects = WallpaperEffects.none(),
val lockEffects: WallpaperEffects = WallpaperEffects.none(),
val liveAlbumId: String? = null,
val liveScalingType: ScalingType = ScalingType.FILL,
val liveEffects: WallpaperEffects = WallpaperEffects.none(),
val adaptiveBrightness: Boolean = false
) {
@@ -30,6 +32,7 @@ data class ScheduleSettings(
fun validate(): ScheduleSettings = copy(
homeIntervalMinutes = homeIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
lockIntervalMinutes = lockIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
liveIntervalMinutes = liveIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
homeEffects = homeEffects.validate(),
lockEffects = lockEffects.validate(),
liveEffects = liveEffects.validate()
@@ -51,7 +54,8 @@ data class ScheduleSettings(
lockEnabled != other.lockEnabled ||
homeIntervalMinutes != other.homeIntervalMinutes ||
lockIntervalMinutes != other.lockIntervalMinutes ||
separateSchedules != other.separateSchedules
separateSchedules != other.separateSchedules ||
liveIntervalMinutes != other.liveIntervalMinutes
}
/**
@@ -66,6 +70,7 @@ data class ScheduleSettings(
homeEffects != other.homeEffects ||
lockEffects != other.lockEffects ||
liveEffects != other.liveEffects ||
liveScalingType != other.liveScalingType ||
adaptiveBrightness != other.adaptiveBrightness
}
@@ -17,9 +17,11 @@ data class WallpaperEffects(
val enableVignette: Boolean = false,
val vignettePercentage: Int = Constants.DEFAULT_VIGNETTE_PERCENTAGE,
val enableGrayscale: Boolean = false,
val grayscalePercentage: Int = Constants.DEFAULT_GRAYSCALE_PERCENTAGE,
// Interactive effects (live wallpaper mode only)
val enableDoubleTap: Boolean = false,
val enableChangeOnScreenOn: Boolean = false,
val enableParallax: Boolean = false,
val parallaxIntensity: Int = Constants.DEFAULT_PARALLAX_INTENSITY
) {
@@ -28,17 +30,18 @@ data class WallpaperEffects(
*/
val hasEffects: Boolean
get() = (enableBlur && blurPercentage > 0) ||
(enableDarken && darkenPercentage != 0) ||
(enableDarken && darkenPercentage > 0) ||
(enableVignette && vignettePercentage > 0) ||
enableGrayscale
(enableGrayscale && grayscalePercentage > 0)
/**
* Validate effect percentages
*/
fun validate(): WallpaperEffects = copy(
darkenPercentage = darkenPercentage.coerceIn(-100, 100),
darkenPercentage = darkenPercentage.coerceIn(0, 100),
blurPercentage = blurPercentage.coerceIn(0, 100),
vignettePercentage = vignettePercentage.coerceIn(0, 100),
grayscalePercentage = grayscalePercentage.coerceIn(0, 100),
parallaxIntensity = parallaxIntensity.coerceIn(0, 100)
)
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.domain.repository
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.model.Folder
import kotlinx.coroutines.flow.Flow
@@ -12,6 +13,11 @@ import kotlinx.coroutines.flow.Flow
* Clean interface following repository pattern - implementation in data layer
*/
interface AlbumRepository {
/**
* Get all album summaries (lightweight metadata + counts)
*/
fun getAlbumSummaries(): Flow<List<AlbumSummary>>
/**
* Get all albums with their wallpapers and folders
*/
@@ -108,4 +108,10 @@ interface WallpaperRepository {
* Scan folder for wallpapers
*/
suspend fun scanFolderForWallpapers(folderUri: Uri): Result<List<Wallpaper>>
/**
* Check if a wallpaper with the given URI already exists in the album
* Optimized for checking duplicates during folder sync
*/
suspend fun isWallpaperInAlbum(albumId: String, uri: String): Boolean
}
@@ -12,15 +12,14 @@ 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.core.util.scaleBitmap
import com.anthonyla.paperize.domain.model.Wallpaper
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.WallpaperRepository
import com.anthonyla.paperize.core.constants.Constants
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
// Constants
private const val MAX_VALIDATION_RETRIES = 10
/**
* Use case to change wallpaper
@@ -52,117 +51,103 @@ class ChangeWallpaperUseCase @Inject constructor(
}
}
// Atomically get and dequeue wallpaper, skipping invalid ones
// This prevents race conditions when multiple wallpaper changes happen simultaneously
var wallpaper: Wallpaper? = null
var maxRetries = MAX_VALIDATION_RETRIES // Prevent infinite loop
// Atomically get and dequeue wallpaper, skipping invalid or corrupted ones
var finalBitmap: Bitmap? = null
var maxRetries = Constants.MAX_WALLPAPER_LOAD_RETRIES
var queueRebuildAttempts = 0
while (wallpaper == null && maxRetries > 0) {
// Atomically get and remove from queue in a single transaction
// Get screen dimensions once for the retry loop
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
}
while (finalBitmap == null && maxRetries > 0) {
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
// If queue is empty (candidate is null), try rebuilding queue
if (candidate == null) {
queueRebuildAttempts++
// Allow up to 2 rebuild attempts
// First attempt: queue ran out due to invalid wallpapers being removed
// Second attempt: confirms album truly has no valid wallpapers
if (queueRebuildAttempts > 2) {
return Result.Error(Exception(context.getString(R.string.no_wallpapers_in_album)))
}
// Try rebuilding queue
val rebuildResult = wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
if (rebuildResult is Result.Error) {
return Result.Error(Exception(context.getString(R.string.error_failed_to_build_queue)))
}
// Continue loop to try getting wallpaper from rebuilt queue
continue
}
// Validate URI
val uri = candidate.uri.toUri()
if (uri.isValid(context.contentResolver)) {
wallpaper = candidate
// 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
var processedBitmap = processBitmap(
context = context,
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--
}
} catch (e: Exception) {
// Error during processing, skip this wallpaper
wallpaperRepository.deleteWallpaper(candidate.id)
maxRetries--
}
} else {
// Remove invalid wallpaper entity (already dequeued)
// URI invalid
wallpaperRepository.deleteWallpaper(candidate.id)
maxRetries--
}
}
if (wallpaper == null) {
if (finalBitmap == null) {
return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
}
val uri = wallpaper.uri.toUri()
// Get effects and scaling from settings
val effects = if (screenType == ScreenType.HOME || screenType == ScreenType.BOTH) {
settings.homeEffects
} else {
settings.lockEffects
}
val scaling = if (screenType == ScreenType.HOME || screenType == ScreenType.BOTH) {
settings.homeScalingType
} else {
settings.lockScalingType
}
// Get screen dimensions
val screenSize = getDeviceScreenSize(context)
// Load bitmap
val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling)
?: return Result.Error(Exception(context.getString(R.string.error_failed_to_load_bitmap)))
// Apply scaling
val scaledBitmap = scaleBitmap(bitmap, screenSize.width, screenSize.height, scaling)
// Recycle original bitmap if scaling created a new one
if (scaledBitmap !== bitmap) {
bitmap.recycle()
}
// Apply effects with proper enable flags
var processedBitmap = processBitmap(
context = context,
source = scaledBitmap,
enableDarken = effects.enableDarken,
darkenPercent = effects.darkenPercentage,
enableBlur = effects.enableBlur,
blurPercent = effects.blurPercentage,
enableVignette = effects.enableVignette,
vignettePercent = effects.vignettePercentage,
enableGrayscale = effects.enableGrayscale,
grayscalePercent = if (effects.enableGrayscale) 100 else 0
)
// Recycle scaled bitmap if effects created a new one
if (processedBitmap !== scaledBitmap) {
scaledBitmap.recycle()
}
// Apply adaptive brightness if enabled
if (settings.adaptiveBrightness) {
val previousBitmap = processedBitmap
processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
// Recycle previous if adaptive brightness created a new bitmap
if (processedBitmap !== previousBitmap) {
previousBitmap.recycle()
}
}
// Check if queue needs refilling (wallpaper was already dequeued atomically)
val queueSize = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
if (queueSize == null) {
// Queue is now empty, rebuild it
// Check if queue needs refilling
val nextItem = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
if (nextItem == null) {
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
}
Result.Success(processedBitmap)
Result.Success(finalBitmap)
} catch (e: Exception) {
Result.Error(e)
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.domain.usecase
import com.anthonyla.paperize.core.Result
import com.anthonyla.paperize.data.datastore.PreferencesManager
import com.anthonyla.paperize.domain.repository.AlbumRepository
import javax.inject.Inject
@@ -8,9 +9,14 @@ import javax.inject.Inject
* Use case to delete an album
*/
class DeleteAlbumUseCase @Inject constructor(
private val albumRepository: AlbumRepository
private val albumRepository: AlbumRepository,
private val preferencesManager: PreferencesManager
) {
suspend operator fun invoke(albumId: String): Result<Unit> {
return albumRepository.deleteAlbum(albumId)
val result = albumRepository.deleteAlbum(albumId)
if (result is Result.Success) {
preferencesManager.clearAlbumSelectionsIfMatches(albumId)
}
return result
}
}
@@ -0,0 +1,16 @@
package com.anthonyla.paperize.domain.usecase
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.domain.repository.AlbumRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
/**
* Use case to get all album summaries (lightweight metadata + counts)
* Optimized for displaying lists of albums without loading full wallpaper data
*/
class GetAlbumSummariesUseCase @Inject constructor(
private val albumRepository: AlbumRepository
) {
operator fun invoke(): Flow<List<AlbumSummary>> = albumRepository.getAlbumSummaries()
}
@@ -37,26 +37,12 @@ class MainActivity : ComponentActivity() {
// Track if DataStore has loaded at least once
// This prevents the loading screen from showing again if the composable is recomposed
var hasLoadedDataStore by remember { mutableStateOf(false) }
val appSettings by settingsViewModel.appSettings.collectAsStateWithLifecycle()
// Wait for the first real DataStore emission (not the default value)
// This prevents flickering to onboarding screen on app start
LaunchedEffect(Unit) {
snapshotFlow { appSettings }
.collect { settings ->
// Mark as loaded once we get a value different from the default
// OR if we've already marked it as loaded (prevents reset on recomposition)
if (settings != AppSettings.default() || hasLoadedDataStore) {
hasLoadedDataStore = true
}
}
}
PaperizeTheme(
darkMode = appSettings.darkMode,
dynamicTheming = appSettings.dynamicTheming
darkMode = appSettings?.darkMode ?: false,
dynamicTheming = appSettings?.dynamicTheming ?: true
) {
Surface(
modifier = Modifier.fillMaxSize(),
@@ -64,10 +50,11 @@ class MainActivity : ComponentActivity() {
) {
// Only render navigation once DataStore has loaded
// After first load, always show navigation even during updates
if (hasLoadedDataStore) {
val currentSettings = appSettings
if (currentSettings != null) {
NavigationGraph(
startDestination = if (appSettings.firstLaunch) StartupRoute else HomeRoute,
animate = appSettings.animate,
startDestination = if (currentSettings.firstLaunch) StartupRoute else HomeRoute,
animate = currentSettings.animate,
onFirstLaunchComplete = {
settingsViewModel.updateFirstLaunch(false)
}
@@ -11,6 +11,7 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import com.anthonyla.paperize.core.util.PermissionUtil
import com.anthonyla.paperize.presentation.common.navigation.util.enterTransitionBackward
import com.anthonyla.paperize.presentation.common.navigation.util.enterTransitionForward
import com.anthonyla.paperize.presentation.common.navigation.util.exitTransitionBackward
@@ -46,6 +47,9 @@ fun NavigationGraph(
if (animate) { { enterTransitionBackward() } } else { { EnterTransition.None } }
val exitBackward: AnimatedContentTransitionScope<NavBackStackEntry>.() -> ExitTransition =
if (animate) { { exitTransitionBackward() } } else { { ExitTransition.None } }
// Helper functions for permission checks
val context = androidx.compose.ui.platform.LocalContext.current
NavHost(
navController = navController,
startDestination = startDestination,
@@ -76,8 +80,19 @@ fun NavigationGraph(
) {
com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection.WallpaperModeSelectionScreen(
onModeSelected = {
navController.navigate(NotificationRoute) {
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
if (!PermissionUtil.hasNotificationPermission(context)) {
navController.navigate(NotificationRoute) {
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
}
} else if (!PermissionUtil.hasStoragePermission()) {
navController.navigate(StoragePermissionRoute) {
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
}
} else {
onFirstLaunchComplete()
navController.navigate(HomeRoute) {
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
}
}
}
)
@@ -92,8 +107,15 @@ fun NavigationGraph(
) {
NotificationPermissionScreen(
onContinue = {
navController.navigate(StoragePermissionRoute) {
popUpTo<NotificationRoute> { inclusive = true }
if (!PermissionUtil.hasStoragePermission()) {
navController.navigate(StoragePermissionRoute) {
popUpTo<NotificationRoute> { inclusive = true }
}
} else {
onFirstLaunchComplete()
navController.navigate(HomeRoute) {
popUpTo<NotificationRoute> { inclusive = true }
}
}
}
)
@@ -142,7 +164,6 @@ fun NavigationGraph(
) { backStackEntry ->
val route = backStackEntry.toRoute<AlbumRoute>()
AlbumViewScreen(
albumId = route.albumId,
onBackClick = { navController.popBackStack() },
onNavigateToFolder = { folderId ->
navController.navigate(FolderRoute(folderId))
@@ -163,9 +184,8 @@ fun NavigationGraph(
popEnterTransition = enterBackward,
popExitTransition = exitBackward
) { backStackEntry ->
val route = backStackEntry.toRoute<SortRoute>()
backStackEntry.toRoute<SortRoute>()
SortViewScreen(
albumId = route.albumId,
onSaveClick = { navController.popBackStack() },
onBackClick = { navController.popBackStack() }
)
@@ -178,9 +198,8 @@ fun NavigationGraph(
popEnterTransition = enterBackward,
popExitTransition = exitBackward
) { backStackEntry ->
val route = backStackEntry.toRoute<FolderRoute>()
backStackEntry.toRoute<FolderRoute>()
FolderViewScreen(
folderId = route.folderId,
onBackClick = { navController.popBackStack() },
onNavigateToWallpaperView = { wallpaperUri, wallpaperName ->
navController.navigate(WallpaperViewRoute(wallpaperUri, wallpaperName))
@@ -0,0 +1,144 @@
package com.anthonyla.paperize.presentation.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
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 androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import com.anthonyla.paperize.presentation.theme.AppSpacing
@Composable
fun OnboardingLayout(
icon: ImageVector,
title: String,
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
actions: @Composable () -> Unit
) {
var visible by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
// Delay to allow navigation transition to complete (approx 300ms)
// preventing "double dip" of animations
kotlinx.coroutines.delay(300)
visible = true
}
Column(
modifier = modifier
.fillMaxSize()
.padding(AppSpacing.extraLarge)
) {
Column(
modifier = Modifier
.weight(1f)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
AnimatedVisibility(
visible = visible,
enter = fadeIn(animationSpec = tween(500)) +
slideInVertically(
animationSpec = tween(500),
initialOffsetY = { 50 }
)
) {
Box(
modifier = Modifier
.size(120.dp) // Larger container for the icon background
.background(
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
shape = CircleShape
),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(AppIconSizes.huge),
tint = MaterialTheme.colorScheme.primary
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
AnimatedVisibility(
visible = visible,
enter = fadeIn(animationSpec = tween(500, delayMillis = 100)) +
slideInVertically(
animationSpec = tween(500, delayMillis = 100),
initialOffsetY = { 50 }
)
) {
Text(
text = title,
style = MaterialTheme.typography.headlineLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
}
Spacer(modifier = Modifier.height(AppSpacing.large))
AnimatedVisibility(
visible = visible,
enter = fadeIn(animationSpec = tween(500, delayMillis = 200)) +
slideInVertically(
animationSpec = tween(500, delayMillis = 200),
initialOffsetY = { 50 }
)
) {
content()
}
}
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Actions pinned to bottom
AnimatedVisibility(
visible = visible,
enter = fadeIn(animationSpec = tween(500, delayMillis = 300)) +
slideInVertically(
animationSpec = tween(500, delayMillis = 300),
initialOffsetY = { 100 }
)
) {
Column(
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
actions()
}
}
}
}
@@ -42,7 +42,6 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
@Composable
fun AlbumViewScreen(
@Suppress("UNUSED_PARAMETER") albumId: String,
onBackClick: () -> Unit,
onNavigateToFolder: (String) -> Unit,
onNavigateToWallpaperView: (String, String) -> Unit,
@@ -241,7 +240,6 @@ fun AlbumViewScreen(
// Sort Bottom Sheet
if (showSortSheet) {
SortBottomSheet(
currentSort = sortOption,
onSortSelected = { sortOption = it },
onDismiss = { showSortSheet = false }
)
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.album_view
import com.anthonyla.paperize.core.constants.Constants
import android.content.Context
import androidx.core.net.toUri
@@ -44,7 +45,7 @@ class AlbumViewViewModel @Inject constructor(
val album: StateFlow<Album?> = albumRepository.getAlbumById(albumId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = null
)
@@ -52,7 +53,7 @@ class AlbumViewViewModel @Inject constructor(
.map { it?.folders ?: emptyList() }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = emptyList()
)
@@ -60,7 +61,7 @@ class AlbumViewViewModel @Inject constructor(
val wallpapers: StateFlow<List<Wallpaper>> = wallpaperRepository.getDirectWallpapersByAlbum(albumId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = emptyList()
)
@@ -37,7 +37,6 @@ enum class SortOption {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SortBottomSheet(
@Suppress("UNUSED_PARAMETER") currentSort: SortOption,
onSortSelected: (SortOption) -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.album_view.components
import com.anthonyla.paperize.core.constants.Constants
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.updateTransition
@@ -71,7 +72,7 @@ fun WallpaperItem(
AsyncImage(
model = ImageRequest.Builder(context)
.data(wallpaperUri.toUri())
.size(Size(300, 500)) // Limit size for performance - suitable for grid thumbnails
.size(Size(Constants.GRID_THUMBNAIL_WIDTH, Constants.GRID_THUMBNAIL_HEIGHT)) // Limit size for performance - suitable for grid thumbnails
.build(),
contentDescription = null,
contentScale = ContentScale.Crop,
@@ -1,4 +1,5 @@
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
@@ -33,7 +34,6 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
@Composable
fun FolderViewScreen(
@Suppress("UNUSED_PARAMETER") folderId: String,
onBackClick: () -> Unit,
onNavigateToWallpaperView: (String, String) -> Unit,
modifier: Modifier = Modifier,
@@ -90,7 +90,7 @@ fun FolderViewScreen(
.then(
Modifier.animateItem(
placementSpec = tween(
durationMillis = 800,
durationMillis = Constants.ANIMATION_DURATION_LONG_MS,
delayMillis = 0,
easing = FastOutSlowInEasing
)
@@ -113,7 +113,6 @@ fun FolderViewScreen(
// Sort Bottom Sheet
if (showSortSheet) {
SortBottomSheet(
currentSort = sortOption,
onSortSelected = { sortOption = it },
onDismiss = { showSortSheet = false }
)
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.folder_view
import com.anthonyla.paperize.core.constants.Constants
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
@@ -28,14 +29,14 @@ class FolderViewViewModel @Inject constructor(
val folder: StateFlow<Folder?> = albumRepository.getFolderById(folderId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = null
)
val wallpapers: StateFlow<List<Wallpaper>> = wallpaperRepository.getWallpapersByFolder(folderId)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = emptyList()
)
}
@@ -1,16 +1,14 @@
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.animation.AnimatedVisibility
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.slideInVertically
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
@@ -41,11 +39,11 @@ 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
import com.anthonyla.paperize.presentation.screens.wallpaper.WallpaperScreen
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@@ -65,8 +63,8 @@ fun HomeScreen(
val context = LocalContext.current
val tabItems = getTabItems(
wallpaperTitle = stringResource(R.string.tab_wallpaper),
libraryTitle = stringResource(R.string.tab_library)
wallpaperTitle = stringResource(R.string.wallpaper),
libraryTitle = stringResource(R.string.library)
)
// Persist the initial tab index across navigation
@@ -78,48 +76,17 @@ fun HomeScreen(
initialTab.intValue = pagerState.currentPage
}
// Smooth entry animation state (persisted across navigation)
var showContent by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(Unit) {
// Only animate on first composition, not when navigating back
if (!showContent) {
// Small delay to ensure smooth appearance (respects animation setting)
if (appSettings.animate) {
delay(50) // Minimal delay for smooth entry
}
showContent = true
}
}
Scaffold(
topBar = {
HomeTopBar(
showSelectionModeAppBar = false,
selectionCount = 0,
onSettingsClick = onNavigateToSettings
)
}
) { paddingValues ->
AnimatedVisibility(
visible = showContent,
enter = if (appSettings.animate) {
fadeIn(
animationSpec = tween(
durationMillis = 300,
easing = FastOutSlowInEasing
)
) + slideInVertically(
animationSpec = tween(
durationMillis = 300,
easing = FastOutSlowInEasing
),
initialOffsetY = { it / 20 } // Small slide from bottom (5%)
)
} else {
fadeIn(animationSpec = tween(durationMillis = 0))
}
) {
Column(modifier = modifier.padding(paddingValues)) {
PrimaryTabRow(
selectedTabIndex = pagerState.currentPage
@@ -148,18 +115,23 @@ fun HomeScreen(
beyondViewportPageCount = 1
) { index ->
when (index.coerceIn(tabItems.indices)) {
0 -> WallpaperScreen(
albums = albums,
scheduleSettings = scheduleSettings,
appSettings = appSettings,
wallpaperMode = wallpaperMode,
onToggleChanger = { viewModel.toggleWallpaperChanger(it, onlyIfNotScheduled = true) },
onSelectHomeAlbum = { album -> viewModel.selectHomeAlbum(album) },
onSelectLockAlbum = { album -> viewModel.selectLockAlbum(album) },
onSelectLiveAlbum = { album -> viewModel.selectLiveAlbum(album) },
onUpdateScheduleSettings = { viewModel.updateScheduleSettings(it) },
onChangeWallpaperNow = { viewModel.changeWallpaperNow(it) }
)
0 -> {
if (wallpaperMode == null) {
Box(modifier = Modifier.fillMaxSize())
} else {
WallpaperScreen(
albums = albums,
scheduleSettings = scheduleSettings,
appSettings = appSettings,
wallpaperMode = wallpaperMode!!,
onToggleChanger = { viewModel.toggleWallpaperChanger(it, onlyIfNotScheduled = true) },
onSelectHomeAlbum = { album -> viewModel.selectHomeAlbum(album) },
onSelectLockAlbum = { album -> viewModel.selectLockAlbum(album) },
onSelectLiveAlbum = { album -> viewModel.selectLiveAlbum(album) },
onUpdateScheduleSettings = { viewModel.updateScheduleSettings(it) }
)
}
}
else -> LibraryScreen(
albums = albums,
onViewAlbum = onNavigateToAlbum,
@@ -169,26 +141,26 @@ fun HomeScreen(
}
}
}
}
// Live Wallpaper Selection Prompt
if (showLiveWallpaperPrompt && wallpaperMode == WallpaperMode.LIVE) {
if (wallpaperMode != null && showLiveWallpaperPrompt && wallpaperMode == WallpaperMode.LIVE) {
AlertDialog(
onDismissRequest = { viewModel.dismissLiveWallpaperPrompt() },
title = {
Text(
text = "Select Live Wallpaper",
text = stringResource(R.string.select_live_wallpaper),
fontWeight = FontWeight.Bold
)
},
text = {
Column {
Text(
text = "To use Paperize in Live Wallpaper mode, you need to select it as your live wallpaper from the system settings.",
text = stringResource(R.string.select_live_wallpaper_instruction),
style = MaterialTheme.typography.bodyMedium
)
Text(
text = "\nTap 'Open Wallpaper Picker' below to select Paperize from the list of available live wallpapers.",
text = stringResource(R.string.open_wallpaper_picker_instruction_newline),
style = MaterialTheme.typography.bodyMedium
)
}
@@ -222,12 +194,12 @@ fun HomeScreen(
}
}
) {
Text("Open Wallpaper Picker")
Text(stringResource(R.string.open_wallpaper_picker))
}
},
dismissButton = {
TextButton(onClick = { viewModel.dismissLiveWallpaperPrompt() }) {
Text("Later")
Text(stringResource(R.string.later))
}
}
)
@@ -1,16 +1,20 @@
package com.anthonyla.paperize.presentation.screens.home
import com.anthonyla.paperize.core.constants.Constants
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.ScreenType
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.GetAlbumsUseCase
import com.anthonyla.paperize.domain.usecase.GetAlbumSummariesUseCase
import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService
import com.anthonyla.paperize.service.worker.WallpaperScheduler
import dagger.hilt.android.lifecycle.HiltViewModel
@@ -28,7 +32,7 @@ import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
@param:ApplicationContext private val context: Context,
getAlbumsUseCase: GetAlbumsUseCase,
getAlbumSummariesUseCase: GetAlbumSummariesUseCase,
private val createAlbumUseCase: CreateAlbumUseCase,
private val deleteAlbumUseCase: DeleteAlbumUseCase,
private val settingsRepository: SettingsRepository,
@@ -36,32 +40,41 @@ class HomeViewModel @Inject constructor(
private val wallpaperRepository: com.anthonyla.paperize.domain.repository.WallpaperRepository
) : ViewModel() {
val albums: StateFlow<List<Album>> = getAlbumsUseCase()
companion object {
private const val TAG = "HomeViewModel"
}
init {
// Check if Paperize live wallpaper was replaced/disabled on startup
checkLiveWallpaperStatus()
}
val albums: StateFlow<List<AlbumSummary>> = getAlbumSummariesUseCase()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = emptyList()
)
val scheduleSettings: StateFlow<ScheduleSettings> = settingsRepository.getScheduleSettingsFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = ScheduleSettings.default()
)
val appSettings = settingsRepository.getAppSettingsFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = com.anthonyla.paperize.domain.model.AppSettings.default()
)
val wallpaperMode = settingsRepository.getWallpaperModeFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = com.anthonyla.paperize.core.WallpaperMode.STATIC
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = null
)
// Show prompt to select live wallpaper when enabling changer in LIVE mode
@@ -72,6 +85,36 @@ class HomeViewModel @Inject constructor(
_showLiveWallpaperPrompt.value = false
}
/**
* Check if Paperize live wallpaper is still active on app startup.
* If the user was in LIVE mode with an album selected but Paperize is no longer
* the active live wallpaper (e.g., user switched to a different wallpaper),
* clear the live album selection and disable the changer.
*/
private fun checkLiveWallpaperStatus() {
viewModelScope.launch {
val mode = settingsRepository.getWallpaperMode()
val settings = settingsRepository.getScheduleSettings()
// Only check if we're in LIVE mode and have an album selected
if (mode == com.anthonyla.paperize.core.WallpaperMode.LIVE &&
settings.liveAlbumId != null &&
settings.enableChanger) {
val isActive = isPaperizeLiveWallpaperActive(context)
Log.d(TAG, "Startup check: LIVE mode with album selected, isPaperizeLiveWallpaperActive=$isActive")
if (!isActive) {
Log.w(TAG, "Paperize live wallpaper was replaced/disabled - clearing live album selection")
// Clear the live album selection and disable changer
settingsRepository.updateLiveAlbumId(null)
settingsRepository.updateEnableChanger(false)
wallpaperScheduler.cancelAllWallpaperChanges()
}
}
}
}
fun createAlbum(name: String) {
viewModelScope.launch {
when (createAlbumUseCase(name)) {
@@ -90,7 +133,13 @@ class HomeViewModel @Inject constructor(
// Disable changer if albums were cleared and no albums remain selected
if (wasCleared) {
val settings = settingsRepository.getScheduleSettings()
if (settings.homeAlbumId == null && settings.lockAlbumId == null) {
// 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)
}
}
@@ -104,7 +153,7 @@ class HomeViewModel @Inject constructor(
}
}
fun selectHomeAlbum(album: Album?) {
fun selectHomeAlbum(album: AlbumSummary?) {
viewModelScope.launch {
// Use atomic update to prevent race conditions with selectLockAlbum()
settingsRepository.updateHomeAlbumId(album?.id)
@@ -170,7 +219,7 @@ class HomeViewModel @Inject constructor(
}
}
fun selectLockAlbum(album: Album?) {
fun selectLockAlbum(album: AlbumSummary?) {
viewModelScope.launch {
// Use atomic update to prevent race conditions with selectHomeAlbum()
settingsRepository.updateLockAlbumId(album?.id)
@@ -236,7 +285,7 @@ class HomeViewModel @Inject constructor(
}
}
fun selectLiveAlbum(album: Album?) {
fun selectLiveAlbum(album: AlbumSummary?) {
viewModelScope.launch {
settingsRepository.updateLiveAlbumId(album?.id)
@@ -264,7 +313,6 @@ class HomeViewModel @Inject constructor(
val updated = settingsRepository.getScheduleSettings()
if (enabled) {
// Check if we have all required albums before changing wallpaper
// Check if we have all required albums before changing wallpaper
val homeActive = updated.homeEnabled && updated.homeAlbumId != null
val lockActive = updated.lockEnabled && updated.lockAlbumId != null
@@ -297,9 +345,12 @@ class HomeViewModel @Inject constructor(
scheduleAlarms(updated, onlyIfNotScheduled)
// Show live wallpaper selection prompt if in LIVE mode and Paperize is NOT already active
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE &&
!com.anthonyla.paperize.core.util.isPaperizeLiveWallpaperActive(context)) {
_showLiveWallpaperPrompt.value = true
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
val isActive = isPaperizeLiveWallpaperActive(context)
Log.d(TAG, "toggleWallpaperChanger: LIVE mode, isPaperizeLiveWallpaperActive=$isActive")
if (!isActive) {
_showLiveWallpaperPrompt.value = true
}
}
} else {
// Not all required albums selected - cancel any existing schedules
@@ -347,7 +398,6 @@ class HomeViewModel @Inject constructor(
val homeActive = validated.homeEnabled && validated.homeAlbumId != null
val lockActive = validated.lockEnabled && validated.lockAlbumId != null
// Determine if we have the required albums selected
// Determine if we have the required albums selected
val hasRequiredAlbums = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
when {
@@ -366,9 +416,12 @@ class HomeViewModel @Inject constructor(
// Show live wallpaper selection prompt if in LIVE mode, changer was just enabled, and Paperize is NOT already active
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE &&
!currentSettings.enableChanger && validated.enableChanger &&
!com.anthonyla.paperize.core.util.isPaperizeLiveWallpaperActive(context)) {
_showLiveWallpaperPrompt.value = true
!currentSettings.enableChanger && validated.enableChanger) {
val isActive = isPaperizeLiveWallpaperActive(context)
Log.d(TAG, "updateScheduleSettings: LIVE mode, changer just enabled, isPaperizeLiveWallpaperActive=$isActive")
if (!isActive) {
_showLiveWallpaperPrompt.value = true
}
}
} else if (validated.enableChanger && !hasRequiredAlbums) {
// Changer enabled but required albums not selected - cancel existing schedules
@@ -402,6 +455,21 @@ class HomeViewModel @Inject constructor(
}
private fun scheduleAlarms(settings: ScheduleSettings, onlyIfNotScheduled: Boolean = false) {
// Check if we're in LIVE mode
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
// LIVE mode: schedule live wallpaper changes
if (settings.liveAlbumId != null && settings.liveIntervalMinutes > 0) {
wallpaperScheduler.scheduleWallpaperChange(
ScreenType.LIVE,
settings.liveIntervalMinutes
)
} else {
wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE)
}
return
}
// STATIC mode: existing logic
val homeActive = settings.homeEnabled && settings.homeAlbumId != null
val lockActive = settings.lockEnabled && settings.lockAlbumId != null
@@ -15,7 +15,6 @@ import com.anthonyla.paperize.R
@Composable
fun HomeTopBar(
showSelectionModeAppBar: Boolean,
@Suppress("UNUSED_PARAMETER") selectionCount: Int,
onSettingsClick: () -> Unit
) {
if (!showSelectionModeAppBar) {
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.library
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -31,7 +32,7 @@ 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.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.presentation.common.components.AddAlbumDialog
import com.anthonyla.paperize.presentation.screens.library.components.AlbumItem
import com.anthonyla.paperize.presentation.theme.AppGrid
@@ -39,7 +40,7 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
@Composable
fun LibraryScreen(
albums: List<Album>,
albums: List<AlbumSummary>,
onViewAlbum: (String) -> Unit,
onCreateAlbum: (String) -> Unit,
modifier: Modifier = Modifier
@@ -60,7 +61,7 @@ fun LibraryScreen(
Icon(
Icons.Filled.Add,
contentDescription = stringResource(R.string.add_album),
modifier = Modifier.size(32.dp)
modifier = Modifier.size(AppIconSizes.medium)
)
}
}
@@ -79,7 +80,7 @@ fun LibraryScreen(
Icon(
imageVector = Icons.Default.PhotoLibrary,
contentDescription = null,
modifier = Modifier.size(80.dp),
modifier = Modifier.size(AppIconSizes.huge),
tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.4f)
)
Text(
@@ -118,6 +119,7 @@ fun LibraryScreen(
}
if (showAddAlbumDialog) {
val errorMessageString = stringResource(R.string.album_name_exists_error)
AddAlbumDialog(
onDismiss = {
showAddAlbumDialog = false
@@ -127,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 = "Album with this name already exists"
albumNameError = errorMessageString
} else {
onCreateAlbum(name)
showAddAlbumDialog = false
@@ -1,4 +1,8 @@
package com.anthonyla.paperize.presentation.screens.library.components
import com.anthonyla.paperize.presentation.theme.AppRadii
import com.anthonyla.paperize.presentation.theme.AppElevation
import com.anthonyla.paperize.presentation.theme.AppShapes
import com.anthonyla.paperize.presentation.theme.AppBorderWidths
import android.content.Context
import android.net.Uri
@@ -36,7 +40,7 @@ import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.presentation.common.components.InteractiveCard
import com.anthonyla.paperize.presentation.theme.AppSpacing
@@ -45,7 +49,7 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
*/
@Composable
fun AlbumItem(
album: Album,
album: AlbumSummary,
onAlbumViewClick: () -> Unit,
modifier: Modifier = Modifier
) {
@@ -57,9 +61,9 @@ fun AlbumItem(
InteractiveCard(
onClick = onAlbumViewClick,
modifier = modifier.fillMaxSize(),
defaultRadius = 20.dp,
pressedRadius = 36.dp,
elevation = 1.dp
defaultRadius = AppRadii.large,
pressedRadius = AppRadii.huge,
elevation = AppElevation.level1
) {
Column(
modifier = Modifier.padding(AppSpacing.medium),
@@ -71,10 +75,10 @@ fun AlbumItem(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(12.dp))
.clip(AppShapes.smallCardShape)
.background(MaterialTheme.colorScheme.surfaceContainerHighest)
.border(
width = 2.dp,
width = AppBorderWidths.medium,
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.15f),
shape = RoundedCornerShape(12.dp)
),
@@ -1,4 +1,7 @@
package com.anthonyla.paperize.presentation.screens.notification
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import com.anthonyla.paperize.presentation.components.OnboardingLayout
import com.anthonyla.paperize.core.util.PermissionUtil
import android.Manifest
import android.content.pm.PackageManager
@@ -33,133 +36,98 @@ fun NotificationPermissionScreen(
modifier: Modifier = Modifier
) {
val context = LocalContext.current
var permissionGranted by remember {
mutableStateOf(
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
} else {
true // Notification permission not needed before Android 13
}
)
mutableStateOf(PermissionUtil.hasNotificationPermission(context))
}
var hasShownScreen by remember { mutableStateOf(false) }
var hasNavigated by remember { mutableStateOf(false) } // Single-use navigation flag
val permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { isGranted ->
// Only update and navigate if we haven't navigated yet
if (!hasNavigated) {
permissionGranted = isGranted
if (isGranted) {
hasNavigated = true // Mark as navigated BEFORE calling onContinue
onContinue()
}
}
}
// Auto-navigate if permission is already granted
LaunchedEffect(permissionGranted) {
if (permissionGranted && !hasNavigated) {
hasNavigated = true // Mark as navigated BEFORE delay
kotlinx.coroutines.delay(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS) // Brief delay for smooth transition
permissionGranted = isGranted
if (isGranted) {
onContinue()
}
}
Column(
modifier = modifier
.fillMaxSize()
.padding(AppSpacing.extraLarge)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Enhanced icon with larger size
Icon(
imageVector = Icons.Default.Notifications,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(AppSpacing.large))
Text(
text = stringResource(R.string.notification_permission_title),
style = MaterialTheme.typography.titleLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Enhanced card with better styling
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer
)
) {
OnboardingLayout(
icon = Icons.Default.Notifications,
title = stringResource(R.string.notification_permission_title),
modifier = modifier,
content = {
Column(
modifier = Modifier.padding(AppSpacing.large),
horizontalAlignment = Alignment.CenterHorizontally
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
// Cleaner explanation card
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f)
),
border = androidx.compose.foundation.BorderStroke(
width = 1.dp,
color = MaterialTheme.colorScheme.outlineVariant
)
) {
Column(
modifier = Modifier.padding(AppSpacing.large),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.notification_permission_description),
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
}
}
}
},
actions = {
// Allow button
Button(
onClick = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
onContinue()
}
},
modifier = Modifier.fillMaxWidth(),
enabled = !permissionGranted,
shape = MaterialTheme.shapes.large
) {
Text(
text = stringResource(R.string.notification_permission_description),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSecondaryContainer
text = if (permissionGranted) {
stringResource(R.string.permission_granted)
} else {
stringResource(R.string.allow)
},
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
// Skip button
FilledTonalButton(
onClick = onContinue,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = ButtonDefaults.filledTonalButtonColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant
)
) {
Text(
text = stringResource(R.string.skip),
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Enhanced allow button
Button(
onClick = {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
onContinue()
}
},
modifier = Modifier.fillMaxWidth(),
enabled = !permissionGranted,
shape = MaterialTheme.shapes.large
) {
Text(
text = if (permissionGranted) {
stringResource(R.string.permission_granted)
} else {
stringResource(R.string.allow)
},
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Enhanced skip button
FilledTonalButton(
onClick = onContinue,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large
) {
Text(
text = stringResource(R.string.skip),
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
)
}
@@ -5,13 +5,20 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Build
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.Wallpaper
import androidx.compose.material.icons.filled.BatteryAlert
import androidx.compose.material.icons.filled.BatteryFull
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.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
@@ -20,6 +27,9 @@ 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
/**
* Settings screen with Material 3 Expressive design
@@ -37,6 +47,25 @@ fun SettingsScreen(
var showResetDialog by remember { mutableStateOf(false) }
var showModeChangeDialog by remember { mutableStateOf(false) }
var pendingMode by remember { mutableStateOf<com.anthonyla.paperize.core.WallpaperMode?>(null) }
val context = LocalContext.current
var isIgnoringBatteryOptimizations by remember {
mutableStateOf(BatteryOptimizationUtil.isIgnoringBatteryOptimizations(context))
}
// Refresh battery optimization status when returning to the screen
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
isIgnoringBatteryOptimizations = BatteryOptimizationUtil.isIgnoringBatteryOptimizations(context)
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
Scaffold(
topBar = {
@@ -60,15 +89,15 @@ fun SettingsScreen(
.verticalScroll(rememberScrollState())
.padding(horizontal = AppSpacing.large)
) {
Spacer(modifier = Modifier.height(AppSpacing.medium))
Spacer(modifier = Modifier.height(AppSpacing.large))
// Wallpaper Mode Section
SectionHeader(
icon = Icons.Filled.Wallpaper,
title = "Wallpaper Mode"
title = stringResource(R.string.wallpaper_mode_setting)
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Spacer(modifier = Modifier.height(AppSpacing.medium))
Card(
modifier = Modifier.fillMaxWidth(),
@@ -87,7 +116,7 @@ fun SettingsScreen(
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Current Mode",
text = stringResource(R.string.current_mode),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
@@ -95,8 +124,8 @@ fun SettingsScreen(
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
Text(
text = when (wallpaperMode) {
com.anthonyla.paperize.core.WallpaperMode.STATIC -> "Static"
com.anthonyla.paperize.core.WallpaperMode.LIVE -> "Live Wallpaper"
com.anthonyla.paperize.core.WallpaperMode.STATIC -> stringResource(R.string.mode_static)
com.anthonyla.paperize.core.WallpaperMode.LIVE -> stringResource(R.string.mode_live_wallpaper)
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.primary,
@@ -113,21 +142,21 @@ fun SettingsScreen(
showModeChangeDialog = true
}
) {
Text("Switch")
Text(stringResource(R.string.switch_button))
}
}
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = "Switching modes will reset all albums, wallpapers, and settings. This cannot be undone.",
text = stringResource(R.string.mode_switch_warning),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.large))
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Appearance Section
SectionHeader(
@@ -135,12 +164,12 @@ fun SettingsScreen(
title = stringResource(R.string.appearance)
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Spacer(modifier = Modifier.height(AppSpacing.medium))
SettingSwitchItem(
title = stringResource(R.string.dark_mode),
description = stringResource(R.string.easier_on_the_eyes),
checked = appSettings.darkMode ?: false,
checked = appSettings?.darkMode ?: false,
onCheckedChange = { viewModel.updateDarkMode(it) }
)
@@ -149,7 +178,7 @@ fun SettingsScreen(
SettingSwitchItem(
title = stringResource(R.string.dynamic_theming),
description = stringResource(R.string.material_you),
checked = appSettings.dynamicTheming,
checked = appSettings?.dynamicTheming ?: true,
onCheckedChange = { viewModel.updateDynamicTheming(it) }
)
@@ -158,11 +187,89 @@ fun SettingsScreen(
SettingSwitchItem(
title = stringResource(R.string.animation),
description = stringResource(R.string.increase_visual_appeal),
checked = appSettings.animate,
checked = appSettings?.animate ?: true,
onCheckedChange = { viewModel.updateAnimate(it) }
)
Spacer(modifier = Modifier.height(AppSpacing.large))
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Reliability Section
SectionHeader(
icon = Icons.Default.Build,
title = stringResource(R.string.reliability)
)
Spacer(modifier = Modifier.height(AppSpacing.medium))
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.medium,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
)
) {
Column(
modifier = Modifier.padding(AppSpacing.large)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.battery_optimization),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = if (isIgnoringBatteryOptimizations)
Icons.Default.BatteryFull else Icons.Default.BatteryAlert,
contentDescription = null,
tint = if (isIgnoringBatteryOptimizations)
MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = if (isIgnoringBatteryOptimizations)
stringResource(R.string.ignoring)
else
stringResource(R.string.optimizing),
style = MaterialTheme.typography.bodyMedium,
color = if (isIgnoringBatteryOptimizations)
MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
fontWeight = FontWeight.Medium
)
}
}
if (!isIgnoringBatteryOptimizations) {
Button(
onClick = {
BatteryOptimizationUtil.requestIgnoreBatteryOptimizations(context)
}
) {
Text(stringResource(R.string.check_status))
}
}
}
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = stringResource(R.string.battery_optimization_description),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// About Section
SectionHeader(
@@ -170,7 +277,7 @@ fun SettingsScreen(
title = stringResource(R.string.about)
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Privacy Policy Card with enhanced styling
Card(
@@ -252,9 +359,15 @@ fun SettingsScreen(
showModeChangeDialog = false
pendingMode = null
},
title = { Text("Switch to ${if (pendingMode == com.anthonyla.paperize.core.WallpaperMode.LIVE) "Live Wallpaper" else "Static"} Mode?") },
title = {
val modeName = if (pendingMode == com.anthonyla.paperize.core.WallpaperMode.LIVE)
stringResource(R.string.mode_live_wallpaper)
else
stringResource(R.string.mode_static)
Text(stringResource(R.string.switch_mode_dialog_title, modeName))
},
text = {
Text("This will reset all albums, wallpapers, and scheduling settings. This action cannot be undone.\n\nYou'll need to re-add your albums and configure your wallpaper settings.")
Text(stringResource(R.string.switch_mode_dialog_description))
},
confirmButton = {
TextButton(
@@ -267,7 +380,7 @@ fun SettingsScreen(
contentColor = MaterialTheme.colorScheme.error
)
) {
Text("Switch Mode")
Text(stringResource(R.string.switch_mode_button))
}
},
dismissButton = {
@@ -292,24 +405,35 @@ private fun SectionHeader(
title: String,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(AppSpacing.small)
Card(
modifier = modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.medium,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.3f)
)
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
Text(
text = title,
style = MaterialTheme.typography.headlineSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Row(
modifier = Modifier.padding(
horizontal = AppSpacing.large,
vertical = AppSpacing.medium
),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(28.dp)
)
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.Bold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
}
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.settings
import com.anthonyla.paperize.core.constants.Constants
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
@@ -25,17 +26,17 @@ class SettingsViewModel @Inject constructor(
private val wallpaperScheduler: WallpaperScheduler
) : ViewModel() {
val appSettings: StateFlow<AppSettings> = settingsRepository.getAppSettingsFlow()
val appSettings: StateFlow<AppSettings?> = settingsRepository.getAppSettingsFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.Eagerly, // Start loading immediately to prevent onboarding flicker
initialValue = AppSettings.default()
initialValue = null
)
val wallpaperMode: StateFlow<WallpaperMode> = settingsRepository.getWallpaperModeFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = WallpaperMode.STATIC
)
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.sort
import com.anthonyla.paperize.core.constants.Constants
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
@@ -30,7 +31,7 @@ class SortViewModel @Inject constructor(
private val _state = MutableStateFlow(SortState())
val state = _state.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
started = SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS),
initialValue = SortState()
)
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.sort
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import android.os.Build
import android.view.HapticFeedbackConstants
@@ -65,7 +66,6 @@ import sh.calvin.reorderable.rememberReorderableLazyListState
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun SortViewScreen(
@Suppress("UNUSED_PARAMETER") albumId: String,
onSaveClick: () -> Unit,
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
@@ -292,7 +292,7 @@ fun SortViewScreen(
contentDescription = wallpaper.displayFileName,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(48.dp)
.size(AppIconSizes.large)
.border(
BorderStroke(
1.dp,
@@ -329,7 +329,7 @@ fun SortViewScreen(
contentDescription = currentFolder.name,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(48.dp)
.size(AppIconSizes.large)
.clip(AppShapes.imageShape)
)
},
@@ -415,7 +415,7 @@ fun SortViewScreen(
contentDescription = wallpaper.displayFileName,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(48.dp)
.size(AppIconSizes.large)
.clip(CircleShape)
.border(
BorderStroke(
@@ -57,7 +57,7 @@ fun SortViewTopBar(
) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
contentDescription = stringResource(R.string.content_desc_back),
contentDescription = stringResource(R.string.back),
)
}
},
@@ -1,4 +1,6 @@
package com.anthonyla.paperize.presentation.screens.startup
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import com.anthonyla.paperize.presentation.components.OnboardingLayout
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
@@ -25,88 +27,73 @@ fun StartupScreen(
onAgree: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxSize()
.padding(AppSpacing.extraLarge)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// App branding with icon
Icon(
imageVector = Icons.Default.Wallpaper,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(AppSpacing.medium))
Text(
text = stringResource(R.string.app_name),
style = MaterialTheme.typography.headlineLarge,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = stringResource(R.string.welcome),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Medium
)
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Privacy notice card with enhanced styling
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer
)
) {
OnboardingLayout(
icon = Icons.Default.Wallpaper,
title = stringResource(R.string.app_name),
modifier = modifier,
content = {
Column(
modifier = Modifier.padding(AppSpacing.extraLarge)
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
Text(
text = stringResource(R.string.privacy_notice),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onPrimaryContainer
text = stringResource(R.string.welcome),
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Medium
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = stringResource(
R.string.please_read_and_agree_to_the_following_privacy_notice_to_use_the_app
// Cleaner privacy notice
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onPrimaryContainer
border = androidx.compose.foundation.BorderStroke(
width = 1.dp,
color = MaterialTheme.colorScheme.outlineVariant
)
) {
Column(
modifier = Modifier.padding(AppSpacing.large)
) {
Text(
text = stringResource(R.string.privacy_notice),
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = stringResource(
R.string.please_read_and_agree_to_the_following_privacy_notice_to_use_the_app
),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
},
actions = {
Button(
onClick = onAgree,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large
) {
Text(
text = stringResource(R.string.agree),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Enhanced button with better styling
Button(
onClick = onAgree,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large
) {
Text(
text = stringResource(R.string.agree),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
)
}
@@ -1,4 +1,7 @@
package com.anthonyla.paperize.presentation.screens.storage
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import com.anthonyla.paperize.presentation.components.OnboardingLayout
import com.anthonyla.paperize.core.util.PermissionUtil
import android.content.Intent
import android.net.Uri
@@ -34,18 +37,12 @@ fun StoragePermissionScreen(
modifier: Modifier = Modifier
) {
val context = LocalContext.current
var permissionGranted by remember { mutableStateOf(Environment.isExternalStorageManager()) }
var hasShownScreen by remember { mutableStateOf(false) }
var hasNavigated by remember { mutableStateOf(false) } // Single-use navigation flag
var permissionGranted by remember { mutableStateOf(PermissionUtil.hasStoragePermission()) }
// Check permission status on resume (when user returns from settings)
DisposableEffect(Unit) {
val listener = object : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
// Only update if we haven't navigated yet
if (!hasNavigated) {
permissionGranted = Environment.isExternalStorageManager()
}
permissionGranted = PermissionUtil.hasStoragePermission()
}
}
val lifecycleOwner = context as? LifecycleOwner
@@ -56,116 +53,102 @@ fun StoragePermissionScreen(
}
}
// Auto-navigate if permission is already granted
// Automatically continue when permission is granted
LaunchedEffect(permissionGranted) {
if (permissionGranted && !hasNavigated) {
hasNavigated = true // Mark as navigated BEFORE delay
kotlinx.coroutines.delay(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS) // Brief delay for smooth transition
if (permissionGranted) {
onContinue()
}
}
Column(
modifier = modifier
.fillMaxSize()
.padding(AppSpacing.extraLarge)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Enhanced icon with larger size
Icon(
imageVector = Icons.Default.Folder,
contentDescription = null,
modifier = Modifier.size(64.dp),
tint = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(AppSpacing.large))
Text(
text = stringResource(R.string.storage_permission_title),
style = MaterialTheme.typography.titleLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Enhanced card with better styling
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer
)
) {
OnboardingLayout(
icon = Icons.Default.Folder,
title = stringResource(R.string.storage_permission_title),
modifier = modifier,
content = {
Column(
modifier = Modifier.padding(AppSpacing.large),
verticalArrangement = Arrangement.spacedBy(AppSpacing.small),
horizontalAlignment = Alignment.CenterHorizontally
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
// Cleaner explanation card
Card(
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.5f)
),
border = androidx.compose.foundation.BorderStroke(
width = 1.dp,
color = MaterialTheme.colorScheme.outlineVariant
)
) {
Column(
modifier = Modifier.padding(AppSpacing.large),
verticalArrangement = Arrangement.spacedBy(AppSpacing.small),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.storage_permission_description),
style = MaterialTheme.typography.bodyLarge,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onTertiaryContainer
)
Text(
text = stringResource(R.string.storage_permission_optional),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.8f),
textAlign = TextAlign.Center,
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium
)
}
}
}
},
actions = {
// Allow button
Button(
onClick = {
if (!PermissionUtil.hasStoragePermission()) {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply {
data = Uri.parse("package:${context.packageName}")
}
context.startActivity(intent)
} else {
onContinue()
}
},
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large
) {
Text(
text = stringResource(R.string.storage_permission_description),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onTertiaryContainer
text = if (permissionGranted) {
stringResource(R.string.permission_granted)
} else {
stringResource(R.string.allow)
},
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
// Continue without permission button
FilledTonalButton(
onClick = onContinue,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = ButtonDefaults.filledTonalButtonColors(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
contentColor = MaterialTheme.colorScheme.onSurfaceVariant
)
) {
Text(
text = stringResource(R.string.storage_permission_optional),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.8f),
textAlign = TextAlign.Center,
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium
text = stringResource(R.string.continue_without_storage),
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Enhanced allow button
Button(
onClick = {
if (!Environment.isExternalStorageManager()) {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply {
data = Uri.parse("package:${context.packageName}")
}
context.startActivity(intent)
} else {
onContinue()
}
},
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large
) {
Text(
text = if (permissionGranted) {
stringResource(R.string.permission_granted)
} else {
stringResource(R.string.allow)
},
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Enhanced continue without permission button
FilledTonalButton(
onClick = onContinue,
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large
) {
Text(
text = stringResource(R.string.continue_without_storage),
style = MaterialTheme.typography.labelLarge,
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
)
}
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.wallpaper
import com.anthonyla.paperize.core.constants.Constants
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
@@ -44,8 +45,8 @@ 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.core.constants.Constants
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
import com.anthonyla.paperize.presentation.common.components.SettingSwitchItem
@@ -63,16 +64,15 @@ enum class AlbumSelectionContext {
@Composable
fun WallpaperScreen(
albums: List<Album>,
albums: List<AlbumSummary>,
scheduleSettings: ScheduleSettings,
appSettings: AppSettings,
wallpaperMode: WallpaperMode,
onToggleChanger: (Boolean) -> Unit,
onSelectHomeAlbum: (Album?) -> Unit,
onSelectLockAlbum: (Album?) -> Unit,
onSelectLiveAlbum: (Album?) -> Unit,
onSelectHomeAlbum: (AlbumSummary?) -> Unit,
onSelectLockAlbum: (AlbumSummary?) -> Unit,
onSelectLiveAlbum: (AlbumSummary?) -> Unit,
onUpdateScheduleSettings: (ScheduleSettings) -> Unit,
@Suppress("UNUSED_PARAMETER") onChangeWallpaperNow: (ScreenType) -> Unit,
modifier: Modifier = Modifier
) {
var showAlbumSelectionSheet by rememberSaveable { mutableStateOf(false) }
@@ -167,7 +167,7 @@ fun WallpaperScreen(
var selectedScalingIndex by rememberSaveable {
mutableIntStateOf(
when (scheduleSettings.homeScalingType) {
when (if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType) {
ScalingType.FILL -> 0
ScalingType.FIT -> 1
ScalingType.STRETCH -> 2
@@ -292,7 +292,6 @@ fun WallpaperScreen(
}
}
// Album Selection - Enhanced with better card styling
// Album Selection - Enhanced with better card styling
if (wallpaperMode == WallpaperMode.STATIC) {
if (homeEnabled && lockEnabled) {
@@ -320,7 +319,7 @@ fun WallpaperScreen(
Column(modifier = Modifier.weight(1f)) {
Text(
text = lockAlbum?.name ?: if (scheduleSettings.lockAlbumId != null) {
"..." // Loading placeholder
stringResource(R.string.loading_placeholder)
} else {
stringResource(R.string.no_album_selected)
},
@@ -369,7 +368,7 @@ fun WallpaperScreen(
Column(modifier = Modifier.weight(1f)) {
Text(
text = homeAlbum?.name ?: if (scheduleSettings.homeAlbumId != null) {
"..." // Loading placeholder
stringResource(R.string.loading_placeholder)
} else {
stringResource(R.string.no_album_selected)
},
@@ -416,7 +415,7 @@ fun WallpaperScreen(
val currentAlbumId = if (homeEnabled) scheduleSettings.homeAlbumId else scheduleSettings.lockAlbumId
Text(
text = currentAlbum?.name ?: if (currentAlbumId != null) {
"..." // Loading placeholder
stringResource(R.string.loading_placeholder)
} else {
stringResource(R.string.no_album_selected)
},
@@ -466,7 +465,7 @@ fun WallpaperScreen(
Column(modifier = Modifier.weight(1f)) {
Text(
text = liveAlbum?.name ?: if (scheduleSettings.liveAlbumId != null) {
"..." // Loading placeholder
stringResource(R.string.loading_placeholder)
} else {
stringResource(R.string.no_album_selected)
},
@@ -557,13 +556,10 @@ fun WallpaperScreen(
// Live Mode: Single Interval Picker
TimeIntervalPicker(
title = stringResource(R.string.interval_text),
minutes = scheduleSettings.homeIntervalMinutes, // Reuse home interval for Live
minutes = scheduleSettings.liveIntervalMinutes,
onMinutesChange = { minutes ->
onUpdateScheduleSettings(
scheduleSettings.copy(
homeIntervalMinutes = minutes,
lockIntervalMinutes = minutes
)
scheduleSettings.copy(liveIntervalMinutes = minutes)
)
}
)
@@ -625,10 +621,14 @@ fun WallpaperScreen(
else -> ScalingType.NONE
}
onUpdateScheduleSettings(
scheduleSettings.copy(
homeScalingType = scalingType,
lockScalingType = scalingType
)
if (wallpaperMode == WallpaperMode.LIVE) {
scheduleSettings.copy(liveScalingType = scalingType)
} else {
scheduleSettings.copy(
homeScalingType = scalingType,
lockScalingType = scalingType
)
}
)
},
selected = index == selectedScalingIndex
@@ -846,17 +846,9 @@ fun WallpaperScreen(
)
// Grayscale
SettingSwitch(
SettingSwitchWithSlider(
title = R.string.gray_filter,
description = if ((if (wallpaperMode == WallpaperMode.STATIC) {
when {
homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale
homeEnabled -> scheduleSettings.homeEffects.enableGrayscale
else -> scheduleSettings.lockEffects.enableGrayscale
}
} else {
scheduleSettings.liveEffects.enableGrayscale
}) && !scheduleSettings.separateSchedules) null else R.string.make_the_colors_grayscale,
description = R.string.make_the_colors_grayscale,
checked = if (wallpaperMode == WallpaperMode.STATIC) {
when {
homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale
@@ -881,6 +873,26 @@ fun WallpaperScreen(
)
)
}
},
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.grayscalePercentage else scheduleSettings.liveEffects.grayscalePercentage,
lockPercentage = scheduleSettings.lockEffects.grayscalePercentage,
onPercentageChange = { homePercent, lockPercent ->
if (wallpaperMode == WallpaperMode.STATIC) {
updateSettingsDebounced(
scheduleSettings.copy(
homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(grayscalePercentage = homePercent) else scheduleSettings.homeEffects,
lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(grayscalePercentage = lockPercent) else scheduleSettings.lockEffects
)
)
} else {
updateSettingsDebounced(
scheduleSettings.copy(
liveEffects = scheduleSettings.liveEffects.copy(grayscalePercentage = homePercent)
)
)
}
}
)
@@ -934,6 +946,20 @@ fun WallpaperScreen(
}
)
// Change wallpaper on screen off
SettingSwitch(
title = R.string.change_on_screen_off,
description = if (scheduleSettings.liveEffects.enableChangeOnScreenOn) null else R.string.change_wallpaper_when_screen_turns_off,
checked = scheduleSettings.liveEffects.enableChangeOnScreenOn,
onCheckedChange = { enabled ->
updateSettingsImmediate(
scheduleSettings.copy(
liveEffects = scheduleSettings.liveEffects.copy(enableChangeOnScreenOn = enabled)
)
)
}
)
// Parallax effect
SettingSwitchWithSlider(
title = R.string.parallax_effect,
@@ -971,7 +997,7 @@ fun WallpaperScreen(
scheduleSettings.liveAlbumId?.let { id ->
// Try to find full album, or create stub with ID for selection marking
albums.find { it.id == id }?.let { listOf(it) }
?: listOf(Album(id = id, name = "", coverUri = null))
?: listOf(AlbumSummary.empty(id = id))
} ?: emptyList()
}
AlbumSelectionContext.HOME -> {
@@ -979,7 +1005,7 @@ fun WallpaperScreen(
scheduleSettings.homeAlbumId?.let { id ->
// Try to find full album, or create stub with ID for selection marking
albums.find { it.id == id }?.let { listOf(it) }
?: listOf(Album(id = id, name = "", coverUri = null))
?: listOf(AlbumSummary.empty(id = id))
} ?: emptyList()
}
AlbumSelectionContext.LOCK -> {
@@ -987,7 +1013,7 @@ fun WallpaperScreen(
scheduleSettings.lockAlbumId?.let { id ->
// Try to find full album, or create stub with ID for selection marking
albums.find { it.id == id }?.let { listOf(it) }
?: listOf(Album(id = id, name = "", coverUri = null))
?: listOf(AlbumSummary.empty(id = id))
} ?: emptyList()
}
AlbumSelectionContext.BOTH -> {
@@ -996,13 +1022,13 @@ fun WallpaperScreen(
homeEnabled -> {
scheduleSettings.homeAlbumId?.let { id ->
albums.find { it.id == id }?.let { listOf(it) }
?: listOf(Album(id = id, name = "", coverUri = null))
?: listOf(AlbumSummary.empty(id = id))
} ?: emptyList()
}
lockEnabled -> {
scheduleSettings.lockAlbumId?.let { id ->
albums.find { it.id == id }?.let { listOf(it) }
?: listOf(Album(id = id, name = "", coverUri = null))
?: listOf(AlbumSummary.empty(id = id))
} ?: emptyList()
}
else -> emptyList()
@@ -1011,7 +1037,7 @@ fun WallpaperScreen(
},
onAlbumSelect = { album ->
// Check if album is empty (has 0 wallpapers)
if (album.totalWallpaperCount == 0) {
if (album.wallpaperCount == 0) {
showEmptyAlbumWarning = true
} else {
when (albumSelectionContext) {
@@ -1076,7 +1102,7 @@ fun WallpaperScreen(
text = {
Text(
text = stringResource(R.string.empty_album_message),
maxLines = 10,
maxLines = Constants.DIALOG_MESSAGE_MAX_LINES,
overflow = TextOverflow.Ellipsis
)
},
@@ -1,4 +1,7 @@
package com.anthonyla.paperize.presentation.screens.wallpaper.components
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import com.anthonyla.paperize.presentation.theme.AppBorderWidths
import com.anthonyla.paperize.core.constants.Constants
import android.content.Context
import android.net.Uri
@@ -46,16 +49,16 @@ import coil3.compose.AsyncImage
import coil3.request.ImageRequest
import coil3.size.Size
import com.anthonyla.paperize.R
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.AlbumSummary
import com.anthonyla.paperize.presentation.theme.AppShapes
import com.anthonyla.paperize.presentation.theme.AppSpacing
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlbumSelectionBottomSheet(
albums: List<Album>,
selectedAlbums: List<Album>,
onAlbumSelect: (Album) -> Unit,
albums: List<AlbumSummary>,
selectedAlbums: List<AlbumSummary>,
onAlbumSelect: (AlbumSummary) -> Unit,
onDismiss: () -> Unit
) {
val sheetState = rememberModalBottomSheetState()
@@ -109,7 +112,7 @@ fun AlbumSelectionBottomSheet(
@Composable
private fun AlbumSelectionItem(
album: Album,
album: AlbumSummary,
isSelected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
@@ -130,10 +133,10 @@ private fun AlbumSelectionItem(
// Album cover thumbnail
Box(
modifier = Modifier
.size(56.dp)
.size(AppIconSizes.extraLarge)
.aspectRatio(1f)
.border(
width = 1.dp,
width = AppBorderWidths.thin,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
shape = AppShapes.imageShape
)
@@ -144,17 +147,17 @@ private fun AlbumSelectionItem(
AsyncImage(
model = ImageRequest.Builder(context)
.data(Uri.parse(album.coverUri))
.size(Size(150, 150)) // Small thumbnail for list item
.size(Size(Constants.LIST_THUMBNAIL_SIZE, Constants.LIST_THUMBNAIL_SIZE)) // Small thumbnail for list item
.build(),
contentDescription = album.name,
contentScale = ContentScale.Crop,
modifier = Modifier.size(56.dp)
modifier = Modifier.size(AppIconSizes.extraLarge)
)
} else {
Icon(
imageVector = Icons.Filled.PhotoAlbum,
contentDescription = album.name,
modifier = Modifier.size(32.dp),
modifier = Modifier.size(AppIconSizes.medium),
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)
)
}
@@ -171,7 +174,7 @@ private fun AlbumSelectionItem(
overflow = TextOverflow.Ellipsis
)
Text(
text = pluralStringResource(R.plurals.wallpaper_count, album.totalWallpaperCount, album.totalWallpaperCount),
text = pluralStringResource(R.plurals.wallpaper_count, album.wallpaperCount, album.wallpaperCount),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -1,4 +1,7 @@
package com.anthonyla.paperize.presentation.screens.wallpaper.components
import com.anthonyla.paperize.presentation.theme.AppMaxWidths
import com.anthonyla.paperize.presentation.theme.AppBorderWidths
import com.anthonyla.paperize.core.constants.Constants
import android.app.WallpaperManager
import android.graphics.drawable.Drawable
@@ -44,7 +47,6 @@ 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.core.constants.Constants
import com.anthonyla.paperize.presentation.theme.AppShapes
import com.anthonyla.paperize.presentation.theme.AppSpacing
import coil3.compose.AsyncImage
@@ -71,7 +73,7 @@ import kotlin.math.min
*/
private suspend fun <T> retryWallpaperRead(
maxAttempts: Int = 4,
delayMs: Long = 500,
delayMs: Long = Constants.WALLPAPER_READ_INITIAL_DELAY_MS,
block: suspend () -> T
): T? {
var lastException: Exception? = null
@@ -179,33 +181,21 @@ fun CurrentWallpaperPreview(
// API 34+ has getDrawable(int which), earlier versions use getDrawable()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
// Get home screen wallpaper with retry logic
// Android's WallpaperManager writes wallpapers asynchronously to disk
// We need to retry with increasing delays to allow encoding to complete
val homeDrawable = retryWallpaperRead(
maxAttempts = 4,
delayMs = 500
) {
val homeDrawable = retryWallpaperRead {
wallpaperManager.getDrawable(WallpaperManager.FLAG_SYSTEM)
}
// Get lock screen wallpaper with retry logic
val lockDrawable = retryWallpaperRead(
maxAttempts = 4,
delayMs = 500
) {
val lockDrawable = retryWallpaperRead {
wallpaperManager.getDrawable(WallpaperManager.FLAG_LOCK)
} ?: homeDrawable
Triple(homeDrawable, lockDrawable, true)
} else {
// For API < 34, use getDrawable() without flags (gets current wallpaper)
val drawable = retryWallpaperRead(
maxAttempts = 4,
delayMs = 500
) {
wallpaperManager.getDrawable()
// For API [31-33], use getDrawable() which returns the current wallpaper
val drawable = retryWallpaperRead {
wallpaperManager.drawable
}
// Lock screen wallpaper not separately accessible on older APIs
Triple(drawable, drawable, true)
}
} catch (e: SecurityException) {
@@ -232,7 +222,7 @@ fun CurrentWallpaperPreview(
Card(
modifier = modifier
.fillMaxWidth()
.widthIn(max = 600.dp) // Material 3 guideline: max content width on large screens
.widthIn(max = AppMaxWidths.contentMaxWidth) // Material 3 guideline: max content width on large screens
.padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall),
shape = AppShapes.cardShape,
colors = CardDefaults.cardColors(
@@ -302,7 +292,7 @@ private fun WallpaperPreviewBox(
modifier = modifier
.aspectRatio(aspectRatio)
.border(
width = 3.dp,
width = AppBorderWidths.thick,
color = Color.Black,
shape = AppShapes.imageShape
)
@@ -312,12 +302,12 @@ private fun WallpaperPreviewBox(
AnimatedVisibility(
visible = !isLoading && wallpaper != null,
enter = if (animate) {
fadeIn(animationSpec = tween(300))
fadeIn(animationSpec = tween(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt()))
} else {
fadeIn(animationSpec = tween(0))
},
exit = if (animate) {
fadeOut(animationSpec = tween(300))
fadeOut(animationSpec = tween(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt()))
} else {
fadeOut(animationSpec = tween(0))
}
@@ -326,8 +316,10 @@ private fun WallpaperPreviewBox(
AsyncImage(
model = ImageRequest.Builder(context)
.data(drawable)
.size(Size(600, 1200)) // Limit size for performance - suitable for preview
.size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT)) // Limit size for performance - suitable for preview
.crossfade(true)
.memoryCachePolicy(coil3.request.CachePolicy.DISABLED) // Don't cache in memory (already in drawable)
.diskCachePolicy(coil3.request.CachePolicy.DISABLED) // Don't cache on disk (already system-managed)
.build(),
contentDescription = contentDescription,
contentScale = ContentScale.Crop,
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.wallpaper.components
import com.anthonyla.paperize.core.constants.Constants
import androidx.annotation.StringRes
import androidx.compose.animation.animateContentSize
@@ -24,7 +25,6 @@ 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.core.constants.Constants
import com.anthonyla.paperize.presentation.theme.AppSpacing
import kotlin.math.roundToInt
@@ -128,7 +128,7 @@ fun SettingSwitchWithSlider(
onPercentageChange(homeValue.roundToInt(), it.roundToInt())
},
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
steps = 99
steps = Constants.SLIDER_EFFECT_STEPS
)
}
@@ -161,7 +161,7 @@ fun SettingSwitchWithSlider(
onPercentageChange(it.roundToInt(), lockValue.roundToInt())
},
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
steps = 99
steps = Constants.SLIDER_EFFECT_STEPS
)
}
} else {
@@ -174,13 +174,17 @@ fun SettingSwitchWithSlider(
Text(
text = stringResource(description),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f),
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Text(
text = "${homeValue.roundToInt()}%",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(start = AppSpacing.medium)
)
}
Slider(
@@ -190,7 +194,7 @@ fun SettingSwitchWithSlider(
onPercentageChange(it.roundToInt(), it.roundToInt())
},
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
steps = 99
steps = Constants.SLIDER_EFFECT_STEPS
)
}
}
@@ -1,4 +1,6 @@
package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection
import com.anthonyla.paperize.presentation.theme.AppIconSizes
import com.anthonyla.paperize.presentation.components.OnboardingLayout
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
@@ -32,75 +34,64 @@ fun WallpaperModeSelectionScreen(
) {
var selectedMode by remember { mutableStateOf<WallpaperMode?>(null) }
Column(
modifier = modifier
.fillMaxSize()
.padding(AppSpacing.extraLarge)
.verticalScroll(rememberScrollState()),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "Choose Wallpaper Mode",
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
OnboardingLayout(
icon = Icons.Default.Wallpaper,
title = stringResource(R.string.choose_wallpaper_mode),
modifier = modifier,
content = {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
) {
Text(
text = stringResource(R.string.change_later_in_settings),
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.height(AppSpacing.small))
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = "You can change this later in settings",
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
// Static Mode Card
ModeSelectionCard(
title = stringResource(R.string.static_mode),
description = stringResource(R.string.static_mode_description),
icon = Icons.Default.Wallpaper,
isSelected = selectedMode == WallpaperMode.STATIC,
onClick = { selectedMode = WallpaperMode.STATIC }
)
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Static Mode Card
ModeSelectionCard(
title = "Static Mode",
description = "Classic wallpaper changing using the system wallpaper manager. Simple and battery-efficient. Supports images only.",
icon = Icons.Default.Wallpaper,
isSelected = selectedMode == WallpaperMode.STATIC,
onClick = { selectedMode = WallpaperMode.STATIC }
)
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Live Mode Card
ModeSelectionCard(
title = "Live Wallpaper Mode",
description = "Advanced live wallpaper with hardware-accelerated effects and interactive features (double-tap, parallax).",
icon = Icons.Default.LiveTv,
isSelected = selectedMode == WallpaperMode.LIVE,
onClick = { selectedMode = WallpaperMode.LIVE }
)
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
// Continue button
Button(
onClick = {
selectedMode?.let { mode ->
viewModel.setWallpaperMode(mode)
onModeSelected()
}
},
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
enabled = selectedMode != null
) {
Text(
text = stringResource(R.string.continue_button),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
// Live Mode Card
ModeSelectionCard(
title = stringResource(R.string.live_wallpaper_mode),
description = stringResource(R.string.live_wallpaper_mode_description),
icon = Icons.Default.LiveTv,
isSelected = selectedMode == WallpaperMode.LIVE,
onClick = { selectedMode = WallpaperMode.LIVE }
)
}
},
actions = {
Button(
onClick = {
selectedMode?.let { mode ->
viewModel.setWallpaperMode(mode)
onModeSelected()
}
},
modifier = Modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
enabled = selectedMode != null
) {
Text(
text = stringResource(R.string.continue_button),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.SemiBold,
modifier = Modifier.padding(vertical = AppSpacing.small)
)
}
}
}
)
}
@Composable
@@ -136,7 +127,7 @@ private fun ModeSelectionCard(
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(48.dp),
modifier = Modifier.size(AppIconSizes.large),
tint = if (isSelected)
MaterialTheme.colorScheme.primary
else
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection
import com.anthonyla.paperize.core.constants.Constants
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
@@ -48,48 +48,65 @@ class BootReceiver : BroadcastReceiver() {
val settings = settingsRepository.getScheduleSettings()
if (settings.enableChanger) {
// Check if we have all required albums before scheduling
val homeActive = settings.homeEnabled && settings.homeAlbumId != null
val lockActive = settings.lockEnabled && settings.lockAlbumId != null
val hasRequiredAlbums = when {
settings.homeEnabled && settings.lockEnabled -> homeActive && lockActive
settings.homeEnabled -> homeActive
settings.lockEnabled -> lockActive
else -> false
}
if (hasRequiredAlbums) {
// Reschedule wallpaper changes with WorkManager
val homeInterval: Int
val lockInterval: Int
if (settings.separateSchedules) {
// Separate schedules for home and lock
homeInterval = if (settings.homeEnabled) settings.homeIntervalMinutes else 0
lockInterval = if (settings.lockEnabled) settings.lockIntervalMinutes else 0
// Get wallpaper mode to determine scheduling type
val wallpaperMode = settingsRepository.getWallpaperMode()
if (wallpaperMode == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
// LIVE mode: schedule live wallpaper changes
if (settings.liveAlbumId != null && settings.liveIntervalMinutes > 0) {
wallpaperScheduler.scheduleWallpaperChange(
ScreenType.LIVE,
settings.liveIntervalMinutes
)
Log.d(TAG, "Live wallpaper changes scheduled on boot")
} else {
// Same interval for both (enabled screens)
val interval = settings.homeIntervalMinutes
homeInterval = if (settings.homeEnabled) interval else 0
lockInterval = if (settings.lockEnabled) interval else 0
Log.d(TAG, "Live mode but no album or interval, not scheduling")
}
} else {
// STATIC mode: existing logic
// Check if we have all required albums before scheduling
val homeActive = settings.homeEnabled && settings.homeAlbumId != null
val lockActive = settings.lockEnabled && settings.lockAlbumId != null
val hasRequiredAlbums = when {
settings.homeEnabled && settings.lockEnabled -> homeActive && lockActive
settings.homeEnabled -> homeActive
settings.lockEnabled -> lockActive
else -> false
}
// Determine if screens should be synchronized
val shouldSync = settings.homeEnabled && settings.lockEnabled &&
settings.homeAlbumId != null &&
settings.homeAlbumId == settings.lockAlbumId &&
!settings.separateSchedules
if (hasRequiredAlbums) {
// Reschedule wallpaper changes with WorkManager
val homeInterval: Int
val lockInterval: Int
wallpaperScheduler.scheduleWallpaperChanges(
homeIntervalMinutes = homeInterval,
lockIntervalMinutes = lockInterval,
synchronized = shouldSync,
onlyIfNotScheduled = true // Don't reschedule if already scheduled
)
if (settings.separateSchedules) {
// Separate schedules for home and lock
homeInterval = if (settings.homeEnabled) settings.homeIntervalMinutes else 0
lockInterval = if (settings.lockEnabled) settings.lockIntervalMinutes else 0
} else {
// Same interval for both (enabled screens)
val interval = settings.homeIntervalMinutes
homeInterval = if (settings.homeEnabled) interval else 0
lockInterval = if (settings.lockEnabled) interval else 0
}
Log.d(TAG, "Wallpaper changes rescheduled successfully")
} else {
Log.d(TAG, "Wallpaper changer enabled but required albums not selected, not scheduling")
// Determine if screens should be synchronized
val shouldSync = settings.homeEnabled && settings.lockEnabled &&
settings.homeAlbumId != null &&
settings.homeAlbumId == settings.lockAlbumId &&
!settings.separateSchedules
wallpaperScheduler.scheduleWallpaperChanges(
homeIntervalMinutes = homeInterval,
lockIntervalMinutes = lockInterval,
synchronized = shouldSync,
onlyIfNotScheduled = true // Don't reschedule if already scheduled
)
Log.d(TAG, "Wallpaper changes rescheduled successfully")
} else {
Log.d(TAG, "Wallpaper changer enabled but required albums not selected, not scheduling")
}
}
} else {
Log.d(TAG, "Wallpaper changer disabled, not scheduling")
@@ -31,7 +31,9 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -117,10 +119,24 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
}
}
private val screenOffReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == Intent.ACTION_SCREEN_OFF) {
handleScreenOff()
}
}
}
override fun onCreate(surfaceHolder: SurfaceHolder) {
super.onCreate(surfaceHolder)
Log.d(TAG, "Engine created")
// Enable offset notifications to receive scroll events
setOffsetNotificationsEnabled(true)
// Enable touch events for double-tap gesture detection
setTouchEventsEnabled(true)
savedStateRegistryController.performRestore(null)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
@@ -133,44 +149,47 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
renderer = PaperizeWallpaperRenderer(applicationContext, this)
renderController = object : PaperizeRenderController(renderer, this@PaperizeLiveWallpaperEngine, engineScope) {
override suspend fun openDownloadedCurrentArtwork(): ImageLoader {
override suspend fun openDownloadedCurrentArtwork(): ImageLoader = withContext(Dispatchers.IO) {
val mode = settingsRepository.getWallpaperMode()
val settings = settingsRepository.getScheduleSettings()
val (albumId, screenType) = if (mode == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
Pair(settings.liveAlbumId, ScreenType.LIVE)
} else {
Pair(settings.homeAlbumId, ScreenType.HOME)
// Live Wallpaper only operates in LIVE mode
// In STATIC mode, the static wallpaper worker handles HOME/LOCK screens separately
if (mode != com.anthonyla.paperize.core.WallpaperMode.LIVE) {
Log.d(TAG, "App is in STATIC mode, Live Wallpaper not active")
return@withContext EmptyImageLoader
}
val albumId = settings.liveAlbumId
if (albumId == null) {
Log.w(TAG, "No album ID set for mode $mode")
return EmptyImageLoader
Log.w(TAG, "No live album ID set")
return@withContext EmptyImageLoader
}
// Check if queue exists, build it if empty
val queueCheck = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
val queueCheck = wallpaperRepository.getNextWallpaperInQueue(albumId, ScreenType.LIVE)
if (queueCheck == null) {
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
wallpaperRepository.buildWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled)
}
var wallpaper: Wallpaper? = null
var maxRetries = 10 // Prevent infinite loop
var maxRetries = Constants.MAX_WALLPAPER_LOAD_RETRIES // Prevent infinite loop
var queueRebuildAttempts = 0
while (wallpaper == null && maxRetries > 0) {
// Atomically get and remove from queue
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, ScreenType.LIVE)
if (candidate == null) {
queueRebuildAttempts++
if (queueRebuildAttempts > 2) {
if (queueRebuildAttempts > Constants.MAX_QUEUE_REBUILD_ATTEMPTS) {
Log.w(TAG, "No wallpapers in album $albumId after retries")
return EmptyImageLoader
return@withContext EmptyImageLoader
}
// Rebuild queue
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
wallpaperRepository.buildWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled)
continue
}
@@ -187,16 +206,16 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
if (wallpaper == null) {
Log.w(TAG, "No valid wallpaper found after retries")
return EmptyImageLoader
return@withContext EmptyImageLoader
}
// Check if queue needs refilling
val queueSize = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
if (queueSize == null) {
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
// Peek at queue to see if it needs refilling (not dequeuing, just checking)
val nextInQueue = wallpaperRepository.getNextWallpaperInQueue(albumId, ScreenType.LIVE)
if (nextInQueue == null) {
wallpaperRepository.buildWallpaperQueue(albumId, ScreenType.LIVE, settings.shuffleEnabled)
}
return try {
try {
val uri = wallpaper.uri.toUri()
ContentUriImageLoader(contentResolver, uri)
} catch (e: Exception) {
@@ -207,10 +226,10 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
}
lifecycle.addObserver(renderController)
setEGLContextClientVersion(2)
setEGLContextClientVersion(Constants.GL_ES_VERSION)
setEGLConfigChooser(8, 8, 8, 0, 0, 0)
setRenderer(renderer)
setRenderMode(GLWallpaperService.RENDERMODE_WHEN_DIRTY)
setRenderMode(RENDERMODE_WHEN_DIRTY)
requestRender()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
@@ -222,7 +241,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
// Observe settings changes
observeSettings()
// Register broadcast receiver
// Register broadcast receiver for reload
val filter = IntentFilter(Constants.ACTION_RELOAD_WALLPAPER)
ContextCompat.registerReceiver(
applicationContext,
@@ -230,6 +249,15 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
filter,
ContextCompat.RECEIVER_NOT_EXPORTED
)
// Register screen-off receiver for wallpaper change on screen off
val screenOffFilter = IntentFilter(Intent.ACTION_SCREEN_OFF)
ContextCompat.registerReceiver(
applicationContext,
screenOffReceiver,
screenOffFilter,
ContextCompat.RECEIVER_NOT_EXPORTED
)
}
private fun observeSettings() {
@@ -239,15 +267,23 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
settingsRepository.getWallpaperModeFlow()
) { settings, mode ->
Pair(settings, mode)
}.catch { e ->
Log.e(TAG, "Error observing settings", e)
}.collect { (settings, mode) ->
val (albumId, effects) = if (mode == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
Pair(settings.liveAlbumId, settings.liveEffects)
} else {
Pair(settings.homeAlbumId, settings.homeEffects)
// Only process settings in LIVE mode
// In STATIC mode, the static wallpaper worker handles HOME/LOCK screens
if (mode != com.anthonyla.paperize.core.WallpaperMode.LIVE) {
return@collect
}
val albumId = settings.liveAlbumId
val effects = settings.liveEffects
val scalingType = settings.liveScalingType
renderer.updateEffects(effects)
renderer.updateScalingType(scalingType)
renderer.updateAdaptiveBrightness(settings.adaptiveBrightness)
// Reload if album changed
if (albumId != currentAlbumId) {
Log.d(TAG, "Album changed from $currentAlbumId to $albumId, reloading")
@@ -277,6 +313,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
yPixelOffset: Int
) {
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset)
Log.d(TAG, "onOffsetsChanged: xOffset=$xOffset, xOffsetStep=$xOffsetStep, xPixelOffset=$xPixelOffset")
renderer.setNormalOffsetX(xOffset)
}
@@ -293,7 +330,12 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
try {
applicationContext.unregisterReceiver(reloadReceiver)
} catch (e: Exception) {
Log.e(TAG, "Error unregistering receiver", e)
Log.e(TAG, "Error unregistering reload receiver", e)
}
try {
applicationContext.unregisterReceiver(screenOffReceiver)
} catch (e: Exception) {
Log.e(TAG, "Error unregistering screen-off receiver", e)
}
// Cleanup renderer resources on GL thread
@@ -315,18 +357,25 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
private fun handleDoubleTap() {
engineScope.launch {
val settings = settingsRepository.getScheduleSettings()
val mode = settingsRepository.getWallpaperMode()
val doubleTapEnabled = if (mode == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
settings.liveEffects.enableDoubleTap
} else {
settings.homeEffects.enableDoubleTap
}
// Always check liveEffects since double-tap is only available in live wallpaper mode
val doubleTapEnabled = settings.liveEffects.enableDoubleTap
if (doubleTapEnabled) {
renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate)
}
}
}
private fun handleScreenOff() {
engineScope.launch {
val settings = settingsRepository.getScheduleSettings()
if (settings.liveEffects.enableChangeOnScreenOn) {
Log.d(TAG, "Screen off - changing wallpaper")
// Use forceReload to bypass visibility check and load while screen is off
renderController.forceReloadCurrentArtwork()
}
}
}
}
}
@@ -1,4 +1,5 @@
package com.anthonyla.paperize.service.livewallpaper.gl
import com.anthonyla.paperize.core.constants.Constants
import android.graphics.Bitmap
import android.opengl.GLES20
@@ -12,17 +13,33 @@ import kotlin.math.min
/**
* Represents a picture as a collection of OpenGL textures (tiles).
* Large images are subdivided into 512x512 tiles to avoid texture size limits.
* Based on Muzei's GLPicture implementation.
* Large images are subdivided into tiles to avoid texture size limits.
* Optimized for modern devices (API 31+) with larger tile sizes and pre-allocated buffers.
*
* @property width Original bitmap width
* @property height Original bitmap height
*/
class GLPicture(bitmap: Bitmap) {
class GLPicture(
bitmap: Bitmap,
val brightnessFactor: Float = 1.0f
) {
companion object {
private const val TAG = "GLPicture"
private const val TILE_SIZE = 512
// Use larger tiles for modern devices - reduces draw calls significantly
private const val PREFERRED_TILE_SIZE = 4096
// Cache max texture size to avoid repeated GL queries
@Volatile
private var cachedMaxTextureSize = 0
private fun getOptimalTileSize(): Int {
if (cachedMaxTextureSize == 0) {
cachedMaxTextureSize = GLUtil.getMaxTextureSize()
}
// Use up to 4096 for good memory/performance balance
return min(cachedMaxTextureSize, PREFERRED_TILE_SIZE)
}
}
val width = bitmap.width
@@ -33,8 +50,14 @@ class GLPicture(bitmap: Bitmap) {
private val rows: Int
init {
val maxTextureSize = min(GLUtil.getMaxTextureSize(), 2048)
val tileSize = min(TILE_SIZE, maxTextureSize)
// Validate bitmap before processing
require(!bitmap.isRecycled) { "Cannot create GLPicture from recycled bitmap" }
require(bitmap.width > 0 && bitmap.height > 0) {
"Cannot create GLPicture from bitmap with invalid dimensions: ${bitmap.width}x${bitmap.height}"
}
val maxTextureSize = min(getOptimalTileSize(), Constants.GL_TEXTURE_SIZE_LIMIT)
val tileSize = maxTextureSize
cols = ceil(width.toFloat() / tileSize).toInt()
rows = ceil(height.toFloat() / tileSize).toInt()
@@ -50,59 +73,12 @@ class GLPicture(bitmap: Bitmap) {
val tileWidth = min(tileSize, width - tileX)
val tileHeight = min(tileSize, height - tileY)
// Extract tile bitmap
val tileBitmap = Bitmap.createBitmap(bitmap, tileX, tileY, tileWidth, tileHeight)
// Calculate geometry once at creation time (not per-frame)
val left = -1f + (tileX.toFloat() / width) * 2f
val right = -1f + ((tileX + tileWidth).toFloat() / width) * 2f
val bottom = 1f - ((tileY + tileHeight).toFloat() / height) * 2f
val top = 1f - (tileY.toFloat() / height) * 2f
// Upload to GPU
val textureId = loadTexture(tileBitmap)
// Recycle tile bitmap (no longer needed after GPU upload)
tileBitmap.recycle()
Tile(
textureId = textureId,
x = tileX,
y = tileY,
width = tileWidth,
height = tileHeight
)
}
}
/**
* Draw all tiles to cover the full picture.
*
* @param program Shader program to use
* @param aPositionHandle Attribute location for vertex positions
* @param aTexCoordHandle Attribute location for texture coordinates
* @param surfaceWidth Surface width for coordinate mapping
* @param surfaceHeight Surface height for coordinate mapping
*/
fun draw(
program: Int,
aPositionHandle: Int,
aTexCoordHandle: Int,
@Suppress("UNUSED_PARAMETER") surfaceWidth: Int,
@Suppress("UNUSED_PARAMETER") surfaceHeight: Int
) {
GLES20.glUseProgram(program)
// Enable vertex attribute arrays
GLES20.glEnableVertexAttribArray(aPositionHandle)
GLES20.glEnableVertexAttribArray(aTexCoordHandle)
// Draw each tile
for (tile in tiles) {
// Bind texture
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tile.textureId)
// Calculate normalized device coordinates for this tile
val left = -1f + (tile.x.toFloat() / width) * 2f
val right = -1f + ((tile.x + tile.width).toFloat() / width) * 2f
val bottom = 1f - ((tile.y + tile.height).toFloat() / height) * 2f
val top = 1f - (tile.y.toFloat() / height) * 2f
// Vertex positions (clip space)
val vertices = floatArrayOf(
left, bottom, // Bottom-left
right, bottom, // Bottom-right
@@ -110,7 +86,6 @@ class GLPicture(bitmap: Bitmap) {
right, top // Top-right
)
// Texture coordinates (full tile)
val texCoords = floatArrayOf(
0f, 1f, // Bottom-left
1f, 1f, // Bottom-right
@@ -118,15 +93,62 @@ class GLPicture(bitmap: Bitmap) {
1f, 0f // Top-right
)
// Pre-allocate buffers (reused every frame)
val vertexBuffer = createFloatBuffer(vertices)
val texCoordBuffer = createFloatBuffer(texCoords)
// Set vertex data
// Extract and upload tile bitmap
val tileBitmap = Bitmap.createBitmap(bitmap, tileX, tileY, tileWidth, tileHeight)
val textureId = loadTexture(tileBitmap)
tileBitmap.recycle()
Tile(
textureId = textureId,
x = tileX,
y = tileY,
width = tileWidth,
height = tileHeight,
vertexBuffer = vertexBuffer,
texCoordBuffer = texCoordBuffer
)
}
}
/**
* Draw all tiles to cover the full picture.
* Uses pre-allocated buffers for optimal performance (zero allocations per frame).
*
* @param program Shader program to use
* @param aPositionHandle Attribute location for vertex positions
* @param aTexCoordHandle Attribute location for texture coordinates
*/
fun draw(
program: Int,
aPositionHandle: Int,
aTexCoordHandle: Int,
mvpMatrix: FloatArray,
uMvpMatrixHandle: Int
) {
GLES20.glUseProgram(program)
// Enable vertex attribute arrays
GLES20.glEnableVertexAttribArray(aPositionHandle)
GLES20.glEnableVertexAttribArray(aTexCoordHandle)
// Pass MVP matrix
GLES20.glUniformMatrix4fv(uMvpMatrixHandle, 1, false, mvpMatrix, 0)
// Draw each tile using pre-allocated buffers (no per-frame allocation)
for (tile in tiles) {
// Bind texture
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tile.textureId)
// Use pre-allocated buffers - no allocation here!
GLES20.glVertexAttribPointer(
aPositionHandle, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer
aPositionHandle, 2, GLES20.GL_FLOAT, false, 0, tile.vertexBuffer
)
GLES20.glVertexAttribPointer(
aTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, texCoordBuffer
aTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, tile.texCoordBuffer
)
// Draw quad
@@ -194,14 +216,16 @@ class GLPicture(bitmap: Bitmap) {
}
/**
* Represents a single tile of the picture.
* Represents a single tile of the picture with pre-allocated GPU buffers.
*/
private data class Tile(
val textureId: Int,
val x: Int,
val y: Int,
val width: Int,
val height: Int
val height: Int,
val vertexBuffer: FloatBuffer,
val texCoordBuffer: FloatBuffer
)
override fun toString(): String {
@@ -98,10 +98,6 @@ abstract class GLWallpaperService : WallpaperService() {
glThread?.queueEvent(runnable)
}
override fun onCreate(surfaceHolder: SurfaceHolder) {
super.onCreate(surfaceHolder)
}
override fun onSurfaceCreated(holder: SurfaceHolder) {
super.onSurfaceCreated(holder)
@@ -395,7 +391,8 @@ abstract class GLWallpaperService : WallpaperService() {
0x0004 // EGL_OPENGL_ES2_BIT
}
val configSpec = intArrayOf(
// Try with EGL_RENDERABLE_TYPE
var configSpec = intArrayOf(
EGL10.EGL_RED_SIZE, redSize,
EGL10.EGL_GREEN_SIZE, greenSize,
EGL10.EGL_BLUE_SIZE, blueSize,
@@ -408,7 +405,20 @@ abstract class GLWallpaperService : WallpaperService() {
val numConfig = IntArray(1)
if (!egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) {
throw RuntimeException("eglChooseConfig failed")
Log.w(TAG, "eglChooseConfig failed with EGL_RENDERABLE_TYPE, retrying without it")
// Fallback: Try without EGL_RENDERABLE_TYPE
configSpec = intArrayOf(
EGL10.EGL_RED_SIZE, redSize,
EGL10.EGL_GREEN_SIZE, greenSize,
EGL10.EGL_BLUE_SIZE, blueSize,
EGL10.EGL_ALPHA_SIZE, alphaSize,
EGL10.EGL_DEPTH_SIZE, depthSize,
EGL10.EGL_STENCIL_SIZE, stencilSize,
EGL10.EGL_NONE
)
if (!egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) {
throw RuntimeException("eglChooseConfig failed")
}
}
if (numConfig[0] <= 0) {
@@ -3,7 +3,6 @@ package com.anthonyla.paperize.service.livewallpaper.renderer
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import kotlin.math.max
/**
* Geometry utilities for OpenGL rendering including vertex positions,
@@ -35,67 +34,7 @@ object GLGeometry {
1.0f, 0.0f // Top-right
)
/**
* Calculate texture coordinates with adaptive parallax offset.
* The parallax effect pans the image based on home screen scroll position.
*
* @param normalOffsetX Normalized scroll offset (0.0 = leftmost, 1.0 = rightmost)
* @param parallaxIntensity User setting (0-100, percentage of maximum parallax)
* @param imageWidth Original image width in pixels
* @param imageHeight Original image height in pixels
* @param surfaceWidth Surface width in pixels
* @param surfaceHeight Surface height in pixels
* @return Texture coordinate array with parallax offset applied
*/
fun calculateParallaxTexCoords(
normalOffsetX: Float,
parallaxIntensity: Int,
imageWidth: Int,
imageHeight: Int,
surfaceWidth: Int,
surfaceHeight: Int
): FloatArray {
if (parallaxIntensity == 0) {
return TEX_COORDS.clone()
}
// Calculate aspect ratios
val imageAspect = imageWidth.toFloat() / imageHeight
val surfaceAspect = surfaceWidth.toFloat() / surfaceHeight
// Determine how much the image needs to be scaled to fill the surface
// while maintaining aspect ratio
val scaleFactor = if (imageAspect > surfaceAspect) {
// Image is wider than surface - scale by height
1.0f
} else {
// Image is narrower than surface - scale by width to fill
surfaceAspect / imageAspect
}
// Calculate how much extra width we have for parallax
// This is the difference between scaled width and visible width
val extraWidth = max(0f, scaleFactor - 1.0f)
// Apply parallax intensity (0-100% of available extra width)
val parallaxAmount = extraWidth * (parallaxIntensity / 100.0f)
// Map scroll position (0-1) to texture coordinate offset
// Center position (0.5) shows middle of image
// Left position (0.0) shows left side, right (1.0) shows right side
val offset = parallaxAmount * (normalOffsetX - 0.5f)
// Calculate texture coordinate bounds with offset
val left = 0.0f - offset
val right = 1.0f - offset
return floatArrayOf(
left, 1.0f, // Bottom-left
right, 1.0f, // Bottom-right
left, 0.0f, // Top-left
right, 0.0f // Top-right
)
}
/**
* Create a native-order FloatBuffer from a float array.
@@ -11,12 +11,13 @@ object GLShaders {
* Used for all rendering passes.
*/
const val VERTEX_SHADER = """
uniform mat4 u_mvpMatrix;
attribute vec4 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
gl_Position = a_position;
gl_Position = u_mvpMatrix * a_position;
v_texCoord = a_texCoord;
}
"""
@@ -39,7 +40,8 @@ object GLShaders {
/**
* Fragment shader for horizontal Gaussian blur pass.
* Uses 9-tap kernel for good quality and performance.
* Uses 9-tap kernel with branchless design for optimal GPU performance.
* Weights are pre-computed for sigma ~= 2.0.
*/
const val BLUR_HORIZONTAL_FRAGMENT_SHADER = """
precision mediump float;
@@ -49,32 +51,24 @@ object GLShaders {
varying vec2 v_texCoord;
void main() {
if (u_blurRadius < 0.01) {
// No blur, pass through
gl_FragColor = texture2D(u_texture, v_texCoord);
return;
}
vec2 pixelSize = 1.0 / u_resolution;
vec4 color = vec4(0.0);
// 9-tap Gaussian weights (sigma ~= 2.0) - ES 2.0 compatible
float weights[9];
weights[0] = 0.0204;
weights[1] = 0.0577;
weights[2] = 0.1215;
weights[3] = 0.1899;
weights[4] = 0.2210;
weights[5] = 0.1899;
weights[6] = 0.1215;
weights[7] = 0.0577;
weights[8] = 0.0204;
// Sample center pixel
vec4 center = texture2D(u_texture, v_texCoord);
// Horizontal blur
for (int i = -4; i <= 4; i++) {
vec2 offset = vec2(float(i) * pixelSize.x * u_blurRadius, 0.0);
color += texture2D(u_texture, v_texCoord + offset) * weights[i + 4];
}
// 9-tap Gaussian blur (branchless - when radius is 0, offsets are 0)
vec4 color = center * 0.2210;
// Symmetric pairs for efficiency
float r = u_blurRadius;
color += (texture2D(u_texture, v_texCoord + vec2(-4.0 * pixelSize.x * r, 0.0)) +
texture2D(u_texture, v_texCoord + vec2( 4.0 * pixelSize.x * r, 0.0))) * 0.0204;
color += (texture2D(u_texture, v_texCoord + vec2(-3.0 * pixelSize.x * r, 0.0)) +
texture2D(u_texture, v_texCoord + vec2( 3.0 * pixelSize.x * r, 0.0))) * 0.0577;
color += (texture2D(u_texture, v_texCoord + vec2(-2.0 * pixelSize.x * r, 0.0)) +
texture2D(u_texture, v_texCoord + vec2( 2.0 * pixelSize.x * r, 0.0))) * 0.1215;
color += (texture2D(u_texture, v_texCoord + vec2(-1.0 * pixelSize.x * r, 0.0)) +
texture2D(u_texture, v_texCoord + vec2( 1.0 * pixelSize.x * r, 0.0))) * 0.1899;
gl_FragColor = color;
}
@@ -82,7 +76,7 @@ object GLShaders {
/**
* Fragment shader for vertical Gaussian blur pass.
* Uses 9-tap kernel matching horizontal pass.
* Uses 9-tap kernel with branchless design matching horizontal pass.
*/
const val BLUR_VERTICAL_FRAGMENT_SHADER = """
precision mediump float;
@@ -93,25 +87,23 @@ object GLShaders {
void main() {
vec2 pixelSize = 1.0 / u_resolution;
vec4 color = vec4(0.0);
// 9-tap Gaussian weights (sigma ~= 2.0) - ES 2.0 compatible
float weights[9];
weights[0] = 0.0204;
weights[1] = 0.0577;
weights[2] = 0.1215;
weights[3] = 0.1899;
weights[4] = 0.2210;
weights[5] = 0.1899;
weights[6] = 0.1215;
weights[7] = 0.0577;
weights[8] = 0.0204;
// Sample center pixel
vec4 center = texture2D(u_texture, v_texCoord);
// Vertical blur
for (int i = -4; i <= 4; i++) {
vec2 offset = vec2(0.0, float(i) * pixelSize.y * u_blurRadius);
color += texture2D(u_texture, v_texCoord + offset) * weights[i + 4];
}
// 9-tap Gaussian blur (branchless - when radius is 0, offsets are 0)
vec4 color = center * 0.2210;
// Symmetric pairs for efficiency
float r = u_blurRadius;
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -4.0 * pixelSize.y * r)) +
texture2D(u_texture, v_texCoord + vec2(0.0, 4.0 * pixelSize.y * r))) * 0.0204;
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.0 * pixelSize.y * r)) +
texture2D(u_texture, v_texCoord + vec2(0.0, 3.0 * pixelSize.y * r))) * 0.0577;
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.0 * pixelSize.y * r)) +
texture2D(u_texture, v_texCoord + vec2(0.0, 2.0 * pixelSize.y * r))) * 0.1215;
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.0 * pixelSize.y * r)) +
texture2D(u_texture, v_texCoord + vec2(0.0, 1.0 * pixelSize.y * r))) * 0.1899;
gl_FragColor = color;
}
@@ -119,7 +111,7 @@ object GLShaders {
/**
* Fragment shader for color effects (darken, vignette, grayscale).
* Applied after blur passes.
* Applied after blur passes. Uses branchless math for optimal GPU performance.
*/
const val EFFECTS_FRAGMENT_SHADER = """
precision mediump float;
@@ -127,31 +119,33 @@ object GLShaders {
uniform float u_alpha;
uniform float u_darkenFactor;
uniform float u_vignetteFactor;
uniform float u_grayscaleEnabled;
uniform float u_grayscaleFactor;
uniform float u_adaptiveBrightnessFactor;
varying vec2 v_texCoord;
void main() {
vec4 color = texture2D(u_texture, v_texCoord);
// 1. Apply darken (brightness adjustment)
if (u_darkenFactor < 0.99) {
color.rgb *= u_darkenFactor;
}
// 2. Apply vignette (radial gradient)
if (u_vignetteFactor > 0.01) {
vec2 center = v_texCoord - 0.5;
float dist = length(center);
float vignette = smoothstep(0.7, 0.2, dist * (1.0 + u_vignetteFactor));
color.rgb *= vignette;
}
// 3. Apply grayscale (luminance calculation)
if (u_grayscaleEnabled > 0.5) {
// ITU-R BT.709 standard
float gray = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));
color.rgb = vec3(gray);
}
// 1. Apply darken (branchless - when factor is 0, multiplier is 1.0)
color.rgb *= (1.0 - u_darkenFactor);
// 2. Apply vignette (branchless using mix)
// When vignetteFactor is 0, the vignette calculation still runs but
// the smoothstep result approaches 1.0 everywhere, so color is unchanged
vec2 center = v_texCoord - 0.5;
float dist = length(center);
float vignette = 1.0 - smoothstep(0.3, 0.9, dist * (1.0 + u_vignetteFactor * 2.0));
// Mix between original (1.0) and vignette based on factor
float vignetteMultiplier = mix(1.0, vignette, u_vignetteFactor);
color.rgb *= vignetteMultiplier;
// 3. Apply grayscale (branchless - mix handles factor 0 correctly)
// ITU-R BT.709 standard luminance calculation
float gray = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));
color.rgb = mix(color.rgb, vec3(gray), u_grayscaleFactor);
// 4. Apply adaptive brightness multiplier
color.rgb *= u_adaptiveBrightnessFactor;
gl_FragColor = vec4(color.rgb, color.a * u_alpha);
}
@@ -54,6 +54,19 @@ class ContentUriImageLoader(
override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? {
return withContext(Dispatchers.IO) {
try {
// First verify the URI is accessible
val isAccessible = try {
contentResolver.openInputStream(uri)?.use { true } ?: false
} catch (e: Exception) {
Log.w(TAG, "URI not accessible: $uri", e)
false
}
if (!isAccessible) {
Log.w(TAG, "Image not accessible or doesn't exist: $uri")
return@withContext null
}
// Get image dimensions without loading pixel data
val dimensions = getImageDimensions() ?: return@withContext null
@@ -71,37 +84,44 @@ class ContentUriImageLoader(
// Load bitmap with sampling
val source = ImageDecoder.createSource(contentResolver, uri)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSampleSize(sampleSize)
decoder.isMutableRequired = false // Immutable for GPU upload
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
}
// Validate loaded bitmap
if (bitmap.width <= 0 || bitmap.height <= 0) {
Log.e(TAG, "Loaded bitmap has invalid dimensions: ${bitmap.width}x${bitmap.height}")
bitmap.recycle()
return@withContext null
}
bitmap
} catch (e: Exception) {
Log.e(TAG, "Failed to load image from $uri", e)
null
} catch (e: OutOfMemoryError) {
Log.e(TAG, "OOM loading image from $uri", e)
null
}
}
}
/**
* Get image dimensions without loading the full bitmap.
* Uses BitmapFactory with inJustDecodeBounds to avoid allocating pixel data.
*/
private fun getImageDimensions(): Pair<Int, Int>? {
return try {
val source = ImageDecoder.createSource(contentResolver, uri)
var width = 0
var height = 0
ImageDecoder.decodeDrawable(source) { decoder, info, _ ->
width = info.size.width
height = info.size.height
decoder.setTargetSampleSize(Int.MAX_VALUE) // Don't load pixel data
}
if (width > 0 && height > 0) {
Pair(width, height)
} else {
null
contentResolver.openInputStream(uri)?.use { inputStream ->
val options = android.graphics.BitmapFactory.Options().apply {
inJustDecodeBounds = true
}
android.graphics.BitmapFactory.decodeStream(inputStream, null, options)
val width = options.outWidth
val height = options.outHeight
if (width > 0 && height > 0) Pair(width, height) else null
}
} catch (e: Exception) {
Log.e(TAG, "Failed to get image dimensions for $uri", e)
@@ -133,7 +153,7 @@ class ContentUriImageLoader(
}
// Guard against invalid source dimensions
if (width <=0 || height <= 0) {
if (width <= 0 || height <= 0) {
Log.w(TAG, "Invalid source dimensions: ${width}x${height}")
return 1
}
@@ -152,7 +172,8 @@ class ContentUriImageLoader(
}
}
// Ensure we don't downsample below target size
return max(1, sampleSize / 2)
// Return the calculated sample size (it is already the largest power-of-2
// that keeps dimensions larger than or equal to target)
return max(1, sampleSize)
}
}
@@ -3,9 +3,11 @@ package com.anthonyla.paperize.service.livewallpaper.renderer
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.anthonyla.paperize.core.constants.Constants
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
/**
@@ -21,7 +23,7 @@ abstract class PaperizeRenderController(
companion object {
private const val TAG = "PaperizeRenderController"
private const val RELOAD_THROTTLE_MS = 250L
private const val RELOAD_THROTTLE_MS = Constants.RELOAD_THROTTLE_MS
}
/**
@@ -99,9 +101,34 @@ abstract class PaperizeRenderController(
}
/**
* Execute wallpaper reload.
* Force reload the current wallpaper, bypassing visibility check.
* Used for screen-off wallpaper changes where we want to load
* the next wallpaper while the screen is dark.
* Skips crossfade animation since screen is off and animation wouldn't be visible.
*/
private fun executeReload() {
fun forceReloadCurrentArtwork() {
Log.d(TAG, "forceReloadCurrentArtwork: visible=$visible, loading=$isLoading")
// Clear any pending reload since we're forcing a reload now
hasPendingReload = false
// If already loading, skip
if (isLoading) {
Log.d(TAG, "Already loading, skipping force reload")
return
}
throttleJob?.cancel()
// Skip crossfade since screen is off - wallpaper will appear instantly when screen turns on
executeReload(skipCrossfade = true)
}
/**
* Execute wallpaper reload.
*
* @param skipCrossfade If true, skip crossfade animation and instantly swap wallpaper
*/
private fun executeReload(skipCrossfade: Boolean = false) {
isLoading = true
controllerScope.launch {
@@ -109,12 +136,17 @@ abstract class PaperizeRenderController(
// Get image loader from service
val loader = openDownloadedCurrentArtwork()
// Check for cancellation before passing to renderer
if (!isActive) return@launch
// Queue wallpaper loading on renderer
// Renderer will load bitmap in background and upload to GPU on GL thread
renderer.queueWallpaper(loader)
renderer.queueWallpaper(loader, skipCrossfade)
} catch (e: Exception) {
Log.e(TAG, "Error reloading wallpaper", e)
if (isActive) {
Log.e(TAG, "Error reloading wallpaper", e)
}
} finally {
isLoading = false
}
@@ -1,4 +1,6 @@
package com.anthonyla.paperize.service.livewallpaper.renderer
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.ScalingType
import android.content.Context
import android.graphics.Bitmap
@@ -13,7 +15,11 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.isActive
import kotlinx.coroutines.Job
import kotlinx.coroutines.CancellationException
import java.nio.FloatBuffer
import android.opengl.Matrix
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
@@ -32,7 +38,8 @@ class PaperizeWallpaperRenderer(
companion object {
private const val TAG = "PaperizeRenderer"
private const val CROSSFADE_DURATION_FRAMES = 45 // 0.75s at 60fps
// Time-based crossfade duration in milliseconds (consistent across all refresh rates)
private const val CROSSFADE_DURATION_MS = Constants.CROSSFADE_DURATION_MS
}
/**
@@ -47,6 +54,9 @@ class PaperizeWallpaperRenderer(
@Volatile private var surfaceWidth = 0
@Volatile private var surfaceHeight = 0
// Display refresh rate (for future optimizations)
private var displayRefreshRate = 60f
// Shader programs
private var simpleProgram = 0
private var blurHorizontalProgram = 0
@@ -57,25 +67,46 @@ class PaperizeWallpaperRenderer(
private var aPositionHandle = 0
private var aTexCoordHandle = 0
private var uTextureHandle = 0
private var uMvpMatrixHandle = 0
private var uAlphaHandle = 0
private var uDarkenFactorHandle = 0
private var uVignetteFactorHandle = 0
private var uGrayscaleEnabledHandle = 0
private var uGrayscaleFactorHandle = 0
private var uAdaptiveBrightnessFactorHandle = 0
// Cached uniform locations for horizontal blur program
private var blurHPositionHandle = 0
private var blurHTexCoordHandle = 0
private var blurHMvpMatrixHandle = 0
private var blurHTextureHandle = 0
private var blurHResolutionHandle = 0
private var blurHRadiusHandle = 0
// Cached uniform locations for vertical blur program
private var blurVPositionHandle = 0
private var blurVTexCoordHandle = 0
private var blurVMvpMatrixHandle = 0
private var blurVTextureHandle = 0
private var blurVResolutionHandle = 0
private var blurVRadiusHandle = 0
// Geometry buffers
private lateinit var vertexBuffer: FloatBuffer
private lateinit var texCoordBuffer: FloatBuffer
// Framebuffer for two-pass blur
private var blurFbo = 0
private var blurTexture = 0
// Framebuffers for two-pass blur (need two for proper blur + effects pipeline)
private var blurFbo1 = 0
private var blurTexture1 = 0
private var blurFbo2 = 0
private var blurTexture2 = 0
// Current wallpaper
private var currentPicture: GLPicture? = null
// Crossfade state
// Crossfade state (time-based)
private var nextPicture: GLPicture? = null
private var crossfadeProgress = 0f
private var crossfadeStartTimeNanos = 0L
// Effects
@Volatile private var currentEffects = WallpaperEffects()
@@ -83,8 +114,21 @@ class PaperizeWallpaperRenderer(
// Parallax
@Volatile private var normalOffsetX = 0.5f
// Scaling
@Volatile private var currentScalingType = ScalingType.FILL
// Adaptive brightness (from ScheduleSettings)
@Volatile private var adaptiveBrightnessEnabled = false
// Matrices
private val mvpMatrix = FloatArray(16)
private val projectionMatrix = FloatArray(16)
private val viewMatrix = FloatArray(16)
private val identityMatrix = FloatArray(16)
// Coroutine scope for background loading
private val loadingScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private var currentLoadJob: Job? = null
override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
Log.d(TAG, "onSurfaceCreated")
@@ -103,6 +147,9 @@ class PaperizeWallpaperRenderer(
vertexBuffer = GLGeometry.createFloatBuffer(GLGeometry.VERTICES)
texCoordBuffer = GLGeometry.createFloatBuffer(GLGeometry.TEX_COORDS)
// Initialize identity matrix
Matrix.setIdentityM(identityMatrix, 0)
Log.d(TAG, "Surface created successfully")
}
@@ -114,14 +161,19 @@ class PaperizeWallpaperRenderer(
GLES20.glViewport(0, 0, width, height)
// Recreate framebuffer for blur at new resolution
createBlurFramebuffer(width, height)
// Recreate framebuffers for blur at new resolution
createBlurFramebuffers(width, height)
}
override fun onDrawFrame(gl: GL10) {
// Clear screen
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
// Prevent division by zero in shaders if surface dimensions are invalid
if (surfaceWidth <= 0 || surfaceHeight <= 0) {
return
}
val current = currentPicture
val next = nextPicture
@@ -132,7 +184,7 @@ class PaperizeWallpaperRenderer(
// Determine if we need blur
val blurRadius = if (currentEffects.enableBlur) {
(currentEffects.blurPercentage / 100.0f) * 25.0f
(currentEffects.blurPercentage / 100.0f) * Constants.MAX_BLUR_RADIUS
} else {
0f
}
@@ -145,10 +197,19 @@ class PaperizeWallpaperRenderer(
// Draw next picture (if crossfading)
next?.let { picture ->
// Safety: If crossfade just started but timer wasn't set, set it now
if (crossfadeStartTimeNanos == 0L) {
crossfadeStartTimeNanos = System.nanoTime()
}
// Draw next picture with its own alpha
drawPictureWithEffects(picture, crossfadeProgress, blurRadius)
// Update crossfade progress
crossfadeProgress += (1f / CROSSFADE_DURATION_FRAMES)
// Update crossfade progress using time-based calculation
// This ensures consistent animation duration regardless of refresh rate (60Hz, 90Hz, 120Hz, etc.)
val currentTimeNanos = System.nanoTime()
val elapsedMs = (currentTimeNanos - crossfadeStartTimeNanos) / 1_000_000f
crossfadeProgress = (elapsedMs / CROSSFADE_DURATION_MS).coerceIn(0f, 1f)
if (crossfadeProgress >= 1.0f) {
// Crossfade complete
@@ -156,6 +217,7 @@ class PaperizeWallpaperRenderer(
currentPicture = picture
nextPicture = null
crossfadeProgress = 0f
crossfadeStartTimeNanos = 0L
Log.d(TAG, "Crossfade complete")
} else {
// Continue animating
@@ -168,10 +230,10 @@ class PaperizeWallpaperRenderer(
* Draw a picture with full effects pipeline.
*/
private fun drawPictureWithEffects(picture: GLPicture, alpha: Float, blurRadius: Float) {
// Update texture coordinates for parallax
updateTextureCoordinates(picture)
// Calculate MVP matrix for Center Crop + Parallax
calculateMvpMatrix(picture, mvpMatrix)
if (blurRadius > 0.01f && currentEffects.enableBlur) {
if (blurRadius > Constants.BLUR_MIN_THRESHOLD && currentEffects.enableBlur) {
// Two-pass blur pipeline
drawWithBlur(picture, alpha, blurRadius)
} else {
@@ -181,54 +243,68 @@ class PaperizeWallpaperRenderer(
}
/**
* Draw picture with two-pass blur followed by color effects.
* Draw picture with proper 3-pass blur + effects pipeline.
* Pass 1: Source texture → Horizontal blur → FBO1
* Pass 2: FBO1 texture → Vertical blur → FBO2
* Pass 3: FBO2 texture → Color effects → Screen
*/
private fun drawWithBlur(picture: GLPicture, alpha: Float, blurRadius: Float) {
// Pass 1: Horizontal blur to FBO
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo)
// Pass 1: Horizontal blur (source → FBO1)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo1)
GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight)
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
GLES20.glUseProgram(blurHorizontalProgram)
val blurHResHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_resolution")
val blurHRadiusHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_blurRadius")
GLES20.glUniform2f(blurHResHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat())
GLES20.glUniform2f(blurHResolutionHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat())
GLES20.glUniform1f(blurHRadiusHandle, blurRadius)
GLES20.glUniform1i(blurHTextureHandle, 0) // Bind texture unit 0
picture.draw(blurHorizontalProgram, aPositionHandle, aTexCoordHandle, surfaceWidth, surfaceHeight)
picture.draw(blurHorizontalProgram, blurHPositionHandle, blurHTexCoordHandle, mvpMatrix, blurHMvpMatrixHandle)
// Pass 2: Vertical blur from FBO to another FBO (not screen yet)
// We need the blur result as a texture to apply color effects
// Pass 2: Vertical blur (FBO1 → FBO2)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo2)
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
GLES20.glUseProgram(blurVerticalProgram)
GLES20.glUniform2f(blurVResolutionHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat())
GLES20.glUniform1f(blurVRadiusHandle, blurRadius)
// Bind horizontal blur result as input texture
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture1)
GLES20.glUniform1i(blurVTextureHandle, 0)
// Draw full-screen quad for vertical blur pass (Identity matrix)
drawQuad(blurVPositionHandle, blurVTexCoordHandle, blurVMvpMatrixHandle, identityMatrix)
// Pass 3: Color effects (FBO2 → Screen)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0)
GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight)
GLES20.glUseProgram(blurVerticalProgram)
val blurVResHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_resolution")
val blurVRadiusHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_blurRadius")
val blurVTextureHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_texture")
GLES20.glUniform2f(blurVResHandle, surfaceWidth.toFloat(), surfaceHeight.toFloat())
GLES20.glUniform1f(blurVRadiusHandle, blurRadius)
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture)
GLES20.glUniform1i(blurVTextureHandle, 0)
// For now, render directly to screen with effects applied
// In a more optimized version, we'd render to another FBO and apply effects in pass 3
GLES20.glUseProgram(effectsProgram)
// Set color effect uniforms
// Set color effect uniforms - respect enable flags
GLES20.glUniform1f(uAlphaHandle, alpha)
GLES20.glUniform1f(uDarkenFactorHandle, (100 - currentEffects.darkenPercentage) / 100f)
GLES20.glUniform1f(uVignetteFactorHandle, currentEffects.vignettePercentage / 100f)
GLES20.glUniform1f(uGrayscaleEnabledHandle, if (currentEffects.enableGrayscale) 1f else 0f)
GLES20.glUniform1f(
uDarkenFactorHandle,
if (currentEffects.enableDarken) currentEffects.darkenPercentage / Constants.PERCENTAGE_DIVISOR else 0f
)
GLES20.glUniform1f(
uVignetteFactorHandle,
if (currentEffects.enableVignette) currentEffects.vignettePercentage / Constants.PERCENTAGE_DIVISOR else 0f
)
GLES20.glUniform1f(
uGrayscaleFactorHandle,
if (currentEffects.enableGrayscale) currentEffects.grayscalePercentage / Constants.PERCENTAGE_DIVISOR else 0f
)
GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, picture.brightnessFactor)
// Bind the blurred texture
// Bind the fully blurred texture as input
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture2)
GLES20.glUniform1i(uTextureHandle, 0)
drawQuad()
drawQuad(aPositionHandle, aTexCoordHandle, uMvpMatrixHandle, identityMatrix)
}
/**
@@ -238,45 +314,132 @@ class PaperizeWallpaperRenderer(
// Render to screen with effects
GLES20.glUseProgram(effectsProgram)
// Set uniforms
// Set uniforms - respect enable flags for all effects
GLES20.glUniform1f(uAlphaHandle, alpha)
GLES20.glUniform1f(uDarkenFactorHandle, (100 - currentEffects.darkenPercentage) / 100f)
GLES20.glUniform1f(uVignetteFactorHandle, currentEffects.vignettePercentage / 100f)
GLES20.glUniform1f(uGrayscaleEnabledHandle, if (currentEffects.enableGrayscale) 1f else 0f)
GLES20.glUniform1f(
uDarkenFactorHandle,
if (currentEffects.enableDarken) currentEffects.darkenPercentage / Constants.PERCENTAGE_DIVISOR else 0f
)
GLES20.glUniform1f(
uVignetteFactorHandle,
if (currentEffects.enableVignette) currentEffects.vignettePercentage / Constants.PERCENTAGE_DIVISOR else 0f
)
GLES20.glUniform1f(
uGrayscaleFactorHandle,
if (currentEffects.enableGrayscale) currentEffects.grayscalePercentage / Constants.PERCENTAGE_DIVISOR else 0f
)
GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, picture.brightnessFactor)
picture.draw(effectsProgram, aPositionHandle, aTexCoordHandle, surfaceWidth, surfaceHeight)
picture.draw(effectsProgram, aPositionHandle, aTexCoordHandle, mvpMatrix, uMvpMatrixHandle)
}
/**
* Update texture coordinates for parallax effect.
* Calculate MVP matrix for Center Crop scaling and Parallax.
*/
private fun updateTextureCoordinates(picture: GLPicture) {
if (!currentEffects.enableParallax || currentEffects.parallaxIntensity == 0) {
// No parallax - use standard coordinates
GLGeometry.updateFloatBuffer(texCoordBuffer, GLGeometry.TEX_COORDS)
private fun calculateMvpMatrix(picture: GLPicture, matrix: FloatArray) {
val viewWidth = surfaceWidth.toFloat()
val viewHeight = surfaceHeight.toFloat()
val imageWidth = picture.width.toFloat()
val imageHeight = picture.height.toFloat()
if (viewWidth == 0f || viewHeight == 0f || imageWidth == 0f || imageHeight == 0f) {
Matrix.setIdentityM(matrix, 0)
return
}
// Calculate parallax coordinates
val parallaxCoords = GLGeometry.calculateParallaxTexCoords(
normalOffsetX,
currentEffects.parallaxIntensity,
picture.width,
picture.height,
surfaceWidth,
surfaceHeight
)
// 1. Calculate scale based on ScalingType
val scaleX = viewWidth / imageWidth
val scaleY = viewHeight / imageHeight
GLGeometry.updateFloatBuffer(texCoordBuffer, parallaxCoords)
val (finalScaleX, finalScaleY) = when (currentScalingType) {
ScalingType.FILL -> {
val scale = kotlin.math.max(scaleX, scaleY)
Pair(scale, scale)
}
ScalingType.FIT -> {
val scale = kotlin.math.min(scaleX, scaleY)
Pair(scale, scale)
}
ScalingType.STRETCH -> {
Pair(scaleX, scaleY)
}
ScalingType.NONE -> {
Pair(1f, 1f)
}
}
var effectiveScaleX = finalScaleX
var effectiveScaleY = finalScaleY
val parallaxEnabled = currentEffects.enableParallax && currentEffects.parallaxIntensity > 0
val parallaxIntensity = if (parallaxEnabled) currentEffects.parallaxIntensity / 100f else 0f
// If parallax is enabled, ensure we have enough width to scroll (overscan).
// If image fits perfectly, apply artificial zoom based on intensity.
if (parallaxEnabled) {
val currentWidth = imageWidth * effectiveScaleX
// Target at least 20% overscan at max intensity
val minExtraWidth = viewWidth * parallaxIntensity * 0.2f
if ((currentWidth - viewWidth) < minExtraWidth) {
// Zoom in to create scrollable area
val targetWidth = viewWidth + minExtraWidth
// Prevent division by zero
if (currentWidth > 0) {
val zoomFactor = targetWidth / currentWidth
effectiveScaleX *= zoomFactor
effectiveScaleY *= zoomFactor
}
}
}
val scaledWidth = imageWidth * effectiveScaleX
val scaledHeight = imageHeight * effectiveScaleY
// 2. Calculate parallax offset
// Available scroll range is the difference between scaled image width and screen width
val extraWidth = kotlin.math.max(0f, scaledWidth - viewWidth)
// Calculate offset based on scroll position (0.0 = left, 1.0 = right)
// Center (0.5) is 0 offset
// Reverting to: `maxParallaxOffset = extraWidth`.
// And relying on the "Zoom" logic to create that width if needed.
val maxParallaxOffset = extraWidth
val parallaxOffset = maxParallaxOffset * (0.5f - normalOffsetX)
// Verbose logging removed to avoid per-frame log spam
// 3. Construct Matrix
// We use an orthographic projection matching the screen dimensions
// Left: -width/2, Right: width/2, Bottom: -height/2, Top: height/2
// This makes 0,0 the center of the screen
Matrix.orthoM(projectionMatrix, 0, -viewWidth / 2f, viewWidth / 2f, -viewHeight / 2f, viewHeight / 2f, -1f, 1f)
// Set view matrix (camera) - identity is fine for 2D
Matrix.setIdentityM(viewMatrix, 0)
// Combine Projection * View
Matrix.multiplyMM(matrix, 0, projectionMatrix, 0, viewMatrix, 0)
// Apply Model transformations
// Translate for parallax
Matrix.translateM(matrix, 0, parallaxOffset, 0f, 0f)
// Scale to match image size * crop scale
// The quad is -1 to 1 (size 2), so we need to scale it to match image dimensions
// Actually, we want to map the quad (-1..1) to the image size (-w/2..w/2)
Matrix.scaleM(matrix, 0, scaledWidth / 2f, scaledHeight / 2f, 1f)
}
/**
* Draw a full-screen quad with current buffers.
*/
private fun drawQuad() {
private fun drawQuad(aPositionHandle: Int, aTexCoordHandle: Int, uMvpMatrixHandle: Int, mvpMatrix: FloatArray) {
GLES20.glEnableVertexAttribArray(aPositionHandle)
GLES20.glEnableVertexAttribArray(aTexCoordHandle)
GLES20.glUniformMatrix4fv(uMvpMatrixHandle, 1, false, mvpMatrix, 0)
GLES20.glVertexAttribPointer(aPositionHandle, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer)
GLES20.glVertexAttribPointer(aTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, texCoordBuffer)
@@ -287,7 +450,7 @@ class PaperizeWallpaperRenderer(
}
/**
* Compile all shader programs.
* Compile all shader programs and cache uniform locations.
*/
private fun compileShaders() {
// Simple program
@@ -300,53 +463,90 @@ class PaperizeWallpaperRenderer(
// Effects program
effectsProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.EFFECTS_FRAGMENT_SHADER)
// Get uniform/attribute locations for effects program
// Cache uniform/attribute locations for effects program
aPositionHandle = GLES20.glGetAttribLocation(effectsProgram, "a_position")
aTexCoordHandle = GLES20.glGetAttribLocation(effectsProgram, "a_texCoord")
uTextureHandle = GLES20.glGetUniformLocation(effectsProgram, "u_texture")
uMvpMatrixHandle = GLES20.glGetUniformLocation(effectsProgram, "u_mvpMatrix")
uAlphaHandle = GLES20.glGetUniformLocation(effectsProgram, "u_alpha")
uDarkenFactorHandle = GLES20.glGetUniformLocation(effectsProgram, "u_darkenFactor")
uVignetteFactorHandle = GLES20.glGetUniformLocation(effectsProgram, "u_vignetteFactor")
uGrayscaleEnabledHandle = GLES20.glGetUniformLocation(effectsProgram, "u_grayscaleEnabled")
uGrayscaleFactorHandle = GLES20.glGetUniformLocation(effectsProgram, "u_grayscaleFactor")
uAdaptiveBrightnessFactorHandle = GLES20.glGetUniformLocation(effectsProgram, "u_adaptiveBrightnessFactor")
// Note: Blur program uniforms are queried dynamically when needed
Log.d(TAG, "Effects uniform locations: alpha=$uAlphaHandle, darken=$uDarkenFactorHandle, " +
"vignette=$uVignetteFactorHandle, grayscale=$uGrayscaleFactorHandle, adaptiveBrightness=$uAdaptiveBrightnessFactorHandle")
Log.d(TAG, "Shaders compiled successfully")
// Cache uniform/attribute locations for horizontal blur program
blurHPositionHandle = GLES20.glGetAttribLocation(blurHorizontalProgram, "a_position")
blurHTexCoordHandle = GLES20.glGetAttribLocation(blurHorizontalProgram, "a_texCoord")
blurHTextureHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_texture")
blurHMvpMatrixHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_mvpMatrix")
blurHResolutionHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_resolution")
blurHRadiusHandle = GLES20.glGetUniformLocation(blurHorizontalProgram, "u_blurRadius")
// Cache uniform/attribute locations for vertical blur program
blurVPositionHandle = GLES20.glGetAttribLocation(blurVerticalProgram, "a_position")
blurVTexCoordHandle = GLES20.glGetAttribLocation(blurVerticalProgram, "a_texCoord")
blurVTextureHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_texture")
blurVMvpMatrixHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_mvpMatrix")
blurVResolutionHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_resolution")
blurVRadiusHandle = GLES20.glGetUniformLocation(blurVerticalProgram, "u_blurRadius")
Log.d(TAG, "Shaders compiled and uniforms cached")
}
/**
* Create framebuffer for blur intermediate pass.
* Create framebuffers for blur passes.
* Two FBOs are needed for proper 3-pass blur + effects pipeline.
*/
private fun createBlurFramebuffer(width: Int, height: Int) {
private fun createBlurFramebuffers(width: Int, height: Int) {
// Delete old resources
if (blurFbo != 0) {
GLUtil.deleteFramebuffer(blurFbo)
}
if (blurTexture != 0) {
GLUtil.deleteTexture(blurTexture)
}
deleteBlurResources()
// Create texture for FBO
// Create FBO1 (horizontal blur output)
val (fbo1, tex1) = createFboWithTexture(width, height)
blurFbo1 = fbo1
blurTexture1 = tex1
// Create FBO2 (vertical blur output)
val (fbo2, tex2) = createFboWithTexture(width, height)
blurFbo2 = fbo2
blurTexture2 = tex2
Log.d(TAG, "Blur framebuffers created: ${width}x${height}")
}
/**
* Create an FBO with attached texture at specified dimensions.
* @return Pair of (fboId, textureId)
*/
private fun createFboWithTexture(width: Int, height: Int): Pair<Int, Int> {
// Create texture
val textureIds = IntArray(1)
GLES20.glGenTextures(1, textureIds, 0)
blurTexture = textureIds[0]
val textureId = textureIds[0]
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null)
GLES20.glTexImage2D(
GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA,
width, height, 0, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null
)
// Create framebuffer
val fboIds = IntArray(1)
GLES20.glGenFramebuffers(1, fboIds, 0)
blurFbo = fboIds[0]
val fboId = fboIds[0]
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo)
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
GLES20.GL_TEXTURE_2D, blurTexture, 0)
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboId)
GLES20.glFramebufferTexture2D(
GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
GLES20.GL_TEXTURE_2D, textureId, 0
)
val status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER)
if (status != GLES20.GL_FRAMEBUFFER_COMPLETE) {
@@ -355,31 +555,71 @@ class PaperizeWallpaperRenderer(
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0)
Log.d(TAG, "Blur framebuffer created: ${width}x${height}")
return Pair(fboId, textureId)
}
/**
* Delete all blur-related GPU resources.
*/
private fun deleteBlurResources() {
if (blurFbo1 != 0) GLUtil.deleteFramebuffer(blurFbo1)
if (blurFbo2 != 0) GLUtil.deleteFramebuffer(blurFbo2)
if (blurTexture1 != 0) GLUtil.deleteTexture(blurTexture1)
if (blurTexture2 != 0) GLUtil.deleteTexture(blurTexture2)
blurFbo1 = 0
blurFbo2 = 0
blurTexture1 = 0
blurTexture2 = 0
}
/**
* Queue a new wallpaper for loading and display.
* This method can be called from any thread.
* Will wait for valid surface dimensions before loading.
*
* @param imageLoader Image loader to use
* @param skipCrossfade If true, instantly swap wallpaper without crossfade animation
*/
fun queueWallpaper(imageLoader: ImageLoader) {
loadingScope.launch {
fun queueWallpaper(imageLoader: ImageLoader, skipCrossfade: Boolean = false) {
// Cancel any existing loading job to prevent race conditions
currentLoadJob?.cancel()
currentLoadJob = loadingScope.launch {
try {
Log.d(TAG, "Loading wallpaper...")
val bitmap = imageLoader.load(surfaceWidth, surfaceHeight)
// Wait for valid surface dimensions (onSurfaceChanged may not have been called yet)
val (width, height) = waitForSurfaceDimensions()
Log.d(TAG, "Loading wallpaper... (skipCrossfade=$skipCrossfade)")
val bitmap = imageLoader.load(width, height)
if (bitmap != null) {
Log.d(TAG, "Wallpaper loaded: ${bitmap.width}x${bitmap.height}")
// Check for cancellation before uploading
if (!isActive) {
Log.d(TAG, "Loading cancelled, recycling bitmap")
bitmap.recycle()
return@launch
}
// Calculate adaptive brightness if enabled
val brightnessFactor = if (adaptiveBrightnessEnabled) {
val brightness = com.anthonyla.paperize.core.util.calculateBitmapBrightness(bitmap)
com.anthonyla.paperize.core.util.getAdaptiveBrightnessMultiplier(context, brightness)
} else {
1.0f
}
// Upload to GPU on GL thread
callbacks.queueEventOnGlThread {
uploadBitmap(bitmap)
uploadBitmap(bitmap, brightnessFactor, skipCrossfade)
}
} else {
Log.w(TAG, "Failed to load wallpaper (null bitmap)")
}
} catch (e: CancellationException) {
Log.d(TAG, "Wallpaper loading cancelled")
} catch (e: Exception) {
Log.e(TAG, "Error loading wallpaper", e)
}
@@ -387,26 +627,87 @@ class PaperizeWallpaperRenderer(
}
/**
* Upload a bitmap to GPU and start crossfade.
* Must be called on GL thread.
* Wait for valid surface dimensions.
* Polls until surfaceWidth and surfaceHeight are non-zero or timeout.
* Falls back to device display metrics if timeout occurs.
*
* @return Pair of (width, height)
*/
private fun uploadBitmap(bitmap: Bitmap) {
private suspend fun waitForSurfaceDimensions(): Pair<Int, Int> {
val maxWaitMs = Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS
val pollIntervalMs = Constants.SURFACE_POLL_INTERVAL_MS
var waitedMs = 0L
while (surfaceWidth <= 0 || surfaceHeight <= 0) {
if (waitedMs >= maxWaitMs) {
// Use actual device display metrics as fallback instead of hardcoded values
val displayMetrics = context.resources.displayMetrics
val fallbackWidth = displayMetrics.widthPixels
val fallbackHeight = displayMetrics.heightPixels
Log.w(TAG, "Timeout waiting for surface dimensions, using display metrics: ${fallbackWidth}x${fallbackHeight}")
return Pair(fallbackWidth, fallbackHeight)
}
kotlinx.coroutines.delay(pollIntervalMs)
waitedMs += pollIntervalMs
}
return Pair(surfaceWidth, surfaceHeight)
}
/**
* Upload a bitmap to GPU and start crossfade (or instant swap).
* Must be called on GL thread.
*
* @param bitmap The bitmap to upload
* @param brightnessFactor The adaptive brightness multiplier for this bitmap
* @param skipCrossfade If true, instantly replace current wallpaper without animation
*/
private fun uploadBitmap(bitmap: Bitmap, brightnessFactor: Float, skipCrossfade: Boolean = false) {
// Validate bitmap before processing
if (bitmap.isRecycled) {
Log.e(TAG, "Cannot upload recycled bitmap")
return
}
if (bitmap.width <= 0 || bitmap.height <= 0) {
Log.e(TAG, "Cannot upload bitmap with invalid dimensions: ${bitmap.width}x${bitmap.height}")
bitmap.recycle()
return
}
try {
val picture = GLPicture(bitmap)
val picture = GLPicture(bitmap, brightnessFactor)
// Recycle bitmap (no longer needed after GPU upload)
bitmap.recycle()
// Start crossfade
nextPicture = picture
crossfadeProgress = 0f
if (skipCrossfade) {
// Instant swap - no animation (used for screen-off changes)
currentPicture?.recycle()
currentPicture = picture
nextPicture = null
crossfadeProgress = 0f
crossfadeStartTimeNanos = 0L
Log.d(TAG, "Wallpaper instantly swapped (no crossfade): $picture")
} else {
// Start crossfade with time-based animation
nextPicture = picture
crossfadeProgress = 0f
crossfadeStartTimeNanos = System.nanoTime()
Log.d(TAG, "Wallpaper uploaded to GPU with crossfade: $picture")
}
callbacks.requestRender()
Log.d(TAG, "Wallpaper uploaded to GPU: $picture")
} catch (e: IllegalArgumentException) {
// GLPicture validation failed (recycled bitmap or invalid dimensions)
Log.e(TAG, "Failed to create GLPicture: ${e.message}")
if (!bitmap.isRecycled) {
bitmap.recycle()
}
} catch (e: Exception) {
Log.e(TAG, "Failed to upload bitmap to GPU", e)
bitmap.recycle()
if (!bitmap.isRecycled) {
bitmap.recycle()
}
}
}
@@ -416,6 +717,11 @@ class PaperizeWallpaperRenderer(
*/
fun updateEffects(effects: WallpaperEffects) {
this.currentEffects = effects
Log.d(TAG, "Effects updated: blur=${effects.enableBlur}/${effects.blurPercentage}, " +
"darken=${effects.enableDarken}/${effects.darkenPercentage}, " +
"vignette=${effects.enableVignette}/${effects.vignettePercentage}, " +
"grayscale=${effects.enableGrayscale}/${effects.grayscalePercentage}, " +
"parallax=${effects.enableParallax}/${effects.parallaxIntensity}")
callbacks.requestRender()
}
@@ -432,12 +738,34 @@ class PaperizeWallpaperRenderer(
}
}
/**
* Update adaptive brightness setting.
* Can be called from any thread.
*/
fun updateAdaptiveBrightness(enabled: Boolean) {
adaptiveBrightnessEnabled = enabled
Log.d(TAG, "Adaptive brightness updated: $enabled")
}
/**
* Update scaling type.
* Can be called from any thread.
*/
fun updateScalingType(scalingType: ScalingType) {
if (currentScalingType != scalingType) {
currentScalingType = scalingType
Log.d(TAG, "Scaling type updated: $scalingType")
callbacks.requestRender()
}
}
/**
* Cleanup resources.
* Must be called on GL thread.
*/
fun destroy() {
loadingScope.cancel()
currentLoadJob?.cancel()
currentPicture?.recycle()
currentPicture = null
@@ -450,8 +778,7 @@ class PaperizeWallpaperRenderer(
GLUtil.deleteProgram(blurVerticalProgram)
GLUtil.deleteProgram(effectsProgram)
GLUtil.deleteFramebuffer(blurFbo)
GLUtil.deleteTexture(blurTexture)
deleteBlurResources()
Log.d(TAG, "Renderer destroyed")
}
@@ -2,25 +2,64 @@ package com.anthonyla.paperize.service.tile
import android.content.Intent
import android.service.quicksettings.TileService
import android.util.Log
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import javax.inject.Inject
/**
* Quick Settings Tile for changing wallpaper
*/
@AndroidEntryPoint
class WallpaperTileService : TileService() {
@Inject
lateinit var settingsRepository: SettingsRepository
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
companion object {
private const val TAG = "WallpaperTileService"
}
override fun onClick() {
super.onClick()
// Start wallpaper change service
val intent = Intent(this, WallpaperChangeService::class.java).apply {
action = Constants.ACTION_CHANGE_WALLPAPER
putExtra(Constants.EXTRA_SCREEN_TYPE, ScreenType.BOTH.name)
}
serviceScope.launch {
try {
val mode = settingsRepository.getWallpaperMode()
// minSdk is 31, so startForegroundService is always available
startForegroundService(intent)
if (mode == WallpaperMode.LIVE) {
// Send broadcast to trigger live wallpaper reload
val intent = Intent(Constants.ACTION_RELOAD_WALLPAPER)
intent.setPackage(packageName)
sendBroadcast(intent)
} else {
// Start wallpaper change service for static wallpaper
// Use BOTH to ensure synchronized change if configured, or both if not
val intent = Intent(this@WallpaperTileService, WallpaperChangeService::class.java).apply {
action = Constants.ACTION_CHANGE_WALLPAPER
putExtra(Constants.EXTRA_SCREEN_TYPE, ScreenType.BOTH.name)
}
startForegroundService(intent)
}
} catch (e: Exception) {
Log.e(TAG, "Error handling tile click", e)
}
}
}
override fun onDestroy() {
super.onDestroy()
serviceScope.cancel()
}
}
@@ -6,6 +6,8 @@ import android.app.PendingIntent
import android.app.Service
import android.app.WallpaperManager
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
@@ -68,22 +70,30 @@ class WallpaperChangeService : Service() {
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// Start foreground service
startForeground(Constants.NOTIFICATION_ID, createNotification())
// Start foreground service. Android 14+ requires specifying the service type.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
startForeground(
Constants.NOTIFICATION_ID,
createNotification(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
)
} else {
startForeground(Constants.NOTIFICATION_ID, createNotification())
}
when (intent?.action) {
ACTION_CHANGE_WALLPAPER -> {
val screenType = intent.getStringExtra(EXTRA_SCREEN_TYPE)?.let {
ScreenType.fromString(it)
} ?: ScreenType.BOTH
handleChangeWallpaper(screenType)
handleChangeWallpaper(screenType, startId)
}
}
return START_NOT_STICKY
}
private fun handleChangeWallpaper(screenType: ScreenType) {
private fun handleChangeWallpaper(screenType: ScreenType, startId: Int) {
serviceScope.launch {
// Use mutex to prevent concurrent wallpaper changes
wallpaperChangeMutex.withLock {
@@ -177,10 +187,10 @@ class WallpaperChangeService : Service() {
}
}
stopSelf()
stopSelf(startId)
} catch (e: Exception) {
Log.e(TAG, "Error changing wallpaper", e)
stopSelf()
stopSelf(startId)
}
}
}
@@ -204,13 +214,12 @@ class WallpaperChangeService : Service() {
true,
WallpaperManager.FLAG_SYSTEM
)
// Recycle bitmap after setting to free memory
bitmap.recycle()
Log.d(TAG, "Home wallpaper changed successfully")
} catch (e: Exception) {
Log.e(TAG, "Error setting home wallpaper", e)
} finally {
// Always recycle bitmap to prevent memory leaks
bitmap.recycle()
}
}.onError { error ->
if (error.message?.contains("No wallpapers available in album") == true) {
@@ -239,13 +248,12 @@ class WallpaperChangeService : Service() {
true,
WallpaperManager.FLAG_LOCK
)
// Recycle bitmap after setting to free memory
bitmap.recycle()
Log.d(TAG, "Lock wallpaper changed successfully")
} catch (e: Exception) {
Log.e(TAG, "Error setting lock wallpaper", e)
} finally {
// Always recycle bitmap to prevent memory leaks
bitmap.recycle()
}
}.onError { error ->
if (error.message?.contains("No wallpapers available in album") == true) {
@@ -10,6 +10,8 @@ import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.usecase.RefreshAlbumUseCase
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.first
/**
@@ -68,54 +70,44 @@ class AlbumRefreshWorker @AssistedInject constructor(
}
}
// Step 2: Rescan all folders for new wallpapers
album.folders.forEach { folder ->
when (val scanResult = wallpaperRepository.scanFolderForWallpapers(android.net.Uri.parse(folder.uri))) {
is CoreResult.Success -> {
val scannedWallpapers = scanResult.data
// Step 2: Rescan all folders for new wallpapers (Parallelized)
coroutineScope {
album.folders.map { folder ->
async {
when (val scanResult = wallpaperRepository.scanFolderForWallpapers(android.net.Uri.parse(folder.uri))) {
is CoreResult.Success -> {
val scannedWallpapers = scanResult.data
// Get ALL existing URIs (direct wallpapers + folder wallpapers)
val existingUris = (album.wallpapers.map { it.uri } +
album.folders.flatMap { it.wallpapers.map { w -> w.uri } }).toSet()
// Find new wallpapers not already in album (anywhere)
val newWallpapers = scannedWallpapers.filter { it.uri !in existingUris }
// Add new wallpapers to album
newWallpapers.forEach { wallpaper ->
// Fix: Create copy with correct albumId and folderId
// scanFolderForWallpapers returns wallpapers with empty albumId/null folderId
val wallpaperToAdd = wallpaper.copy(
albumId = album.id,
folderId = folder.id
)
when (wallpaperRepository.addWallpaper(wallpaperToAdd)) {
is CoreResult.Success -> {
totalAdded++
albumHasNewWallpapers = true
}
is CoreResult.Error -> {
Log.e(TAG, "Error adding wallpaper to album '${album.name}'")
failedCount++
}
is CoreResult.Loading -> {
/* Loading state not used */
// Find and add new wallpapers not already in album
scannedWallpapers.forEach { wallpaper ->
// Memory-efficient check: check database for existing URI in this album
if (!wallpaperRepository.isWallpaperInAlbum(album.id, wallpaper.uri)) {
val wallpaperToAdd = wallpaper.copy(
albumId = album.id,
folderId = folder.id
)
when (wallpaperRepository.addWallpaper(wallpaperToAdd)) {
is CoreResult.Success -> {
totalAdded++
albumHasNewWallpapers = true
}
is CoreResult.Error -> {
Log.e(TAG, "Error adding wallpaper to album '${album.name}'")
failedCount++
}
is CoreResult.Loading -> { /* Not used */ }
}
}
}
}
}
if (newWallpapers.isNotEmpty()) {
Log.d(TAG, "Album '${album.name}': added ${newWallpapers.size} new wallpapers from folder '${folder.name}'")
is CoreResult.Error -> {
Log.e(TAG, "Error scanning folder '${folder.name}' in album '${album.name}'", scanResult.exception)
}
is CoreResult.Loading -> { /* Not used */ }
}
}
is CoreResult.Error -> {
Log.e(TAG, "Error scanning folder '${folder.name}' in album '${album.name}'", scanResult.exception)
}
is CoreResult.Loading -> {
/* Loading state not used */
}
}
}.forEach { it.await() }
}
// Step 3: Refresh folder covers if new wallpapers were added
@@ -70,9 +70,11 @@ class WallpaperChangeWorker @AssistedInject constructor(
when (screenType) {
ScreenType.LIVE -> {
// Live wallpaper changes are handled by the live wallpaper service itself
// WorkManager is not used for live wallpaper scheduling
Log.d(TAG, "Live wallpaper change - no action needed in worker")
// Send broadcast to trigger live wallpaper reload
val intent = android.content.Intent(Constants.ACTION_RELOAD_WALLPAPER)
intent.setPackage(context.packageName)
context.sendBroadcast(intent)
Log.d(TAG, "Sent reload broadcast to live wallpaper service")
}
ScreenType.HOME -> {
val homeAlbumId = settings.homeAlbumId
@@ -93,7 +95,8 @@ class WallpaperChangeWorker @AssistedInject constructor(
ScreenType.BOTH -> {
// Synchronized mode: set both screens to the same wallpaper
// This ensures both HOME and LOCK show identical wallpapers
val albumId = settings.homeAlbumId // Use home album (should be same as lock when synced)
// Use home album, fallback to lock album (they should be the same when synced)
val albumId = settings.homeAlbumId ?: settings.lockAlbumId
if (albumId != null) {
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
@@ -8,9 +8,17 @@ import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import kotlinx.coroutines.flow.first
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.constants.Constants
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.Calendar
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@@ -30,6 +38,8 @@ class WallpaperScheduler @Inject constructor(
@param:ApplicationContext private val context: Context
) {
private val workManager = WorkManager.getInstance(context)
private val schedulerScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private val mutex = Mutex()
companion object {
private const val TAG = "WallpaperScheduler"
@@ -105,74 +115,86 @@ class WallpaperScheduler @Inject constructor(
requireCharging: Boolean = false,
onlyIfNotScheduled: Boolean = false
) {
// Don't cancel all first - let UPDATE policy handle existing work
// This prevents immediate wallpaper change when just updating intervals
schedulerScope.launch {
mutex.withLock {
// Don't cancel all first - let UPDATE policy handle existing work
// This prevents immediate wallpaper change when just updating intervals
// Check if both should be synchronized (same interval, synchronized flag set)
val shouldSync = synchronized &&
homeIntervalMinutes > 0 &&
lockIntervalMinutes > 0 &&
homeIntervalMinutes == lockIntervalMinutes
// Check if both should be synchronized (same interval, synchronized flag set)
val shouldSync = synchronized &&
homeIntervalMinutes > 0 &&
lockIntervalMinutes > 0 &&
homeIntervalMinutes == lockIntervalMinutes
if (shouldSync) {
// When synchronized, schedule a single BOTH job that sets both screens
// This ensures both screens always show the same wallpaper
if (!onlyIfNotScheduled || !isWorkScheduled(ScreenType.BOTH)) {
scheduleWallpaperChange(
ScreenType.BOTH,
homeIntervalMinutes,
networkRequired,
requireCharging
)
// Cancel any existing separate HOME/LOCK jobs
cancelWallpaperChange(ScreenType.HOME)
cancelWallpaperChange(ScreenType.LOCK)
Log.d(TAG, "Scheduled synchronized wallpaper changes (BOTH) every $homeIntervalMinutes minutes")
} else {
Log.d(TAG, "Skipped scheduling BOTH wallpaper changes - already scheduled")
}
} else {
// Independent schedules - schedule or cancel each separately
// Cancel BOTH job if it exists (switching from sync to separate mode)
cancelWallpaperChange(ScreenType.BOTH)
if (homeIntervalMinutes > 0) {
if (!onlyIfNotScheduled || !isWorkScheduled(ScreenType.HOME)) {
scheduleWallpaperChange(
ScreenType.HOME,
homeIntervalMinutes,
networkRequired,
requireCharging
)
if (shouldSync) {
// When synchronized, schedule a single BOTH job that sets both screens
// This ensures both screens always show the same wallpaper
if (!onlyIfNotScheduled || !isWorkScheduled(ScreenType.BOTH)) {
scheduleWallpaperChange(
ScreenType.BOTH,
homeIntervalMinutes,
networkRequired,
requireCharging
)
// Cancel any existing separate HOME/LOCK jobs
cancelWallpaperChange(ScreenType.HOME)
cancelWallpaperChange(ScreenType.LOCK)
Log.d(TAG, "Scheduled synchronized wallpaper changes (BOTH) every $homeIntervalMinutes minutes")
} else {
Log.d(TAG, "Skipped scheduling BOTH wallpaper changes - already scheduled")
}
} else {
Log.d(TAG, "Skipped scheduling HOME wallpaper changes - already scheduled")
}
} else {
cancelWallpaperChange(ScreenType.HOME)
}
// Independent schedules - schedule or cancel each separately
// Check if BOTH was scheduled BEFORE cancelling it
// This is needed to force schedule HOME/LOCK when switching from sync mode
val wasBothScheduled = isWorkScheduled(ScreenType.BOTH)
// Cancel BOTH job if it exists (switching from sync to separate mode)
cancelWallpaperChange(ScreenType.BOTH)
// When switching away from sync mode, we must ensure HOME/LOCK are scheduled
// even if onlyIfNotScheduled is true, because they were previously suppressed
val forceSchedule = wasBothScheduled
if (lockIntervalMinutes > 0) {
if (!onlyIfNotScheduled || !isWorkScheduled(ScreenType.LOCK)) {
scheduleWallpaperChange(
ScreenType.LOCK,
lockIntervalMinutes,
networkRequired,
requireCharging
)
if (homeIntervalMinutes > 0) {
if (!onlyIfNotScheduled || forceSchedule || !isWorkScheduled(ScreenType.HOME)) {
scheduleWallpaperChange(
ScreenType.HOME,
homeIntervalMinutes,
networkRequired,
requireCharging
)
} else {
Log.d(TAG, "Skipped scheduling HOME wallpaper changes - already scheduled")
}
} else {
cancelWallpaperChange(ScreenType.HOME)
}
if (lockIntervalMinutes > 0) {
if (!onlyIfNotScheduled || forceSchedule || !isWorkScheduled(ScreenType.LOCK)) {
scheduleWallpaperChange(
ScreenType.LOCK,
lockIntervalMinutes,
networkRequired,
requireCharging
)
} else {
Log.d(TAG, "Skipped scheduling LOCK wallpaper changes - already scheduled")
}
} else {
cancelWallpaperChange(ScreenType.LOCK)
}
}
// Schedule daily album refresh to validate all albums
if (!onlyIfNotScheduled || !isAlbumRefreshScheduled()) {
scheduleAlbumRefresh()
} else {
Log.d(TAG, "Skipped scheduling LOCK wallpaper changes - already scheduled")
Log.d(TAG, "Skipped scheduling album refresh - already scheduled")
}
} else {
cancelWallpaperChange(ScreenType.LOCK)
}
}
// Schedule daily album refresh to validate all albums
if (!onlyIfNotScheduled || !isAlbumRefreshScheduled()) {
scheduleAlbumRefresh()
} else {
Log.d(TAG, "Skipped scheduling album refresh - already scheduled")
}
}
/**
@@ -204,9 +226,17 @@ class WallpaperScheduler @Inject constructor(
workManager.cancelUniqueWork(Constants.WORK_NAME_HOME)
workManager.cancelUniqueWork(Constants.WORK_NAME_LOCK)
workManager.cancelUniqueWork(Constants.WORK_NAME_BOTH)
workManager.cancelUniqueWork(Constants.WORK_NAME_LIVE)
cancelAlbumRefresh()
Log.d(TAG, "Cancelled all wallpaper change schedules")
}
// ... scheduleAlbumRefresh and cancelAlbumRefresh omitted as they were not targeted for change ...
// Wait, I should not delete them. I'll use the proper range.
// I will target up to cancelAllWallpaperChanges for this call.
// The next tool call will fix triggerImmediateChange.
/**
* Schedule daily album refresh worker
@@ -221,11 +251,26 @@ class WallpaperScheduler @Inject constructor(
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.build()
// Calculate initial delay to target 3 AM
val calendar = Calendar.getInstance()
val nowMillis = calendar.timeInMillis
if (calendar.get(Calendar.HOUR_OF_DAY) >= 3) {
calendar.add(Calendar.DAY_OF_YEAR, 1)
}
calendar.set(Calendar.HOUR_OF_DAY, 3)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.SECOND, 0)
calendar.set(Calendar.MILLISECOND, 0)
val initialDelay = calendar.timeInMillis - nowMillis
val workRequest = PeriodicWorkRequestBuilder<AlbumRefreshWorker>(
1,
TimeUnit.DAYS
)
.setConstraints(constraints)
.setInitialDelay(initialDelay, TimeUnit.MILLISECONDS)
.addTag(Constants.WORK_TAG_REFRESH)
.build()
@@ -262,7 +307,13 @@ class WallpaperScheduler @Inject constructor(
.addTag("${Constants.WORK_TAG_IMMEDIATE}_${screenType.name.lowercase()}")
.build()
workManager.enqueue(workRequest)
val uniqueWorkName = "${Constants.WORK_TAG_IMMEDIATE}_${screenType.name.lowercase()}"
workManager.enqueueUniqueWork(
uniqueWorkName,
androidx.work.ExistingWorkPolicy.REPLACE,
workRequest
)
Log.d(TAG, "Triggered immediate $screenType wallpaper change")
}
@@ -271,7 +322,7 @@ class WallpaperScheduler @Inject constructor(
ScreenType.HOME -> Constants.WORK_NAME_HOME
ScreenType.LOCK -> Constants.WORK_NAME_LOCK
ScreenType.BOTH -> Constants.WORK_NAME_BOTH
ScreenType.LIVE -> "wallpaper_change_live" // Not used in WorkManager scheduling
ScreenType.LIVE -> Constants.WORK_NAME_LIVE
}
}
@@ -280,7 +331,7 @@ class WallpaperScheduler @Inject constructor(
ScreenType.HOME -> Constants.WORK_TAG_HOME
ScreenType.LOCK -> Constants.WORK_TAG_LOCK
ScreenType.BOTH -> Constants.WORK_TAG_BOTH
ScreenType.LIVE -> "wallpaper_live" // Not used in WorkManager scheduling
ScreenType.LIVE -> Constants.WORK_TAG_LIVE
}
}
@@ -290,9 +341,16 @@ class WallpaperScheduler @Inject constructor(
* @param screenType Screen type to check
* @return true if work is scheduled (ENQUEUED or RUNNING), false otherwise
*/
private fun isWorkScheduled(screenType: ScreenType): Boolean {
private suspend fun isWorkScheduled(screenType: ScreenType): Boolean {
val workName = getWorkName(screenType)
val workInfos = workManager.getWorkInfosForUniqueWork(workName).get()
val workInfos = try {
workManager.getWorkInfosForUniqueWorkFlow(workName).first()
} catch (e: Exception) {
Log.e(TAG, "Error checking work status", e)
return false
}
if (workInfos.isEmpty()) return false
return workInfos.any { workInfo ->
workInfo.state == androidx.work.WorkInfo.State.ENQUEUED ||
@@ -305,8 +363,15 @@ class WallpaperScheduler @Inject constructor(
*
* @return true if work is scheduled (ENQUEUED or RUNNING), false otherwise
*/
private fun isAlbumRefreshScheduled(): Boolean {
val workInfos = workManager.getWorkInfosForUniqueWork(Constants.WORK_NAME_REFRESH).get()
private suspend fun isAlbumRefreshScheduled(): Boolean {
val workInfos = try {
workManager.getWorkInfosForUniqueWorkFlow(Constants.WORK_NAME_REFRESH).first()
} catch (e: Exception) {
Log.e(TAG, "Error checking refresh status", e)
return false
}
if (workInfos.isEmpty()) return false
return workInfos.any { workInfo ->
workInfo.state == androidx.work.WorkInfo.State.ENQUEUED ||
+39 -5
View File
@@ -2,9 +2,9 @@
<resources>
<string name="app_name">Paperize</string>
<string name="home">Home</string>
<string name="wallpaper_screen">Wallpaper</string>
<string name="library_screen">Library</string>
<string name="settings_screen">Settings</string>
<string name="wallpaper">Wallpaper</string>
<string name="library">Library</string>
<string name="back">Back</string>
<string name="add_images">Add images</string>
<string name="add_folder">Add folder</string>
@@ -106,6 +106,8 @@
<string name="make_the_colors_grayscale">Make the colors grayscale</string>
<string name="double_tap_to_change">Double-Tap to Change</string>
<string name="double_tap_wallpaper_to_change_it">Double-tap wallpaper to change it</string>
<string name="change_on_screen_off">Change on Screen Off</string>
<string name="change_wallpaper_when_screen_turns_off">Change wallpaper when screen turns off</string>
<string name="parallax_effect">Parallax Effect</string>
<string name="wallpaper_moves_with_screen_scroll">Wallpaper moves with screen scroll</string>
<string name="live_wallpaper_name">Paperize Live Wallpaper</string>
@@ -133,7 +135,6 @@
<string name="content_desc_delete_selected">Delete selected</string>
<string name="content_desc_expand">Expand</string>
<string name="content_desc_collapse">Collapse</string>
<string name="content_desc_back">Back</string>
<string name="content_desc_sort_items">Sort items</string>
<string name="content_desc_save">Save</string>
<string name="content_desc_current_lock_wallpaper">Current lock screen wallpaper</string>
@@ -153,8 +154,6 @@
<string name="current_wallpapers">Current Wallpapers</string>
<!-- Tab Titles -->
<string name="tab_wallpaper">Wallpaper</string>
<string name="tab_library">Library</string>
<!-- Sort Options -->
<string name="sort_name_asc">Name (A-Z)</string>
@@ -204,4 +203,39 @@
<!-- Album Labels -->
<string name="album_suffix"> Album</string>
<!-- Wallpaper Mode Selection -->
<string name="choose_wallpaper_mode">Choose Wallpaper Mode</string>
<string name="change_later_in_settings">You can change this later in settings</string>
<string name="static_mode">Static Mode</string>
<string name="static_mode_description">Classic wallpaper changing using the system wallpaper manager. Simple and battery-efficient. Supports images only.</string>
<string name="live_wallpaper_mode">Live Wallpaper Mode</string>
<string name="live_wallpaper_mode_description">Advanced live wallpaper with hardware-accelerated effects and interactive features (double-tap, parallax).</string>
<!-- Live Wallpaper Selection Dialog -->
<string name="select_live_wallpaper">Select Live Wallpaper</string>
<string name="select_live_wallpaper_instruction">To use Paperize in Live Wallpaper mode, you need to select it as your live wallpaper from the system settings.</string>
<string name="open_wallpaper_picker_instruction">\nTap \'Open Wallpaper Picker\' below to select Paperize from the list of available live wallpapers.</string>
<string name="open_wallpaper_picker">Open Wallpaper Picker</string>
<string name="later">Later</string>
<!-- Settings Mode Switcher -->
<string name="wallpaper_mode_setting">Wallpaper Mode</string>
<string name="current_mode">Current Mode</string>
<string name="mode_static">Static</string>
<string name="mode_live_wallpaper">Live Wallpaper</string>
<string name="switch_button">Switch</string>
<string name="mode_switch_warning">Switching modes will reset all albums, wallpapers, and settings. This cannot be undone.</string>
<string name="switch_mode_dialog_title">Switch to %1$s Mode?</string>
<string name="switch_mode_dialog_description">This will reset all albums, wallpapers, and scheduling settings. This action cannot be undone.\n\nYou\'ll need to re-add your albums and configure your wallpaper settings.</string>
<string name="switch_mode_button">Switch Mode</string>
<string name="open_wallpaper_picker_instruction_newline">\nTap \'Open Wallpaper Picker\' below to select Paperize from the list of available live wallpapers.</string>
<string name="loading_placeholder">…</string>
<string name="album_name_exists_error">Album with this name already exists</string>
<string name="battery_optimization">Battery Optimization</string>
<string name="battery_optimization_description">Disable battery optimization to ensure reliable wallpaper changes in the background.</string>
<string name="check_status">Check Status</string>
<string name="ignoring">Ignoring (Recommended)</string>
<string name="optimizing">Optimizing (May delay changes)</string>
<string name="reliability">Reliability</string>
</resources>