add live wallpaper

This commit is contained in:
Anthonyy232 authored and Anthony La committed 2025-12-21 18:30:23 -08:00
1 parent 572252b187
commit 391bbb6bc0
58 files changed
+4102 -648

No files matched your search

+17
View File
@@ -11,6 +11,8 @@
<uses-permission android:name="android.permission.WAKE_LOCK" />
<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 -->
<uses-feature
@@ -86,6 +88,21 @@
</intent-filter>
</service>
<!-- Live Wallpaper Service -->
<service
android:name=".service.livewallpaper.PaperizeLiveWallpaperService"
android:enabled="true"
android:exported="true"
android:label="@string/live_wallpaper_name"
android:permission="android.permission.BIND_WALLPAPER">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="@xml/wallpaper" />
</service>
</application>
</manifest>
@@ -6,7 +6,8 @@ package com.anthonyla.paperize.core
enum class ScreenType {
HOME,
LOCK,
BOTH;
BOTH,
LIVE;
companion object {
fun fromString(value: String?): ScreenType {
@@ -0,0 +1,54 @@
package com.anthonyla.paperize.core
/**
* Media type for wallpapers
*
* Determines what type of media the wallpaper file is, which affects
* how it's rendered in live wallpaper mode.
*
* Note: Currently only IMAGE type is supported.
*/
enum class WallpaperMediaType {
/**
* Image files: JPEG, PNG, WEBP, AVIF
* Supported in both static and live wallpaper modes
*/
IMAGE;
/**
* Supported file extensions for this media type
*/
val supportedExtensions: Set<String>
get() = when (this) {
IMAGE -> setOf("jpg", "jpeg", "png", "webp", "avif")
}
/**
* Whether this media type is supported in static wallpaper mode
*/
val supportedInStaticMode: Boolean
get() = this == IMAGE
/**
* Whether this media type is supported in live wallpaper mode
*/
val supportedInLiveMode: Boolean
get() = true // All types supported in live mode
companion object {
/**
* Detect media type from file extension
*/
fun fromExtension(extension: String): WallpaperMediaType? {
val ext = extension.lowercase()
return entries.find { ext in it.supportedExtensions }
}
/**
* Convert string to WallpaperMediaType
*/
fun fromString(value: String?): WallpaperMediaType? {
return entries.find { it.name.equals(value, ignoreCase = true) }
}
}
}
@@ -0,0 +1,40 @@
package com.anthonyla.paperize.core
/**
* Wallpaper mode enum
*
* Determines whether the app uses static wallpaper (WallpaperManager.setBitmap)
* or live wallpaper (WallpaperService) for applying wallpapers.
*
* Users choose their preferred mode during onboarding and can switch later
* with full data reset.
*/
enum class WallpaperMode {
/**
* Static wallpaper mode
* - Uses WallpaperManager.setBitmap() to apply wallpapers
* - Supports images only
* - Lower battery usage
* - No interactive effects
*/
STATIC,
/**
* Live wallpaper mode
* - Uses WallpaperService for continuous rendering
* - Supports images only (with effects)
* - Interactive effects (double-tap, parallax)
* - Higher battery usage
*/
LIVE;
companion object {
/**
* Convert string to WallpaperMode
* Defaults to STATIC if string is null or doesn't match any mode
*/
fun fromString(value: String?): WallpaperMode {
return entries.find { it.name.equals(value, ignoreCase = true) } ?: STATIC
}
}
}
@@ -6,7 +6,7 @@ package com.anthonyla.paperize.core.constants
object Constants {
// Database
const val DATABASE_NAME = "paperize_database"
const val DATABASE_VERSION = 1
const val DATABASE_VERSION = 2 // v2: Added mediaType and crop fields to WallpaperEntity
// DataStore
const val PREFERENCES_NAME = "paperize_preferences"
@@ -17,6 +17,9 @@ object Constants {
// Services
const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER"
const val ACTION_CHANGE_LIVE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_LIVE_WALLPAPER"
const val ACTION_UPDATE_LIVE_EFFECTS = "com.anthonyla.paperize.ACTION_UPDATE_LIVE_EFFECTS"
const val ACTION_RELOAD_WALLPAPER = "com.anthonyla.paperize.ACTION_RELOAD_WALLPAPER"
// WorkManager
const val WORK_NAME_HOME = "wallpaper_change_home"
@@ -37,6 +40,7 @@ object Constants {
const val DEFAULT_BLUR_PERCENTAGE = 0
const val DEFAULT_DARKEN_PERCENTAGE = 0
const val DEFAULT_VIGNETTE_PERCENTAGE = 0
const val DEFAULT_PARALLAX_INTENSITY = 50
const val MAX_EFFECT_PERCENTAGE = 100
const val MIN_EFFECT_PERCENTAGE = 0
@@ -102,7 +106,6 @@ object Constants {
object PreferenceKeys {
// Theme
const val DARK_MODE = "dark_mode"
const val AMOLED_THEME = "amoled_theme"
const val DYNAMIC_THEMING = "dynamic_theming"
const val ANIMATE = "animate"
@@ -135,6 +138,29 @@ object PreferenceKeys {
const val LOCK_VIGNETTE = "lock_vignette"
const val LOCK_GRAYSCALE = "lock_grayscale"
// Interactive Effects - Home (live wallpaper mode only)
const val HOME_ENABLE_DOUBLE_TAP = "home_enable_double_tap"
const val HOME_ENABLE_PARALLAX = "home_enable_parallax"
const val HOME_PARALLAX_INTENSITY = "home_parallax_intensity"
// Interactive Effects - Lock (live wallpaper mode only)
const val LOCK_ENABLE_DOUBLE_TAP = "lock_enable_double_tap"
const val LOCK_ENABLE_PARALLAX = "lock_enable_parallax"
const val LOCK_PARALLAX_INTENSITY = "lock_parallax_intensity"
// Live Wallpaper Mode Settings
const val LIVE_ALBUM_ID = "live_album_id"
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_GRAYSCALE = "live_grayscale"
const val LIVE_ENABLE_DOUBLE_TAP = "live_enable_double_tap"
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"
@@ -148,4 +174,7 @@ object PreferenceKeys {
// First launch
const val FIRST_LAUNCH = "first_launch"
// Wallpaper mode
const val WALLPAPER_MODE = "wallpaper_mode"
}
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.core.util
import android.app.WallpaperManager
import android.content.Context
import android.content.res.Configuration
import android.graphics.Bitmap
@@ -28,6 +29,7 @@ import androidx.compose.ui.util.fastRoundToInt
import androidx.core.graphics.createBitmap
import androidx.exifinterface.media.ExifInterface
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.WallpaperMediaType
/**
* Wallpaper utility functions for bitmap processing and effects
@@ -431,7 +433,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
/**
* Blur bitmap using GPU acceleration
*/
fun blurBitmap(context: Context, source: Bitmap, percent: Int): Bitmap {
fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
return blurBitmapHardware(source, percent)
}
@@ -632,7 +634,7 @@ fun processBitmap(
if (enableBlur && blurPercent > 0) {
previous = result
result = blurBitmap(context, result, blurPercent)
result = blurBitmap(result, blurPercent)
// Blur always creates a new bitmap, recycle the previous one if different
if (result !== previous && previous !== source) {
previous.recycle()
@@ -660,3 +662,82 @@ fun processBitmap(
return result
}
/**
* Detect media type from URI
*
* Examines the file extension and MIME type to determine the media type.
* Returns null if the media type cannot be determined or is unsupported.
*/
fun Uri.detectMediaType(context: Context): WallpaperMediaType? {
try {
// First try to get file extension from path
val path = this.path
if (path != null) {
val extension = path.substringAfterLast('.', "")
if (extension.isNotEmpty()) {
val mediaType = WallpaperMediaType.fromExtension(extension)
if (mediaType != null) {
return mediaType
}
}
}
// Fallback: Try to get MIME type from content resolver
val mimeType = context.contentResolver.getType(this)
if (mimeType != null) {
return when {
mimeType.startsWith("image/") -> WallpaperMediaType.IMAGE
else -> null
}
}
// If all else fails, assume IMAGE for backward compatibility
return WallpaperMediaType.IMAGE
} catch (e: Exception) {
Log.e(TAG, "Error detecting media type for URI: $this", e)
return WallpaperMediaType.IMAGE // Default to IMAGE on error
}
}
/**
* Validate that media type is supported in the current wallpaper mode
*/
fun WallpaperMediaType.isSupportedInMode(mode: com.anthonyla.paperize.core.WallpaperMode): Boolean {
return when (mode) {
com.anthonyla.paperize.core.WallpaperMode.STATIC -> this.supportedInStaticMode
com.anthonyla.paperize.core.WallpaperMode.LIVE -> this.supportedInLiveMode
}
}
/**
* Check if Paperize live wallpaper is currently active/selected
* Returns true if the Paperize live wallpaper service is the current wallpaper
*/
fun isPaperizeLiveWallpaperActive(context: Context): Boolean {
return try {
// If we are checking from within the service itself (e.g. preview mode), we are active
if (context is com.anthonyla.paperize.service.livewallpaper.PaperizeLiveWallpaperService) {
return true
}
val wallpaperManager = WallpaperManager.getInstance(context)
val wallpaperInfo = wallpaperManager.wallpaperInfo
// If wallpaperInfo is null, user has a static wallpaper (not a live wallpaper)
if (wallpaperInfo == null) {
return false
}
// Check if the service component matches Paperize live wallpaper
val expectedComponent = android.content.ComponentName(
context.packageName,
"com.anthonyla.paperize.service.livewallpaper.PaperizeLiveWallpaperService"
)
val isPaperize = wallpaperInfo.component == expectedComponent
isPaperize
} catch (e: Exception) {
Log.e("WallpaperUtil", "Error checking live wallpaper status", e)
false
}
}
@@ -3,6 +3,7 @@ package com.anthonyla.paperize.data.database.converters
import androidx.room.TypeConverter
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.core.WallpaperSourceType
/**
@@ -27,4 +28,11 @@ class TypeConverters {
@TypeConverter
fun toWallpaperSourceType(value: String): WallpaperSourceType =
WallpaperSourceType.entries.find { it.name == value } ?: WallpaperSourceType.DIRECT
@TypeConverter
fun fromWallpaperMediaType(value: WallpaperMediaType): String = value.name
@TypeConverter
fun toWallpaperMediaType(value: String): WallpaperMediaType =
WallpaperMediaType.fromString(value) ?: WallpaperMediaType.IMAGE
}
@@ -58,17 +58,6 @@ interface WallpaperQueueDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertQueueItems(items: List<WallpaperQueueEntity>)
/**
* Remove first item from queue and normalize positions
*/
@Transaction
suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType) {
// Delete the first item
deleteFirstQueueItem(albumId, screenType)
// Normalize positions to fix any gaps from CASCADE deletes
normalizeQueuePositions(albumId, screenType)
}
@Query("""
DELETE FROM wallpaper_queue
WHERE albumId = :albumId AND screenType = :screenType
@@ -5,6 +5,7 @@ import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.core.WallpaperSourceType
/**
@@ -49,5 +50,19 @@ data class WallpaperEntity(
val dateModified: Long,
val displayOrder: Int = 0,
val sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
val addedAt: Long = System.currentTimeMillis()
val addedAt: Long = System.currentTimeMillis(),
/**
* Media type (IMAGE)
* Added in database version 2 for live wallpaper support
*/
val mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE,
/**
* Manual crop parameters for live wallpaper rendering
* Added in database version 2
*/
val cropOffsetX: Float? = null,
val cropOffsetY: Float? = null,
val cropScale: Float? = null
)
@@ -10,6 +10,7 @@ import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.anthonyla.paperize.core.ScalingType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.constants.PreferenceKeys
import com.anthonyla.paperize.domain.model.AppSettings
@@ -45,7 +46,6 @@ class PreferencesManager @Inject constructor(
val prefs = dataStore.data.first()
return AppSettings(
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
amoledTheme = prefs[booleanPreferencesKey(PreferenceKeys.AMOLED_THEME)] ?: false,
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: true,
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
@@ -57,7 +57,6 @@ class PreferencesManager @Inject constructor(
fun getAppSettingsFlow(): Flow<AppSettings> = dataStore.data.map { prefs ->
AppSettings(
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
amoledTheme = prefs[booleanPreferencesKey(PreferenceKeys.AMOLED_THEME)] ?: false,
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: true,
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
@@ -69,7 +68,6 @@ class PreferencesManager @Inject constructor(
suspend fun updateAppSettings(settings: AppSettings) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = settings.darkMode ?: false
prefs[booleanPreferencesKey(PreferenceKeys.AMOLED_THEME)] = settings.amoledTheme
prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = settings.dynamicTheming
prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = settings.animate
prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = settings.firstLaunch
@@ -82,6 +80,36 @@ class PreferencesManager @Inject constructor(
}
}
// ============ Wallpaper Mode ============
/**
* Get current wallpaper mode (STATIC or LIVE)
* Defaults to STATIC for new installations and backward compatibility
*/
suspend fun getWallpaperMode(): WallpaperMode {
val prefs = dataStore.data.first()
val modeString = prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]
return WallpaperMode.fromString(modeString)
}
/**
* Get wallpaper mode as a Flow for reactive updates
*/
fun getWallpaperModeFlow(): Flow<WallpaperMode> = dataStore.data.map { prefs ->
val modeString = prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]
WallpaperMode.fromString(modeString)
}
/**
* Update wallpaper mode
* IMPORTANT: Caller should handle data reset when switching modes
*/
suspend fun updateWallpaperMode(mode: WallpaperMode) {
dataStore.edit { prefs ->
prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)] = mode.name
}
}
// ============ Schedule Settings ============
suspend fun getScheduleSettings(): ScheduleSettings {
@@ -90,10 +118,11 @@ class PreferencesManager @Inject constructor(
enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: true,
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: true,
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
?: Constants.DEFAULT_INTERVAL_MINUTES,
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
@@ -107,7 +136,10 @@ 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_GRAYSCALE)] ?: false,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
),
lockEffects = WallpaperEffects(
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
@@ -116,7 +148,10 @@ 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_GRAYSCALE)] ?: false,
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
),
adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
)
@@ -127,10 +162,11 @@ class PreferencesManager @Inject constructor(
enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: true,
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: true,
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
?: Constants.DEFAULT_INTERVAL_MINUTES,
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
@@ -144,7 +180,10 @@ 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_GRAYSCALE)] ?: false,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
),
lockEffects = WallpaperEffects(
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
@@ -153,7 +192,22 @@ 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_GRAYSCALE)] ?: false,
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_GRAYSCALE)] ?: false,
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: 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
)
@@ -176,6 +230,11 @@ class PreferencesManager @Inject constructor(
} else {
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
}
if (settings.liveAlbumId != null) {
prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)] = settings.liveAlbumId
} else {
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
}
prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)] = settings.homeIntervalMinutes
prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)] = settings.lockIntervalMinutes
prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)] = settings.homeScalingType.name
@@ -189,6 +248,9 @@ class PreferencesManager @Inject constructor(
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_DOUBLE_TAP)] = settings.homeEffects.enableDoubleTap
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] = settings.homeEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] = settings.homeEffects.parallaxIntensity
// Lock effects
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] = settings.lockEffects.enableBlur
@@ -198,6 +260,24 @@ class PreferencesManager @Inject constructor(
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_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
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] = settings.liveEffects.enableDarken
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_DOUBLE_TAP)] = settings.liveEffects.enableDoubleTap
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] = settings.liveEffects.enableParallax
prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] = settings.liveEffects.parallaxIntensity
// Adaptive brightness
prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] = settings.adaptiveBrightness
@@ -234,6 +314,19 @@ class PreferencesManager @Inject constructor(
}
}
/**
* Atomically update live album ID without race conditions
*/
suspend fun updateLiveAlbumId(albumId: String?) {
dataStore.edit { prefs ->
if (albumId != null) {
prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)] = albumId
} else {
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
}
}
}
/**
* Atomically clear album selections if they match the given album ID
* Used when deleting an album to prevent race conditions
@@ -271,15 +364,6 @@ class PreferencesManager @Inject constructor(
}
}
/**
* Atomically update AMOLED theme setting without race conditions
*/
suspend fun updateAmoledTheme(enabled: Boolean) {
dataStore.edit { prefs ->
prefs[booleanPreferencesKey(PreferenceKeys.AMOLED_THEME)] = enabled
}
}
/**
* Atomically update dynamic theming setting without race conditions
*/
@@ -355,6 +439,73 @@ class PreferencesManager @Inject constructor(
} as T
}
/**
* Clear schedule settings (reset to defaults)
* Used when switching wallpaper modes
*/
suspend fun clearScheduleSettings() {
dataStore.edit { prefs ->
// Clear scheduling settings
prefs.remove(booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER))
prefs.remove(booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES))
prefs.remove(booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLED))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED))
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES))
// Clear home effects
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_BLUR))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_DARKEN))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_VIGNETTE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP))
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX))
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY))
// Clear lock effects
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_BLUR))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_DARKEN))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX))
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY))
// Clear live effects
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_BLUR))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_DARKEN))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE))
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE))
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP))
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))
// Clear current wallpapers
prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID))
prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID))
// Clear adaptive brightness
prefs.remove(booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS))
}
}
suspend fun clear() {
dataStore.edit { it.clear() }
}
@@ -16,7 +16,8 @@ fun WallpaperEntity.toDomainModel(): Wallpaper = Wallpaper(
dateModified = dateModified,
displayOrder = displayOrder,
sourceType = sourceType,
addedAt = addedAt
addedAt = addedAt,
mediaType = mediaType
)
fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
@@ -28,7 +29,8 @@ fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
dateModified = dateModified,
displayOrder = displayOrder,
sourceType = sourceType,
addedAt = addedAt
addedAt = addedAt,
mediaType = mediaType
)
fun List<WallpaperEntity>.toDomainModels(): List<Wallpaper> = map { it.toDomainModel() }
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.data.repository
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.data.datastore.PreferencesManager
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.model.ScheduleSettings
@@ -25,6 +26,15 @@ class SettingsRepositoryImpl @Inject constructor(
override suspend fun updateAppSettings(settings: AppSettings) =
preferencesManager.updateAppSettings(settings)
override suspend fun getWallpaperMode(): WallpaperMode =
preferencesManager.getWallpaperMode()
override fun getWallpaperModeFlow(): Flow<WallpaperMode> =
preferencesManager.getWallpaperModeFlow()
override suspend fun updateWallpaperMode(mode: WallpaperMode) =
preferencesManager.updateWallpaperMode(mode)
override suspend fun getScheduleSettings(): ScheduleSettings =
preferencesManager.getScheduleSettings()
@@ -37,12 +47,18 @@ class SettingsRepositoryImpl @Inject constructor(
override suspend fun clearAllSettings() =
preferencesManager.clear()
override suspend fun clearScheduleSettings() =
preferencesManager.clearScheduleSettings()
override suspend fun updateHomeAlbumId(albumId: String?) =
preferencesManager.updateHomeAlbumId(albumId)
override suspend fun updateLockAlbumId(albumId: String?) =
preferencesManager.updateLockAlbumId(albumId)
override suspend fun updateLiveAlbumId(albumId: String?) =
preferencesManager.updateLiveAlbumId(albumId)
override suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean =
preferencesManager.clearAlbumSelectionsIfMatches(albumId)
@@ -51,9 +67,6 @@ class SettingsRepositoryImpl @Inject constructor(
override suspend fun updateDarkMode(enabled: Boolean) =
preferencesManager.updateDarkMode(enabled)
override suspend fun updateAmoledTheme(enabled: Boolean) =
preferencesManager.updateAmoledTheme(enabled)
override suspend fun updateDynamicTheming(enabled: Boolean) =
preferencesManager.updateDynamicTheming(enabled)
@@ -159,6 +159,7 @@ class WallpaperRepositoryImpl @Inject constructor(
ScreenType.HOME -> ScreenType.LOCK
ScreenType.LOCK -> ScreenType.HOME
ScreenType.BOTH -> null
ScreenType.LIVE -> null
}
val existingQueueIds = otherScreenType?.let {
@@ -199,15 +200,6 @@ class WallpaperRepositoryImpl @Inject constructor(
}
}
override suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType): Result<Unit> {
return try {
wallpaperQueueDao.dequeueWallpaper(albumId, screenType)
Result.Success(Unit)
} catch (e: Exception) {
Result.Error(e)
}
}
override suspend fun clearAllQueues(): Result<Unit> {
return try {
wallpaperQueueDao.deleteAllQueueItems()
@@ -232,6 +224,7 @@ class WallpaperRepositoryImpl @Inject constructor(
// 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)
Result.Success(Unit)
} catch (e: Exception) {
Result.Error(e)
@@ -5,7 +5,6 @@ package com.anthonyla.paperize.domain.model
*/
data class AppSettings(
val darkMode: Boolean? = null, // null = system default, true = dark, false = light
val amoledTheme: Boolean = false,
val dynamicTheming: Boolean = true,
val animate: Boolean = true,
val firstLaunch: Boolean = true,
@@ -20,6 +20,8 @@ data class ScheduleSettings(
val lockScalingType: ScalingType = ScalingType.FILL,
val homeEffects: WallpaperEffects = WallpaperEffects.none(),
val lockEffects: WallpaperEffects = WallpaperEffects.none(),
val liveAlbumId: String? = null,
val liveEffects: WallpaperEffects = WallpaperEffects.none(),
val adaptiveBrightness: Boolean = false
) {
/**
@@ -29,7 +31,8 @@ data class ScheduleSettings(
homeIntervalMinutes = homeIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
lockIntervalMinutes = lockIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
homeEffects = homeEffects.validate(),
lockEffects = lockEffects.validate()
lockEffects = lockEffects.validate(),
liveEffects = liveEffects.validate()
)
/**
@@ -62,6 +65,7 @@ data class ScheduleSettings(
lockScalingType != other.lockScalingType ||
homeEffects != other.homeEffects ||
lockEffects != other.lockEffects ||
liveEffects != other.liveEffects ||
adaptiveBrightness != other.adaptiveBrightness
}
@@ -1,6 +1,7 @@
package com.anthonyla.paperize.domain.model
import android.net.Uri
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.core.WallpaperSourceType
/**
@@ -17,7 +18,8 @@ data class Wallpaper(
val dateModified: Long,
val displayOrder: Int = 0,
val sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
val addedAt: Long = System.currentTimeMillis()
val addedAt: Long = System.currentTimeMillis(),
val mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE
) {
/**
* Get URL-decoded file name for display (filename only, no path)
@@ -6,15 +6,22 @@ import com.anthonyla.paperize.core.constants.Constants
* Domain model for Wallpaper Effects
*
* Represents the visual effects applied to wallpapers
* Includes both visual effects (blur, darken, etc.) and interactive effects (double-tap, parallax)
*/
data class WallpaperEffects(
// Visual effects (available in both static and live modes)
val enableBlur: Boolean = false,
val blurPercentage: Int = Constants.DEFAULT_BLUR_PERCENTAGE,
val enableDarken: Boolean = false,
val darkenPercentage: Int = Constants.DEFAULT_DARKEN_PERCENTAGE,
val enableVignette: Boolean = false,
val vignettePercentage: Int = Constants.DEFAULT_VIGNETTE_PERCENTAGE,
val enableGrayscale: Boolean = false
val enableGrayscale: Boolean = false,
// Interactive effects (live wallpaper mode only)
val enableDoubleTap: Boolean = false,
val enableParallax: Boolean = false,
val parallaxIntensity: Int = Constants.DEFAULT_PARALLAX_INTENSITY
) {
/**
* Check if any effects are applied
@@ -31,7 +38,8 @@ data class WallpaperEffects(
fun validate(): WallpaperEffects = copy(
darkenPercentage = darkenPercentage.coerceIn(-100, 100),
blurPercentage = blurPercentage.coerceIn(0, 100),
vignettePercentage = vignettePercentage.coerceIn(0, 100)
vignettePercentage = vignettePercentage.coerceIn(0, 100),
parallaxIntensity = parallaxIntensity.coerceIn(0, 100)
)
companion object {
@@ -1,5 +1,6 @@
package com.anthonyla.paperize.domain.repository
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.model.ScheduleSettings
import kotlinx.coroutines.flow.Flow
@@ -23,6 +24,22 @@ interface SettingsRepository {
*/
suspend fun updateAppSettings(settings: AppSettings)
/**
* Get wallpaper mode (STATIC or LIVE)
*/
suspend fun getWallpaperMode(): WallpaperMode
/**
* Get wallpaper mode as Flow
*/
fun getWallpaperModeFlow(): Flow<WallpaperMode>
/**
* Update wallpaper mode
* IMPORTANT: Caller must handle data reset when switching modes
*/
suspend fun updateWallpaperMode(mode: WallpaperMode)
/**
* Get schedule settings
*/
@@ -43,6 +60,17 @@ interface SettingsRepository {
*/
suspend fun clearAllSettings()
/**
* Clear schedule settings (reset to defaults)
* Used when switching wallpaper modes to reset all scheduling configuration
*/
suspend fun clearScheduleSettings()
/**
* Set wallpaper mode (wrapper for updateWallpaperMode)
*/
suspend fun setWallpaperMode(mode: WallpaperMode) = updateWallpaperMode(mode)
/**
* Atomically update home album ID to prevent race conditions
* Use this instead of updateScheduleSettings when only changing home album
@@ -55,6 +83,12 @@ interface SettingsRepository {
*/
suspend fun updateLockAlbumId(albumId: String?)
/**
* Atomically update live album ID to prevent race conditions
* Use this instead of updateScheduleSettings when only changing live album
*/
suspend fun updateLiveAlbumId(albumId: String?)
/**
* Atomically clear album selections if they match the given album ID
* Used when deleting an album to prevent race conditions
@@ -65,7 +99,6 @@ interface SettingsRepository {
// ============ Atomic AppSettings Operations ============
suspend fun updateDarkMode(enabled: Boolean)
suspend fun updateAmoledTheme(enabled: Boolean)
suspend fun updateDynamicTheming(enabled: Boolean)
suspend fun updateAnimate(enabled: Boolean)
suspend fun updateFirstLaunch(isFirstLaunch: Boolean)
@@ -85,11 +85,6 @@ interface WallpaperRepository {
shuffle: Boolean = false
): Result<Unit>
/**
* Dequeue wallpaper (remove first from queue)
*/
suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType): Result<Unit>
/**
* Clear all queues for all albums
* Used when shuffle setting changes to force rebuild with new mode
@@ -56,7 +56,6 @@ class MainActivity : ComponentActivity() {
PaperizeTheme(
darkMode = appSettings.darkMode,
amoledMode = appSettings.amoledTheme,
dynamicTheming = appSettings.dynamicTheming
) {
Surface(
@@ -41,7 +41,6 @@ import com.anthonyla.paperize.R
@Composable
fun AddAlbumAnimatedFab(
isLoading: Boolean,
animate: Boolean,
onImageClick: () -> Unit,
onFolderClick: () -> Unit,
modifier: Modifier = Modifier
@@ -107,72 +107,6 @@ fun EditAlbumNameDialog(
)
}
/**
* Dialog for confirming album deletion
*/
@Composable
fun DeleteAlbumDialog(
albumName: String,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
modifier: Modifier = Modifier
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.delete_album_question)) },
text = { Text(stringResource(R.string.are_you_sure_you_want_to_delete_this)) },
confirmButton = {
TextButton(
onClick = onConfirm,
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) {
Text(stringResource(R.string.delete_album))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.cancel))
}
},
modifier = modifier
)
}
/**
* Dialog for confirming wallpaper deletion
*/
@Composable
fun DeleteWallpapersDialog(
count: Int,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
modifier: Modifier = Modifier
) {
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.delete_these)) },
text = { Text(stringResource(R.string.are_you_sure_you_want_to_delete_these_wallpapers)) },
confirmButton = {
TextButton(
onClick = onConfirm,
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) {
Text(stringResource(R.string.delete_album))
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.cancel))
}
},
modifier = modifier
)
}
/**
* Dialog for confirming reset
*/
@@ -7,7 +7,8 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
/**
* Image picker using Android Photo Picker
* Media picker using Android Photo Picker
* Supports images only
*/
@Composable
fun rememberImagePicker(
@@ -22,6 +23,7 @@ fun rememberImagePicker(
}
return {
// Allow images only
launcher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}
}
@@ -60,13 +60,29 @@ fun NavigationGraph(
) {
StartupScreen(
onAgree = {
navController.navigate(NotificationRoute) {
navController.navigate(WallpaperModeSelectionRoute) {
popUpTo<StartupRoute> { inclusive = true }
}
}
)
}
// Wallpaper mode selection screen
composable<WallpaperModeSelectionRoute>(
enterTransition = enterForward,
exitTransition = exitForward,
popEnterTransition = enterBackward,
popExitTransition = exitBackward
) {
com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection.WallpaperModeSelectionScreen(
onModeSelected = {
navController.navigate(NotificationRoute) {
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
}
}
)
}
// Notification permission screen
composable<NotificationRoute>(
enterTransition = enterForward,
@@ -15,6 +15,9 @@ object NotificationRoute
@Serializable
object StoragePermissionRoute
@Serializable
object WallpaperModeSelectionRoute
@Serializable
object HomeRoute
@@ -92,38 +92,6 @@ private val DarkColors = darkColorScheme(
surfaceContainerLowest = md_theme_dark_surfaceContainerLowest,
)
private val AmoledDarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = Color(0xFF1C1B1E), // Near-black for OLED efficiency
onSecondary = Color(0xFFE6E1E5), // Soft gray instead of pure white
secondaryContainer = Color(0xFF2B2930), // Dark gray container
onSecondaryContainer = Color(0xFFE6E1E5),
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = Color(0xFFFFB4AB), // Softer error color from Material 3
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = Color(0xFF000000), // True black for OLED
onBackground = Color(0xFFE6E1E5), // Soft gray for better readability
surface = Color(0xFF000000), // True black for OLED
onSurface = Color(0xFFE6E1E5), // Soft gray for better readability
surfaceVariant = Color(0xFF1C1B1E), // Near-black variant
onSurfaceVariant = Color(0xFFC9C5CA), // Softer gray for secondary text
outline = Color(0xFF938F94), // Medium gray for outlines
inverseOnSurface = Color(0xFF1C1B1E),
inverseSurface = Color(0xFFE6E1E5),
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = Color(0xFF49454F),
scrim = Color(0xFF000000),
)
/**
* App theming for dynamic theming when supported and dark mode.
* Migrated to Material 3 Expressive design system with enhanced motion, typography, and shapes.
@@ -132,7 +100,6 @@ private val AmoledDarkColors = darkColorScheme(
@Composable
fun PaperizeTheme(
darkMode: Boolean?,
amoledMode: Boolean,
dynamicTheming: Boolean,
content: @Composable () -> Unit
) {
@@ -144,8 +111,7 @@ fun PaperizeTheme(
val colors = when {
isDynamicTheming && isDarkMode -> dynamicDarkColorScheme(context)
isDynamicTheming && !isDarkMode -> dynamicLightColorScheme(context)
isDarkMode && amoledMode -> AmoledDarkColors
isDarkMode && !amoledMode -> DarkColors
isDarkMode -> DarkColors
else -> LightColors
}
@@ -42,7 +42,7 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
@Composable
fun AlbumViewScreen(
albumId: String,
@Suppress("UNUSED_PARAMETER") albumId: String,
onBackClick: () -> Unit,
onNavigateToFolder: (String) -> Unit,
onNavigateToWallpaperView: (String, String) -> Unit,
@@ -156,7 +156,6 @@ fun AlbumViewScreen(
if (!isSelectionMode) {
AddAlbumAnimatedFab(
isLoading = false,
animate = true,
onImageClick = { imagePickerLauncher.launch(arrayOf("image/*")) },
onFolderClick = { folderPickerLauncher.launch(null) }
)
@@ -6,9 +6,11 @@ import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.toRoute
import com.anthonyla.paperize.core.util.detectMediaType
import com.anthonyla.paperize.core.util.generateId
import com.anthonyla.paperize.core.util.getFileName
import com.anthonyla.paperize.core.util.scanFolderForImages
import com.anthonyla.paperize.core.WallpaperMediaType
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.Folder
import com.anthonyla.paperize.domain.model.Wallpaper
@@ -75,14 +77,18 @@ class AlbumViewViewModel @Inject constructor(
fun addWallpapers(uris: List<String>) {
viewModelScope.launch {
val wallpapers = uris.mapIndexed { index, uri ->
val parsedUri = uri.toUri()
val mediaType = parsedUri.detectMediaType(context) ?: WallpaperMediaType.IMAGE
Wallpaper(
id = generateId(),
albumId = albumId,
folderId = null,
uri = uri,
fileName = uri.toUri().getFileName(context) ?: uri.substringAfterLast('/'),
fileName = parsedUri.getFileName(context) ?: uri.substringAfterLast('/'),
dateModified = System.currentTimeMillis(),
displayOrder = index
displayOrder = index,
mediaType = mediaType
)
}
when (albumRepository.addWallpapersToAlbum(albumId, wallpapers)) {
@@ -103,6 +109,8 @@ class AlbumViewViewModel @Inject constructor(
// Create folder with scanned wallpapers
val folderId = generateId()
val wallpapers = imageUris.mapIndexed { index, imageUri ->
val mediaType = imageUri.detectMediaType(context) ?: WallpaperMediaType.IMAGE
Wallpaper(
id = generateId(),
albumId = albumId,
@@ -110,7 +118,8 @@ class AlbumViewViewModel @Inject constructor(
uri = imageUri.toString(),
fileName = imageUri.getFileName(context) ?: imageUri.lastPathSegment ?: imageUri.toString().substringAfterLast('/'),
dateModified = System.currentTimeMillis(),
displayOrder = index
displayOrder = index,
mediaType = mediaType
)
}
@@ -37,7 +37,7 @@ enum class SortOption {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SortBottomSheet(
currentSort: SortOption,
@Suppress("UNUSED_PARAMETER") currentSort: SortOption,
onSortSelected: (SortOption) -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier
@@ -33,7 +33,7 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
@Composable
fun FolderViewScreen(
folderId: String,
@Suppress("UNUSED_PARAMETER") folderId: String,
onBackClick: () -> Unit,
onNavigateToWallpaperView: (String, String) -> Unit,
modifier: Modifier = Modifier,
@@ -1,5 +1,10 @@
package com.anthonyla.paperize.presentation.screens.home
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
@@ -9,12 +14,16 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
@@ -26,9 +35,12 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
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.presentation.screens.home.components.HomeTopBar
import com.anthonyla.paperize.presentation.screens.home.components.getTabItems
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
@@ -47,7 +59,10 @@ fun HomeScreen(
val albums by viewModel.albums.collectAsState()
val scheduleSettings by viewModel.scheduleSettings.collectAsState()
val appSettings by viewModel.appSettings.collectAsState()
val wallpaperMode by viewModel.wallpaperMode.collectAsState()
val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsState()
val coroutineScope = rememberCoroutineScope()
val context = LocalContext.current
val tabItems = getTabItems(
wallpaperTitle = stringResource(R.string.tab_wallpaper),
@@ -137,9 +152,11 @@ fun HomeScreen(
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) }
)
@@ -153,4 +170,66 @@ fun HomeScreen(
}
}
}
// Live Wallpaper Selection Prompt
if (showLiveWallpaperPrompt && wallpaperMode == WallpaperMode.LIVE) {
AlertDialog(
onDismissRequest = { viewModel.dismissLiveWallpaperPrompt() },
title = {
Text(
text = "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.",
style = MaterialTheme.typography.bodyMedium
)
Text(
text = "\nTap 'Open Wallpaper Picker' below to select Paperize from the list of available live wallpapers.",
style = MaterialTheme.typography.bodyMedium
)
}
},
confirmButton = {
Button(
onClick = {
viewModel.dismissLiveWallpaperPrompt()
try {
// Open live wallpaper chooser with Paperize pre-selected
val intent = Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER).apply {
putExtra(
WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
ComponentName(
context.packageName,
"com.anthonyla.paperize.service.livewallpaper.PaperizeLiveWallpaperService"
)
)
}
context.startActivity(intent)
} catch (e: Exception) {
// Fallback: Open general wallpaper settings
try {
val fallbackIntent = Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
context.startActivity(fallbackIntent)
} catch (e2: Exception) {
// Last resort: Open wallpaper settings
val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS)
context.startActivity(settingsIntent)
}
}
}
) {
Text("Open Wallpaper Picker")
}
},
dismissButton = {
TextButton(onClick = { viewModel.dismissLiveWallpaperPrompt() }) {
Text("Later")
}
}
)
}
}
@@ -7,7 +7,6 @@ import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.domain.model.Album
import com.anthonyla.paperize.domain.model.ScheduleSettings
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.usecase.CreateAlbumUseCase
import com.anthonyla.paperize.domain.usecase.DeleteAlbumUseCase
@@ -16,6 +15,7 @@ import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService
import com.anthonyla.paperize.service.worker.WallpaperScheduler
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
@@ -31,7 +31,6 @@ class HomeViewModel @Inject constructor(
getAlbumsUseCase: GetAlbumsUseCase,
private val createAlbumUseCase: CreateAlbumUseCase,
private val deleteAlbumUseCase: DeleteAlbumUseCase,
private val albumRepository: AlbumRepository,
private val settingsRepository: SettingsRepository,
private val wallpaperScheduler: WallpaperScheduler,
private val wallpaperRepository: com.anthonyla.paperize.domain.repository.WallpaperRepository
@@ -58,6 +57,21 @@ class HomeViewModel @Inject constructor(
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
)
// Show prompt to select live wallpaper when enabling changer in LIVE mode
private val _showLiveWallpaperPrompt = MutableStateFlow(false)
val showLiveWallpaperPrompt: StateFlow<Boolean> = _showLiveWallpaperPrompt
fun dismissLiveWallpaperPrompt() {
_showLiveWallpaperPrompt.value = false
}
fun createAlbum(name: String) {
viewModelScope.launch {
when (createAlbumUseCase(name)) {
@@ -114,19 +128,23 @@ class HomeViewModel @Inject constructor(
// Only change wallpaper and schedule if all required albums are selected
if (hasRequiredAlbums) {
val screenType = if (
updated.homeAlbumId == updated.lockAlbumId &&
updated.homeAlbumId != null &&
!updated.separateSchedules &&
updated.homeEnabled &&
updated.lockEnabled
) {
// Same album for both screens and not separately scheduled - use BOTH
ScreenType.BOTH
} else {
ScreenType.HOME
// In LIVE mode, don't trigger immediate wallpaper change - the live wallpaper service handles it
// In STATIC mode, trigger immediate change to update the wallpaper
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
val screenType = if (
updated.homeAlbumId == updated.lockAlbumId &&
updated.homeAlbumId != null &&
!updated.separateSchedules &&
updated.homeEnabled &&
updated.lockEnabled
) {
// Same album for both screens and not separately scheduled - use BOTH
ScreenType.BOTH
} else {
ScreenType.HOME
}
changeWallpaperNow(screenType)
}
changeWallpaperNow(screenType)
scheduleAlarms(updated)
} else {
// Not all required albums selected - cancel any existing schedules
@@ -176,19 +194,23 @@ class HomeViewModel @Inject constructor(
// Only change wallpaper and schedule if all required albums are selected
if (hasRequiredAlbums) {
val screenType = if (
updated.homeAlbumId == updated.lockAlbumId &&
updated.lockAlbumId != null &&
!updated.separateSchedules &&
updated.homeEnabled &&
updated.lockEnabled
) {
// Same album for both screens and not separately scheduled - use BOTH
ScreenType.BOTH
} else {
ScreenType.LOCK
// In LIVE mode, don't trigger immediate wallpaper change - the live wallpaper service handles it
// In STATIC mode, trigger immediate change to update the wallpaper
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
val screenType = if (
updated.homeAlbumId == updated.lockAlbumId &&
updated.lockAlbumId != null &&
!updated.separateSchedules &&
updated.homeEnabled &&
updated.lockEnabled
) {
// Same album for both screens and not separately scheduled - use BOTH
ScreenType.BOTH
} else {
ScreenType.LOCK
}
changeWallpaperNow(screenType)
}
changeWallpaperNow(screenType)
scheduleAlarms(updated)
} else {
// Not all required albums selected - cancel any existing schedules
@@ -214,6 +236,25 @@ class HomeViewModel @Inject constructor(
}
}
fun selectLiveAlbum(album: Album?) {
viewModelScope.launch {
settingsRepository.updateLiveAlbumId(album?.id)
val updated = settingsRepository.getScheduleSettings()
// If unselecting, disable changer
if (album == null) {
toggleWallpaperChanger(false)
} else if (updated.enableChanger) {
// Album selected and changer is enabled - schedule alarms
scheduleAlarms(updated)
} else {
// Album selected but changer is not enabled - enable it
toggleWallpaperChanger(true)
}
}
}
fun toggleWallpaperChanger(enabled: Boolean, onlyIfNotScheduled: Boolean = false) {
viewModelScope.launch {
// Use atomic update to prevent race conditions with album selection updates
@@ -223,22 +264,28 @@ 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
val hasRequiredAlbums = when {
updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive
updated.homeEnabled -> homeActive
updated.lockEnabled -> lockActive
else -> false
val hasRequiredAlbums = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
when {
updated.homeEnabled && updated.lockEnabled -> homeActive && lockActive
updated.homeEnabled -> homeActive
updated.lockEnabled -> lockActive
else -> false
}
} else {
updated.liveAlbumId != null
}
// Only change wallpaper and schedule if all required albums are selected
if (hasRequiredAlbums) {
// Only change wallpaper now if this is not a "check if scheduled" call
if (!onlyIfNotScheduled) {
val isSynced = homeActive && lockActive &&
updated.homeAlbumId == updated.lockAlbumId &&
// In LIVE mode, skip immediate wallpaper changes - the live wallpaper service handles it
if (!onlyIfNotScheduled && wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
val isSynced = homeActive && lockActive &&
updated.homeAlbumId == updated.lockAlbumId &&
!updated.separateSchedules
if (isSynced) {
changeWallpaperNow(ScreenType.BOTH)
@@ -248,6 +295,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
}
} else {
// Not all required albums selected - cancel any existing schedules
wallpaperScheduler.cancelAllWallpaperChanges()
@@ -295,16 +348,28 @@ class HomeViewModel @Inject constructor(
val lockActive = validated.lockEnabled && validated.lockAlbumId != null
// Determine if we have the required albums selected
val hasRequiredAlbums = when {
validated.homeEnabled && validated.lockEnabled -> homeActive && lockActive
validated.homeEnabled -> homeActive
validated.lockEnabled -> lockActive
else -> false
// Determine if we have the required albums selected
val hasRequiredAlbums = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
when {
validated.homeEnabled && validated.lockEnabled -> homeActive && lockActive
validated.homeEnabled -> homeActive
validated.lockEnabled -> lockActive
else -> false
}
} else {
validated.liveAlbumId != null
}
// Handle scheduling changes (interval, screen enable/disable, etc.)
if (validated.enableChanger && hasRequiredAlbums && schedulingChanged) {
scheduleAlarms(validated)
// Show live wallpaper selection prompt if in LIVE mode, changer was just enabled, and Paperize is NOT already active
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE &&
!currentSettings.enableChanger && validated.enableChanger &&
!com.anthonyla.paperize.core.util.isPaperizeLiveWallpaperActive(context)) {
_showLiveWallpaperPrompt.value = true
}
} else if (validated.enableChanger && !hasRequiredAlbums) {
// Changer enabled but required albums not selected - cancel existing schedules
wallpaperScheduler.cancelAllWallpaperChanges()
@@ -312,9 +377,11 @@ class HomeViewModel @Inject constructor(
// Handle display changes (scaling, effects, adaptive brightness)
// Reapply current wallpaper immediately to show the effect
if (validated.enableChanger && hasRequiredAlbums && displayChanged) {
val isSynced = homeActive && lockActive &&
validated.homeAlbumId == validated.lockAlbumId &&
// In LIVE mode, skip immediate wallpaper changes - the live wallpaper service handles it
if (validated.enableChanger && hasRequiredAlbums && displayChanged &&
wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.STATIC) {
val isSynced = homeActive && lockActive &&
validated.homeAlbumId == validated.lockAlbumId &&
!validated.separateSchedules
if (isSynced) {
changeWallpaperNow(ScreenType.BOTH)
@@ -15,7 +15,7 @@ import com.anthonyla.paperize.R
@Composable
fun HomeTopBar(
showSelectionModeAppBar: Boolean,
selectionCount: Int,
@Suppress("UNUSED_PARAMETER") selectionCount: Int,
onSettingsClick: () -> Unit
) {
if (!showSelectionModeAppBar) {
@@ -46,25 +46,25 @@ fun NotificationPermissionScreen(
)
}
var hasShownScreen by remember { mutableStateOf(false) }
var hasNavigated by remember { mutableStateOf(false) } // Single-use navigation flag
val permissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { isGranted ->
permissionGranted = isGranted
if (isGranted) {
onContinue()
// 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()
}
}
}
// Mark screen as shown after first composition
LaunchedEffect(Unit) {
hasShownScreen = true
}
// Auto-skip if permission granted after screen has been shown
// This prevents immediate navigation on first render if permission is already granted
LaunchedEffect(permissionGranted, hasShownScreen) {
if (permissionGranted && hasShownScreen) {
// 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
onContinue()
}
@@ -7,6 +7,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.Wallpaper
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
@@ -32,7 +33,10 @@ fun SettingsScreen(
viewModel: SettingsViewModel = hiltViewModel()
) {
val appSettings by viewModel.appSettings.collectAsState()
val wallpaperMode by viewModel.wallpaperMode.collectAsState()
var showResetDialog by remember { mutableStateOf(false) }
var showModeChangeDialog by remember { mutableStateOf(false) }
var pendingMode by remember { mutableStateOf<com.anthonyla.paperize.core.WallpaperMode?>(null) }
Scaffold(
topBar = {
@@ -58,6 +62,73 @@ fun SettingsScreen(
) {
Spacer(modifier = Modifier.height(AppSpacing.medium))
// Wallpaper Mode Section
SectionHeader(
icon = Icons.Filled.Wallpaper,
title = "Wallpaper Mode"
)
Spacer(modifier = Modifier.height(AppSpacing.small))
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 = "Current Mode",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
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"
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.Medium
)
}
FilledTonalButton(
onClick = {
pendingMode = when (wallpaperMode) {
com.anthonyla.paperize.core.WallpaperMode.STATIC -> com.anthonyla.paperize.core.WallpaperMode.LIVE
com.anthonyla.paperize.core.WallpaperMode.LIVE -> com.anthonyla.paperize.core.WallpaperMode.STATIC
}
showModeChangeDialog = true
}
) {
Text("Switch")
}
}
Spacer(modifier = Modifier.height(AppSpacing.small))
Text(
text = "Switching modes will reset all albums, wallpapers, and settings. This cannot be undone.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Spacer(modifier = Modifier.height(AppSpacing.large))
// Appearance Section
SectionHeader(
icon = Icons.Filled.Palette,
@@ -73,16 +144,6 @@ fun SettingsScreen(
onCheckedChange = { viewModel.updateDarkMode(it) }
)
if (appSettings.darkMode == true) {
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
SettingSwitchItem(
title = stringResource(R.string.amoled_mode),
description = stringResource(R.string.full_dark_mode),
checked = appSettings.amoledTheme,
onCheckedChange = { viewModel.updateAmoledTheme(it) }
)
}
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
SettingSwitchItem(
@@ -184,6 +245,41 @@ fun SettingsScreen(
}
)
}
if (showModeChangeDialog && pendingMode != null) {
AlertDialog(
onDismissRequest = {
showModeChangeDialog = false
pendingMode = null
},
title = { Text("Switch to ${if (pendingMode == com.anthonyla.paperize.core.WallpaperMode.LIVE) "Live Wallpaper" else "Static"} Mode?") },
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.")
},
confirmButton = {
TextButton(
onClick = {
pendingMode?.let { viewModel.switchWallpaperMode(it) }
showModeChangeDialog = false
pendingMode = null
},
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) {
Text("Switch Mode")
}
},
dismissButton = {
TextButton(onClick = {
showModeChangeDialog = false
pendingMode = null
}) {
Text(stringResource(R.string.cancel))
}
}
)
}
}
}
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.presentation.screens.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.domain.model.AppSettings
import com.anthonyla.paperize.domain.repository.AlbumRepository
import com.anthonyla.paperize.domain.repository.SettingsRepository
@@ -31,6 +32,13 @@ class SettingsViewModel @Inject constructor(
initialValue = AppSettings.default()
)
val wallpaperMode: StateFlow<WallpaperMode> = settingsRepository.getWallpaperModeFlow()
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = WallpaperMode.STATIC
)
fun updateDarkMode(enabled: Boolean) {
viewModelScope.launch {
// Use atomic update to prevent race conditions
@@ -38,13 +46,6 @@ class SettingsViewModel @Inject constructor(
}
}
fun updateAmoledTheme(enabled: Boolean) {
viewModelScope.launch {
// Use atomic update to prevent race conditions
settingsRepository.updateAmoledTheme(enabled)
}
}
fun updateDynamicTheming(enabled: Boolean) {
viewModelScope.launch {
// Use atomic update to prevent race conditions
@@ -66,6 +67,31 @@ class SettingsViewModel @Inject constructor(
}
}
/**
* Switch wallpaper mode and reset all data
* This is required because STATIC and LIVE modes have different capabilities
* and incompatible wallpaper types
*/
fun switchWallpaperMode(newMode: WallpaperMode) {
viewModelScope.launch {
// Cancel all scheduled wallpaper changes first
wallpaperScheduler.cancelAllWallpaperChanges()
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
when (albumRepository.deleteAllAlbums()) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
// Reset schedule settings to default (clears effects, intervals, etc.)
settingsRepository.clearScheduleSettings()
// Set new wallpaper mode
settingsRepository.setWallpaperMode(newMode)
}
}
/**
* Reset all app data - settings, albums, wallpapers, folders, queues, and alarms
* This completely resets the app to initial state as if just installed
@@ -65,7 +65,7 @@ import sh.calvin.reorderable.rememberReorderableLazyListState
@OptIn(ExperimentalSharedTransitionApi::class)
@Composable
fun SortViewScreen(
albumId: String,
@Suppress("UNUSED_PARAMETER") albumId: String,
onSaveClick: () -> Unit,
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
@@ -36,12 +36,16 @@ fun StoragePermissionScreen(
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
// Check permission status on resume (when user returns from settings)
DisposableEffect(Unit) {
val listener = object : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
permissionGranted = Environment.isExternalStorageManager()
// Only update if we haven't navigated yet
if (!hasNavigated) {
permissionGranted = Environment.isExternalStorageManager()
}
}
}
val lifecycleOwner = context as? LifecycleOwner
@@ -52,15 +56,10 @@ fun StoragePermissionScreen(
}
}
// Mark screen as shown after first composition
LaunchedEffect(Unit) {
hasShownScreen = true
}
// Auto-skip if permission granted after screen has been shown
// This prevents immediate navigation on first render if permission is already granted
LaunchedEffect(permissionGranted, hasShownScreen) {
if (permissionGranted && hasShownScreen) {
// 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
onContinue()
}
@@ -0,0 +1,182 @@
package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.LiveTv
import androidx.compose.material.icons.filled.Wallpaper
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import com.anthonyla.paperize.R
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.presentation.theme.AppSpacing
/**
* Wallpaper mode selection screen shown during onboarding
* Allows user to choose between STATIC and LIVE wallpaper modes
*/
@Composable
fun WallpaperModeSelectionScreen(
onModeSelected: () -> Unit,
modifier: Modifier = Modifier,
viewModel: WallpaperModeSelectionViewModel = hiltViewModel()
) {
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
)
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
)
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)
)
}
}
}
@Composable
private fun ModeSelectionCard(
title: String,
description: String,
icon: androidx.compose.ui.graphics.vector.ImageVector,
isSelected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Card(
onClick = onClick,
modifier = modifier.fillMaxWidth(),
shape = MaterialTheme.shapes.large,
colors = CardDefaults.cardColors(
containerColor = if (isSelected)
MaterialTheme.colorScheme.primaryContainer
else
MaterialTheme.colorScheme.surfaceContainerLow
),
border = if (isSelected)
BorderStroke(2.dp, MaterialTheme.colorScheme.primary)
else
null
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(AppSpacing.large),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(48.dp),
tint = if (isSelected)
MaterialTheme.colorScheme.primary
else
MaterialTheme.colorScheme.onSurfaceVariant
)
Spacer(modifier = Modifier.width(AppSpacing.medium))
Column(
modifier = Modifier.weight(1f)
) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.SemiBold,
color = if (isSelected)
MaterialTheme.colorScheme.onPrimaryContainer
else
MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
Text(
text = description,
style = MaterialTheme.typography.bodySmall,
color = if (isSelected)
MaterialTheme.colorScheme.onPrimaryContainer
else
MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (isSelected) {
Spacer(modifier = Modifier.width(AppSpacing.small))
RadioButton(
selected = true,
onClick = onClick
)
}
}
}
}
@@ -0,0 +1,39 @@
package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.domain.repository.SettingsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class WallpaperModeSelectionViewModel @Inject constructor(
private val settingsRepository: SettingsRepository,
private val albumRepository: com.anthonyla.paperize.domain.repository.AlbumRepository,
private val wallpaperScheduler: com.anthonyla.paperize.service.worker.WallpaperScheduler
) : ViewModel() {
/**
* Set wallpaper mode (STATIC or LIVE)
*/
fun setWallpaperMode(mode: WallpaperMode) {
viewModelScope.launch {
// Cancel all scheduled wallpaper changes first
wallpaperScheduler.cancelAllWallpaperChanges()
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
when (albumRepository.deleteAllAlbums()) {
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
}
// Reset schedule settings to default (clears effects, intervals, etc.)
settingsRepository.clearScheduleSettings()
settingsRepository.setWallpaperMode(mode)
}
}
}
@@ -0,0 +1,332 @@
package com.anthonyla.paperize.service.livewallpaper
import android.content.ContentResolver
import android.net.Uri
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.SurfaceHolder
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.savedstate.SavedStateRegistry
import androidx.savedstate.SavedStateRegistryController
import androidx.savedstate.SavedStateRegistryOwner
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.domain.repository.SettingsRepository
import com.anthonyla.paperize.domain.repository.WallpaperRepository
import com.anthonyla.paperize.service.livewallpaper.gl.GLWallpaperService
import com.anthonyla.paperize.service.livewallpaper.renderer.ContentUriImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.EmptyImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.ImageLoader
import com.anthonyla.paperize.service.livewallpaper.renderer.PaperizeWallpaperRenderer
import com.anthonyla.paperize.service.livewallpaper.renderer.PaperizeRenderController
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.core.util.isValid
import com.anthonyla.paperize.domain.model.Wallpaper
@EntryPoint
@InstallIn(SingletonComponent::class)
interface PaperizeLiveWallpaperEntryPoint {
fun settingsRepository(): SettingsRepository
fun wallpaperRepository(): WallpaperRepository
}
@AndroidEntryPoint
class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
companion object {
private const val TAG = "PaperizeLiveWallpaper"
}
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
override val lifecycle: Lifecycle
get() = lifecycleRegistry
override fun onCreate() {
super.onCreate()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
override fun onDestroy() {
super.onDestroy()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
override fun onCreateEngine(): Engine {
return PaperizeLiveWallpaperEngine()
}
inner class PaperizeLiveWallpaperEngine : GLEngine(),
LifecycleOwner,
SavedStateRegistryOwner,
PaperizeRenderController.Callbacks,
PaperizeWallpaperRenderer.Callbacks {
private lateinit var settingsRepository: SettingsRepository
private lateinit var wallpaperRepository: WallpaperRepository
private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
private val savedStateRegistryController = SavedStateRegistryController.create(this)
override val lifecycle: Lifecycle
get() = lifecycleRegistry
override val savedStateRegistry: SavedStateRegistry
get() = savedStateRegistryController.savedStateRegistry
private lateinit var renderer: PaperizeWallpaperRenderer
private lateinit var renderController: PaperizeRenderController
private val engineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private var currentAlbumId: String? = null
private val gestureDetector = GestureDetector(
this@PaperizeLiveWallpaperService,
object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent): Boolean {
handleDoubleTap()
return true
}
}
)
private val reloadReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent?.action == Constants.ACTION_RELOAD_WALLPAPER) {
Log.d(TAG, "Received reload broadcast")
renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate)
}
}
}
override fun onCreate(surfaceHolder: SurfaceHolder) {
super.onCreate(surfaceHolder)
Log.d(TAG, "Engine created")
savedStateRegistryController.performRestore(null)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
val entryPoint = EntryPointAccessors.fromApplication(
applicationContext,
PaperizeLiveWallpaperEntryPoint::class.java
)
settingsRepository = entryPoint.settingsRepository()
wallpaperRepository = entryPoint.wallpaperRepository()
renderer = PaperizeWallpaperRenderer(applicationContext, this)
renderController = object : PaperizeRenderController(renderer, this@PaperizeLiveWallpaperEngine, engineScope) {
override suspend fun openDownloadedCurrentArtwork(): ImageLoader {
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)
}
if (albumId == null) {
Log.w(TAG, "No album ID set for mode $mode")
return EmptyImageLoader
}
// Check if queue exists, build it if empty
val queueCheck = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
if (queueCheck == null) {
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
}
var wallpaper: Wallpaper? = null
var maxRetries = 10 // Prevent infinite loop
var queueRebuildAttempts = 0
while (wallpaper == null && maxRetries > 0) {
// Atomically get and remove from queue
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
if (candidate == null) {
queueRebuildAttempts++
if (queueRebuildAttempts > 2) {
Log.w(TAG, "No wallpapers in album $albumId after retries")
return EmptyImageLoader
}
// Rebuild queue
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
continue
}
// Validate URI
val uri = candidate.uri.toUri()
if (uri.isValid(contentResolver)) {
wallpaper = candidate
} else {
// Remove invalid wallpaper
wallpaperRepository.deleteWallpaper(candidate.id)
maxRetries--
}
}
if (wallpaper == null) {
Log.w(TAG, "No valid wallpaper found after retries")
return EmptyImageLoader
}
// Check if queue needs refilling
val queueSize = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
if (queueSize == null) {
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
}
return try {
val uri = wallpaper.uri.toUri()
ContentUriImageLoader(contentResolver, uri)
} catch (e: Exception) {
Log.e(TAG, "Error creating image loader", e)
EmptyImageLoader
}
}
}
lifecycle.addObserver(renderController)
setEGLContextClientVersion(2)
setEGLConfigChooser(8, 8, 8, 0, 0, 0)
setRenderer(renderer)
setRenderMode(GLWallpaperService.RENDERMODE_WHEN_DIRTY)
requestRender()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
// Trigger initial load
renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate)
// Observe settings changes
observeSettings()
// Register broadcast receiver
val filter = IntentFilter(Constants.ACTION_RELOAD_WALLPAPER)
ContextCompat.registerReceiver(
applicationContext,
reloadReceiver,
filter,
ContextCompat.RECEIVER_NOT_EXPORTED
)
}
private fun observeSettings() {
engineScope.launch {
combine(
settingsRepository.getScheduleSettingsFlow(),
settingsRepository.getWallpaperModeFlow()
) { settings, mode ->
Pair(settings, mode)
}.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)
}
renderer.updateEffects(effects)
// Reload if album changed
if (albumId != currentAlbumId) {
Log.d(TAG, "Album changed from $currentAlbumId to $albumId, reloading")
currentAlbumId = albumId
renderController.reloadCurrentArtwork()
}
}
}
}
override fun onSurfaceCreated(holder: SurfaceHolder) {
super.onSurfaceCreated(holder)
}
override fun onVisibilityChanged(visible: Boolean) {
renderController.visible = visible
super.onVisibilityChanged(visible)
}
override fun onOffsetsChanged(
xOffset: Float,
yOffset: Float,
xOffsetStep: Float,
yOffsetStep: Float,
xPixelOffset: Int,
yPixelOffset: Int
) {
super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset)
renderer.setNormalOffsetX(xOffset)
}
override fun onTouchEvent(event: MotionEvent) {
try {
gestureDetector.onTouchEvent(event)
} catch (e: Exception) {
Log.w(TAG, "Error processing touch event", e)
}
super.onTouchEvent(event)
}
override fun onDestroy() {
try {
applicationContext.unregisterReceiver(reloadReceiver)
} catch (e: Exception) {
Log.e(TAG, "Error unregistering receiver", e)
}
// Cleanup renderer resources on GL thread
queueEvent {
renderer.destroy()
}
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
engineScope.cancel()
super.onDestroy()
}
override fun queueEventOnGlThread(event: () -> Unit) {
queueEvent(event)
}
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
}
if (doubleTapEnabled) {
renderController.reloadCurrentArtwork(com.anthonyla.paperize.service.livewallpaper.renderer.ReloadImmediate)
}
}
}
}
}
@@ -0,0 +1,210 @@
package com.anthonyla.paperize.service.livewallpaper.gl
import android.graphics.Bitmap
import android.opengl.GLES20
import android.opengl.GLUtils
import android.util.Log
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import kotlin.math.ceil
import kotlin.math.min
/**
* Represents a picture as a collection of OpenGL textures (tiles).
* Large images are subdivided into 512x512 tiles to avoid texture size limits.
* Based on Muzei's GLPicture implementation.
*
* @property width Original bitmap width
* @property height Original bitmap height
*/
class GLPicture(bitmap: Bitmap) {
companion object {
private const val TAG = "GLPicture"
private const val TILE_SIZE = 512
}
val width = bitmap.width
val height = bitmap.height
private val tiles: Array<Tile>
private val cols: Int
private val rows: Int
init {
val maxTextureSize = min(GLUtil.getMaxTextureSize(), 2048)
val tileSize = min(TILE_SIZE, maxTextureSize)
cols = ceil(width.toFloat() / tileSize).toInt()
rows = ceil(height.toFloat() / tileSize).toInt()
Log.d(TAG, "Creating GLPicture: ${width}x${height}, tiling to ${cols}x${rows} (tile size: $tileSize)")
tiles = Array(cols * rows) { index ->
val col = index % cols
val row = index / cols
val tileX = col * tileSize
val tileY = row * tileSize
val tileWidth = min(tileSize, width - tileX)
val tileHeight = min(tileSize, height - tileY)
// Extract tile bitmap
val tileBitmap = Bitmap.createBitmap(bitmap, tileX, tileY, tileWidth, tileHeight)
// 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
left, top, // Top-left
right, top // Top-right
)
// Texture coordinates (full tile)
val texCoords = floatArrayOf(
0f, 1f, // Bottom-left
1f, 1f, // Bottom-right
0f, 0f, // Top-left
1f, 0f // Top-right
)
val vertexBuffer = createFloatBuffer(vertices)
val texCoordBuffer = createFloatBuffer(texCoords)
// Set vertex data
GLES20.glVertexAttribPointer(
aPositionHandle, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer
)
GLES20.glVertexAttribPointer(
aTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, texCoordBuffer
)
// Draw quad
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
}
// Disable vertex attribute arrays
GLES20.glDisableVertexAttribArray(aPositionHandle)
GLES20.glDisableVertexAttribArray(aTexCoordHandle)
}
/**
* Recycle all tile textures and free GPU memory.
* Must be called on GL thread.
*/
fun recycle() {
for (tile in tiles) {
GLUtil.deleteTexture(tile.textureId)
}
}
/**
* Load a bitmap as an OpenGL texture.
*/
private fun loadTexture(bitmap: Bitmap): Int {
val textureIds = IntArray(1)
GLES20.glGenTextures(1, textureIds, 0)
val textureId = textureIds[0]
if (textureId == 0) {
throw RuntimeException("Failed to generate texture ID")
}
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId)
// Set texture parameters
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
// Upload bitmap to GPU
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0)
val error = GLES20.glGetError()
if (error != GLES20.GL_NO_ERROR) {
GLES20.glDeleteTextures(1, intArrayOf(textureId), 0)
throw RuntimeException("Texture upload failed: error 0x${Integer.toHexString(error)}")
}
return textureId
}
/**
* Create a native-order float buffer from an array.
*/
private fun createFloatBuffer(data: FloatArray): FloatBuffer {
return ByteBuffer.allocateDirect(data.size * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(data)
position(0)
}
}
/**
* Represents a single tile of the picture.
*/
private data class Tile(
val textureId: Int,
val x: Int,
val y: Int,
val width: Int,
val height: Int
)
override fun toString(): String {
return "GLPicture(size=${width}x${height}, tiles=${cols}x${rows})"
}
}
@@ -0,0 +1,56 @@
package com.anthonyla.paperize.service.livewallpaper.gl
import android.util.Log
/**
* Handle for an OpenGL texture that manages lifecycle and prevents leaks.
* Textures must be explicitly recycled when no longer needed.
*
* @property textureId OpenGL texture ID
* @property width Texture width in pixels
* @property height Texture height in pixels
*/
class GLTextureHandle(
val textureId: Int,
val width: Int,
val height: Int
) {
companion object {
private const val TAG = "GLTextureHandle"
}
@Volatile
private var recycled = false
/**
* Recycle the texture and free GPU memory.
* This must be called on the GL thread.
*/
fun recycle() {
if (!recycled) {
GLUtil.deleteTexture(textureId)
recycled = true
}
}
/**
* Check if this texture has been recycled.
*/
fun isRecycled(): Boolean = recycled
/**
* Finalize method to detect leaked textures.
* Note: Cannot call GL functions from finalizer (wrong thread).
*/
@Suppress("removal")
protected fun finalize() {
if (!recycled) {
Log.w(TAG, "Texture $textureId (${width}x${height}) was not recycled! This is a memory leak.")
}
}
override fun toString(): String {
return "GLTextureHandle(id=$textureId, size=${width}x${height}, recycled=$recycled)"
}
}
@@ -0,0 +1,160 @@
package com.anthonyla.paperize.service.livewallpaper.gl
import android.opengl.GLES20
import android.util.Log
/**
* Utilities for OpenGL ES operations including shader compilation,
* program linking, and error checking.
*/
object GLUtil {
private const val TAG = "GLUtil"
/**
* Compile a shader from source code.
*
* @param type Shader type (GLES20.GL_VERTEX_SHADER or GLES20.GL_FRAGMENT_SHADER)
* @param source GLSL source code
* @return Shader handle
* @throws RuntimeException if compilation fails
*/
fun compileShader(type: Int, source: String): Int {
val shader = GLES20.glCreateShader(type)
if (shader == 0) {
throw RuntimeException("Failed to create shader")
}
GLES20.glShaderSource(shader, source)
GLES20.glCompileShader(shader)
val compiled = IntArray(1)
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0)
if (compiled[0] == 0) {
val log = GLES20.glGetShaderInfoLog(shader)
GLES20.glDeleteShader(shader)
val shaderType = if (type == GLES20.GL_VERTEX_SHADER) "vertex" else "fragment"
throw RuntimeException("Shader compilation failed ($shaderType):\n$log")
}
return shader
}
/**
* Create a program from vertex and fragment shaders.
*
* @param vertexShader Compiled vertex shader handle
* @param fragmentShader Compiled fragment shader handle
* @return Program handle
* @throws RuntimeException if linking fails
*/
fun createProgram(vertexShader: Int, fragmentShader: Int): Int {
val program = GLES20.glCreateProgram()
if (program == 0) {
throw RuntimeException("Failed to create program")
}
GLES20.glAttachShader(program, vertexShader)
checkGLError("glAttachShader (vertex)")
GLES20.glAttachShader(program, fragmentShader)
checkGLError("glAttachShader (fragment)")
GLES20.glLinkProgram(program)
val linked = IntArray(1)
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0)
if (linked[0] == 0) {
val log = GLES20.glGetProgramInfoLog(program)
GLES20.glDeleteProgram(program)
throw RuntimeException("Program linking failed:\n$log")
}
return program
}
/**
* Compile shaders and create a program in one call.
*
* @param vertexSource Vertex shader GLSL source
* @param fragmentSource Fragment shader GLSL source
* @return Program handle
* @throws RuntimeException if compilation or linking fails
*/
fun createProgram(vertexSource: String, fragmentSource: String): Int {
val vertexShader = compileShader(GLES20.GL_VERTEX_SHADER, vertexSource)
val fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource)
val program = createProgram(vertexShader, fragmentShader)
// Shaders can be deleted after linking
GLES20.glDeleteShader(vertexShader)
GLES20.glDeleteShader(fragmentShader)
return program
}
/**
* Check for OpenGL errors and throw if one occurred.
*
* @param operation Description of the operation for error message
* @throws RuntimeException if GL error occurred
*/
fun checkGLError(operation: String) {
val error = GLES20.glGetError()
if (error != GLES20.GL_NO_ERROR) {
val errorMsg = "GL error after $operation: 0x${Integer.toHexString(error)}"
Log.e(TAG, errorMsg)
throw RuntimeException(errorMsg)
}
}
/**
* Get the maximum texture size supported by the GPU.
*
* @return Maximum texture dimension in pixels
*/
fun getMaxTextureSize(): Int {
val maxSize = IntArray(1)
GLES20.glGetIntegerv(GLES20.GL_MAX_TEXTURE_SIZE, maxSize, 0)
return maxSize[0]
}
/**
* Delete a shader program and check for errors.
*
* @param program Program handle to delete
*/
fun deleteProgram(program: Int) {
if (program != 0) {
GLES20.glDeleteProgram(program)
checkGLError("glDeleteProgram")
}
}
/**
* Delete a texture and check for errors.
*
* @param texture Texture handle to delete
*/
fun deleteTexture(texture: Int) {
if (texture != 0) {
GLES20.glDeleteTextures(1, intArrayOf(texture), 0)
checkGLError("glDeleteTextures")
}
}
/**
* Delete a framebuffer and check for errors.
*
* @param framebuffer Framebuffer handle to delete
*/
fun deleteFramebuffer(framebuffer: Int) {
if (framebuffer != 0) {
GLES20.glDeleteFramebuffers(1, intArrayOf(framebuffer), 0)
checkGLError("glDeleteFramebuffers")
}
}
}
@@ -0,0 +1,426 @@
package com.anthonyla.paperize.service.livewallpaper.gl
import android.opengl.GLSurfaceView
import android.service.wallpaper.WallpaperService
import android.util.Log
import android.view.SurfaceHolder
import javax.microedition.khronos.egl.EGL10
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.egl.EGLContext
import javax.microedition.khronos.egl.EGLDisplay
import javax.microedition.khronos.egl.EGLSurface
import javax.microedition.khronos.opengles.GL10
/**
* Base class for OpenGL ES 2.0 based wallpaper services.
* Manages EGL context, rendering thread, and surface lifecycle.
* Based on GLSurfaceView but adapted for WallpaperService.Engine.
*/
abstract class GLWallpaperService : WallpaperService() {
companion object {
private const val TAG = "GLWallpaperService"
const val RENDERMODE_WHEN_DIRTY = 0
const val RENDERMODE_CONTINUOUSLY = 1
}
/**
* Abstract engine that supports OpenGL ES rendering.
* Subclasses should override onCreateEngine() to return an instance.
*/
abstract inner class GLEngine : Engine() {
private var glThread: GLThread? = null
private var renderer: GLSurfaceView.Renderer? = null
private var eglContextClientVersion = 2
private var internalRenderMode = RENDERMODE_WHEN_DIRTY
// EGL configuration
private var eglConfigChooser: EGLConfigChooser? = null
/**
* Set the renderer for this engine.
* Must be called before surface is created.
*/
fun setRenderer(renderer: GLSurfaceView.Renderer) {
this.renderer = renderer
}
/**
* Set the OpenGL ES context client version (2 or 3).
* Must be called before surface is created.
*/
fun setEGLContextClientVersion(version: Int) {
this.eglContextClientVersion = version
}
/**
* Set the EGL config chooser.
*/
fun setEGLConfigChooser(configChooser: EGLConfigChooser) {
this.eglConfigChooser = configChooser
}
/**
* Simplified EGL config chooser for RGB888 with no depth/stencil.
*/
fun setEGLConfigChooser(
redSize: Int,
greenSize: Int,
blueSize: Int,
alphaSize: Int,
depthSize: Int,
stencilSize: Int
) {
this.eglConfigChooser = SimpleEGLConfigChooser(
redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize, eglContextClientVersion
)
}
/**
* Set the render mode: RENDERMODE_WHEN_DIRTY or RENDERMODE_CONTINUOUSLY.
*/
fun setRenderMode(mode: Int) {
this.internalRenderMode = mode
}
/**
* Request a render. Only has effect if render mode is RENDERMODE_WHEN_DIRTY.
*/
fun requestRender() {
glThread?.requestRender()
}
/**
* Queue a runnable to be run on the GL thread.
*/
fun queueEvent(runnable: Runnable) {
glThread?.queueEvent(runnable)
}
override fun onCreate(surfaceHolder: SurfaceHolder) {
super.onCreate(surfaceHolder)
}
override fun onSurfaceCreated(holder: SurfaceHolder) {
super.onSurfaceCreated(holder)
val configChooser = eglConfigChooser ?: SimpleEGLConfigChooser(
8, 8, 8, 0, 0, 0, eglContextClientVersion
)
glThread = GLThread(
holder = holder,
renderer = renderer ?: throw IllegalStateException("Renderer not set"),
configChooser = configChooser,
eglContextClientVersion = eglContextClientVersion
).apply {
renderMode = this@GLEngine.internalRenderMode
start()
}
}
override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
super.onSurfaceChanged(holder, format, width, height)
glThread?.onWindowResize(width, height)
}
override fun onSurfaceDestroyed(holder: SurfaceHolder) {
super.onSurfaceDestroyed(holder)
glThread?.requestExitAndWait()
glThread = null
}
override fun onVisibilityChanged(visible: Boolean) {
super.onVisibilityChanged(visible)
if (visible) {
glThread?.onResume()
} else {
glThread?.onPause()
}
}
override fun onDestroy() {
super.onDestroy()
glThread?.requestExitAndWait()
glThread = null
}
}
/**
* GL rendering thread.
*/
private class GLThread(
private val holder: SurfaceHolder,
private val renderer: GLSurfaceView.Renderer,
private val configChooser: EGLConfigChooser,
private val eglContextClientVersion: Int
) : Thread("GLThread") {
@Volatile var renderMode = RENDERMODE_WHEN_DIRTY
private val eventQueue = mutableListOf<Runnable>()
private val lock = Object()
@Volatile private var shouldExit = false
@Volatile private var paused = false
@Volatile private var hasSurface = true
@Volatile private var width = 0
@Volatile private var height = 0
@Volatile private var requestRender = true
@Volatile private var sizeChanged = true
private var egl: EGL10? = null
private var eglDisplay: EGLDisplay? = null
private var eglSurface: EGLSurface? = null
private var eglContext: EGLContext? = null
private var gl: GL10? = null
fun requestRender() {
synchronized(lock) {
requestRender = true
lock.notifyAll()
}
}
fun queueEvent(runnable: Runnable) {
synchronized(eventQueue) {
eventQueue.add(runnable)
}
requestRender()
}
fun onWindowResize(width: Int, height: Int) {
synchronized(lock) {
this.width = width
this.height = height
sizeChanged = true
requestRender = true
lock.notifyAll()
}
}
fun onPause() {
synchronized(lock) {
paused = true
lock.notifyAll()
}
}
fun onResume() {
synchronized(lock) {
paused = false
requestRender = true
lock.notifyAll()
}
}
fun requestExitAndWait() {
synchronized(lock) {
shouldExit = true
lock.notifyAll()
}
try {
join()
} catch (e: InterruptedException) {
Log.w(TAG, "Thread join interrupted", e)
}
}
override fun run() {
try {
initGL()
while (true) {
var event: Runnable? = null
synchronized(lock) {
while (true) {
if (shouldExit) {
cleanupGL()
return
}
// Process events
synchronized(eventQueue) {
if (eventQueue.isNotEmpty()) {
event = eventQueue.removeAt(0)
break
}
}
// Check if we should render
val readyToDraw = hasSurface && !paused
if (readyToDraw && (renderMode == RENDERMODE_CONTINUOUSLY || requestRender)) {
requestRender = false
break
}
// Wait for event
lock.wait()
}
}
// Execute event
event?.let {
it.run()
continue
}
// Handle size change
if (sizeChanged) {
gl?.let { renderer.onSurfaceChanged(it, width, height) }
sizeChanged = false
}
// Render frame
gl?.let { renderer.onDrawFrame(it) }
// Swap buffers
egl?.let { eglInstance ->
if (!eglInstance.eglSwapBuffers(eglDisplay, eglSurface)) {
Log.w(TAG, "eglSwapBuffers failed")
}
}
// Yield to avoid hogging CPU
sleep(1)
}
} catch (e: Exception) {
Log.e(TAG, "GL thread error", e)
} finally {
cleanupGL()
}
}
private fun initGL() {
egl = EGLContext.getEGL() as EGL10
eglDisplay = egl?.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY)
if (eglDisplay == EGL10.EGL_NO_DISPLAY) {
throw RuntimeException("eglGetDisplay failed")
}
val version = IntArray(2)
if (egl?.eglInitialize(eglDisplay, version) == false) {
throw RuntimeException("eglInitialize failed")
}
val eglConfig = configChooser.chooseConfig(egl!!, eglDisplay!!)
val attribList = intArrayOf(
0x3098, // EGL_CONTEXT_CLIENT_VERSION
eglContextClientVersion,
EGL10.EGL_NONE
)
eglContext = egl?.eglCreateContext(
eglDisplay,
eglConfig,
EGL10.EGL_NO_CONTEXT,
attribList
)
if (eglContext == null || eglContext == EGL10.EGL_NO_CONTEXT) {
throw RuntimeException("eglCreateContext failed")
}
eglSurface = egl?.eglCreateWindowSurface(eglDisplay, eglConfig, holder, null)
if (eglSurface == null || eglSurface == EGL10.EGL_NO_SURFACE) {
throw RuntimeException("eglCreateWindowSurface failed")
}
if (egl?.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) == false) {
throw RuntimeException("eglMakeCurrent failed")
}
gl = eglContext?.gl as? GL10
gl?.let { renderer.onSurfaceCreated(it, eglConfig) }
}
private fun cleanupGL() {
egl?.let { eglInstance ->
eglInstance.eglMakeCurrent(
eglDisplay,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT
)
eglSurface?.let {
eglInstance.eglDestroySurface(eglDisplay, it)
}
eglContext?.let {
eglInstance.eglDestroyContext(eglDisplay, it)
}
eglInstance.eglTerminate(eglDisplay)
}
egl = null
eglDisplay = null
eglSurface = null
eglContext = null
gl = null
}
}
/**
* Interface for choosing EGL configuration.
*/
interface EGLConfigChooser {
fun chooseConfig(egl: EGL10, display: EGLDisplay): EGLConfig
}
/**
* Simple EGL config chooser that picks the first config matching the requirements.
*/
private class SimpleEGLConfigChooser(
private val redSize: Int,
private val greenSize: Int,
private val blueSize: Int,
private val alphaSize: Int,
private val depthSize: Int,
private val stencilSize: Int,
private val eglContextClientVersion: Int
) : EGLConfigChooser {
override fun chooseConfig(egl: EGL10, display: EGLDisplay): EGLConfig {
val renderableType = if (eglContextClientVersion >= 3) {
0x0040 // EGL_OPENGL_ES3_BIT
} else {
0x0004 // EGL_OPENGL_ES2_BIT
}
val 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,
0x3142, renderableType, // EGL_RENDERABLE_TYPE
EGL10.EGL_NONE
)
val numConfig = IntArray(1)
if (!egl.eglChooseConfig(display, configSpec, null, 0, numConfig)) {
throw RuntimeException("eglChooseConfig failed")
}
if (numConfig[0] <= 0) {
throw RuntimeException("No EGL configs match")
}
val configs = arrayOfNulls<EGLConfig>(numConfig[0])
if (!egl.eglChooseConfig(display, configSpec, configs, numConfig[0], numConfig)) {
throw RuntimeException("eglChooseConfig failed")
}
return configs[0] ?: throw RuntimeException("No config chosen")
}
}
}
@@ -0,0 +1,129 @@
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,
* texture coordinates, and adaptive parallax calculations.
*/
object GLGeometry {
/**
* Full-screen quad vertices in normalized device coordinates (-1 to 1).
* Layout: x, y for each vertex (2 floats per vertex, 4 vertices).
* Order: bottom-left, bottom-right, top-left, top-right (triangle strip).
*/
val VERTICES = floatArrayOf(
-1.0f, -1.0f, // Bottom-left
1.0f, -1.0f, // Bottom-right
-1.0f, 1.0f, // Top-left
1.0f, 1.0f // Top-right
)
/**
* Standard texture coordinates (0 to 1, Y-flipped for OpenGL convention).
* Layout: u, v for each vertex (2 floats per vertex, 4 vertices).
* Order: bottom-left, bottom-right, top-left, top-right.
*/
val TEX_COORDS = floatArrayOf(
0.0f, 1.0f, // Bottom-left
1.0f, 1.0f, // Bottom-right
0.0f, 0.0f, // Top-left
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.
* Required for passing vertex data to OpenGL.
*
* @param data Float array to convert
* @return FloatBuffer ready for use with OpenGL
*/
fun createFloatBuffer(data: FloatArray): FloatBuffer {
return ByteBuffer.allocateDirect(data.size * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(data)
position(0)
}
}
/**
* Update an existing FloatBuffer with new data.
* More efficient than creating a new buffer.
*
* @param buffer Buffer to update
* @param data New data to put in buffer
*/
fun updateFloatBuffer(buffer: FloatBuffer, data: FloatArray) {
buffer.clear()
buffer.put(data)
buffer.position(0)
}
}
@@ -0,0 +1,171 @@
package com.anthonyla.paperize.service.livewallpaper.renderer
/**
* GLSL shader programs for live wallpaper rendering.
* Includes vertex shaders and fragment shaders for two-pass blur and color effects.
*/
object GLShaders {
/**
* Simple vertex shader that passes through positions and texture coordinates.
* Used for all rendering passes.
*/
const val VERTEX_SHADER = """
attribute vec4 a_position;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
void main() {
gl_Position = a_position;
v_texCoord = a_texCoord;
}
"""
/**
* Simple fragment shader for basic texture rendering without effects.
* Used for testing or when no effects are enabled.
*/
const val SIMPLE_FRAGMENT_SHADER = """
precision mediump float;
uniform sampler2D u_texture;
uniform float u_alpha;
varying vec2 v_texCoord;
void main() {
vec4 color = texture2D(u_texture, v_texCoord);
gl_FragColor = vec4(color.rgb, color.a * u_alpha);
}
"""
/**
* Fragment shader for horizontal Gaussian blur pass.
* Uses 9-tap kernel for good quality and performance.
*/
const val BLUR_HORIZONTAL_FRAGMENT_SHADER = """
precision mediump float;
uniform sampler2D u_texture;
uniform vec2 u_resolution;
uniform float u_blurRadius;
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;
// 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];
}
gl_FragColor = color;
}
"""
/**
* Fragment shader for vertical Gaussian blur pass.
* Uses 9-tap kernel matching horizontal pass.
*/
const val BLUR_VERTICAL_FRAGMENT_SHADER = """
precision mediump float;
uniform sampler2D u_texture;
uniform vec2 u_resolution;
uniform float u_blurRadius;
varying vec2 v_texCoord;
void main() {
vec2 pixelSize = 1.0 / u_resolution;
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;
// 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];
}
gl_FragColor = color;
}
"""
/**
* Fragment shader for color effects (darken, vignette, grayscale).
* Applied after blur passes.
*/
const val EFFECTS_FRAGMENT_SHADER = """
precision mediump float;
uniform sampler2D u_texture;
uniform float u_alpha;
uniform float u_darkenFactor;
uniform float u_vignetteFactor;
uniform float u_grayscaleEnabled;
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);
}
gl_FragColor = vec4(color.rgb, color.a * u_alpha);
}
"""
/**
* Solid color fragment shader for debugging and UI overlays.
*/
const val COLOR_FRAGMENT_SHADER = """
precision mediump float;
uniform vec4 u_color;
void main() {
gl_FragColor = u_color;
}
"""
}
@@ -0,0 +1,158 @@
package com.anthonyla.paperize.service.livewallpaper.renderer
import android.content.ContentResolver
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.net.Uri
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.math.max
/**
* Sealed interface for loading images from different sources.
* Provides type-safe abstraction for image loading with automatic
* sample size calculation and memory optimization.
*/
sealed interface ImageLoader {
/**
* Load the image as a Bitmap with the specified target dimensions.
* The image will be downsampled to approximately match the target size.
*
* @param targetWidth Target width in pixels
* @param targetHeight Target height in pixels
* @return Loaded bitmap, or null if loading failed
*/
suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap?
}
/**
* Empty image loader that always returns null.
* Used as a null object pattern when no wallpaper is available.
*/
object EmptyImageLoader : ImageLoader {
override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? = null
}
/**
* Image loader for Android content URIs.
* Loads images from the MediaStore or other content providers.
*
* @property contentResolver Content resolver for URI access
* @property uri Content URI to load
*/
class ContentUriImageLoader(
private val contentResolver: ContentResolver,
private val uri: Uri
) : ImageLoader {
companion object {
private const val TAG = "ContentUriImageLoader"
}
override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? {
return withContext(Dispatchers.IO) {
try {
// Get image dimensions without loading pixel data
val dimensions = getImageDimensions() ?: return@withContext null
// Calculate optimal sample size
val sampleSize = calculateSampleSize(
dimensions.first,
dimensions.second,
targetWidth,
targetHeight
)
Log.d(TAG, "Loading image: ${dimensions.first}x${dimensions.second} -> " +
"${dimensions.first / sampleSize}x${dimensions.second / sampleSize} " +
"(sample size: $sampleSize)")
// Load bitmap with sampling
val source = ImageDecoder.createSource(contentResolver, uri)
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
decoder.setTargetSampleSize(sampleSize)
decoder.isMutableRequired = false // Immutable for GPU upload
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
}
} catch (e: Exception) {
Log.e(TAG, "Failed to load image from $uri", e)
null
}
}
}
/**
* Get image dimensions without loading the full bitmap.
*/
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
}
} catch (e: Exception) {
Log.e(TAG, "Failed to get image dimensions for $uri", e)
null
}
}
/**
* Calculate the optimal sample size for downsampling.
* Returns the largest power-of-2 sample size that still maintains
* image dimensions larger than or equal to target dimensions.
*
* @param width Source image width
* @param height Source image height
* @param targetWidth Target width
* @param targetHeight Target height
* @return Sample size (power of 2)
*/
private fun calculateSampleSize(
width: Int,
height: Int,
targetWidth: Int,
targetHeight: Int
): Int {
// Guard against invalid target dimensions
if (targetWidth <= 0 || targetHeight <= 0) {
Log.w(TAG, "Invalid target dimensions: ${targetWidth}x${targetHeight}, using original size")
return 1
}
// Guard against invalid source dimensions
if (width <=0 || height <= 0) {
Log.w(TAG, "Invalid source dimensions: ${width}x${height}")
return 1
}
var sampleSize = 1
if (width > targetWidth || height > targetHeight) {
val halfWidth = width / 2
val halfHeight = height / 2
// Calculate the largest sample size that is a power of 2 and keeps both
// dimensions larger than the target dimensions
while ((halfWidth / sampleSize) >= targetWidth &&
(halfHeight / sampleSize) >= targetHeight) {
sampleSize *= 2
}
}
// Ensure we don't downsample below target size
return max(1, sampleSize / 2)
}
}
@@ -0,0 +1,154 @@
package com.anthonyla.paperize.service.livewallpaper.renderer
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/**
* Abstract controller for managing wallpaper loading and rendering lifecycle.
* Handles visibility changes, load orchestration, and coordination between
* background loading and GL thread rendering.
*/
abstract class PaperizeRenderController(
private val renderer: PaperizeWallpaperRenderer,
private val callbacks: Callbacks,
private val controllerScope: CoroutineScope
) : DefaultLifecycleObserver {
companion object {
private const val TAG = "PaperizeRenderController"
private const val RELOAD_THROTTLE_MS = 250L
}
/**
* Callbacks for GL thread operations.
*/
interface Callbacks {
fun queueEventOnGlThread(event: () -> Unit)
fun requestRender()
}
@Volatile
var visible: Boolean = false
set(value) {
field = value
if (value) {
// When becoming visible, execute any pending reload
if (hasPendingReload) {
hasPendingReload = false
reloadCurrentArtwork(ReloadImmediate)
}
}
}
@Volatile
private var isLoading = false
@Volatile
private var hasPendingReload = false
private var throttleJob: Job? = null
/**
* Abstract method to open the current wallpaper for loading.
* Implemented by the service to integrate with queue system.
*
* @return ImageLoader for the current wallpaper
*/
protected abstract suspend fun openDownloadedCurrentArtwork(): ImageLoader
/**
* Reload the current wallpaper.
*
* @param reason Reload reason (immediate or queued)
*/
fun reloadCurrentArtwork(reason: ReloadReason = ReloadQueued) {
Log.d(TAG, "reloadCurrentArtwork: reason=$reason, visible=$visible, loading=$isLoading")
// If not visible, defer reload until visible
if (!visible) {
hasPendingReload = true
return
}
// If already loading, skip
if (isLoading) {
Log.d(TAG, "Already loading, skipping reload")
return
}
when (reason) {
is ReloadImmediate -> {
// Cancel any throttled reload and execute immediately
throttleJob?.cancel()
executeReload()
}
is ReloadQueued -> {
// Throttle reloads to avoid excessive processing
throttleJob?.cancel()
throttleJob = controllerScope.launch {
delay(RELOAD_THROTTLE_MS)
executeReload()
}
}
}
}
/**
* Execute wallpaper reload.
*/
private fun executeReload() {
isLoading = true
controllerScope.launch {
try {
// Get image loader from service
val loader = openDownloadedCurrentArtwork()
// Queue wallpaper loading on renderer
// Renderer will load bitmap in background and upload to GPU on GL thread
renderer.queueWallpaper(loader)
} catch (e: Exception) {
Log.e(TAG, "Error reloading wallpaper", e)
} finally {
isLoading = false
}
}
}
override fun onStart(owner: LifecycleOwner) {
Log.d(TAG, "onStart")
// Lifecycle started - ready for operation
}
override fun onStop(owner: LifecycleOwner) {
Log.d(TAG, "onStop")
// Lifecycle stopped - pause operations
throttleJob?.cancel()
}
override fun onDestroy(owner: LifecycleOwner) {
Log.d(TAG, "onDestroy")
throttleJob?.cancel()
}
}
/**
* Sealed class representing reload reason.
*/
sealed class ReloadReason
/**
* Immediate reload (triggered by user action like double-tap or broadcast).
*/
object ReloadImmediate : ReloadReason()
/**
* Queued reload (throttled to avoid excessive processing).
*/
object ReloadQueued : ReloadReason()
@@ -0,0 +1,458 @@
package com.anthonyla.paperize.service.livewallpaper.renderer
import android.content.Context
import android.graphics.Bitmap
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.util.Log
import com.anthonyla.paperize.domain.model.WallpaperEffects
import com.anthonyla.paperize.service.livewallpaper.gl.GLPicture
import com.anthonyla.paperize.service.livewallpaper.gl.GLUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import java.nio.FloatBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
/**
* Main OpenGL renderer for live wallpaper.
* Handles texture rendering, two-pass blur effects, color effects,
* crossfade animations, and parallax scrolling.
*
* @property context Application context
* @property callbacks Callbacks for queuing events on GL thread
*/
class PaperizeWallpaperRenderer(
private val context: Context,
private val callbacks: Callbacks
) : GLSurfaceView.Renderer {
companion object {
private const val TAG = "PaperizeRenderer"
private const val CROSSFADE_DURATION_FRAMES = 45 // 0.75s at 60fps
}
/**
* Callbacks for communication with the engine.
*/
interface Callbacks {
fun queueEventOnGlThread(event: () -> Unit)
fun requestRender()
}
// Surface dimensions
@Volatile private var surfaceWidth = 0
@Volatile private var surfaceHeight = 0
// Shader programs
private var simpleProgram = 0
private var blurHorizontalProgram = 0
private var blurVerticalProgram = 0
private var effectsProgram = 0
// Attribute/uniform locations (for effects program)
private var aPositionHandle = 0
private var aTexCoordHandle = 0
private var uTextureHandle = 0
private var uAlphaHandle = 0
private var uDarkenFactorHandle = 0
private var uVignetteFactorHandle = 0
private var uGrayscaleEnabledHandle = 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
// Current wallpaper
private var currentPicture: GLPicture? = null
// Crossfade state
private var nextPicture: GLPicture? = null
private var crossfadeProgress = 0f
// Effects
@Volatile private var currentEffects = WallpaperEffects()
// Parallax
@Volatile private var normalOffsetX = 0.5f
// Coroutine scope for background loading
private val loadingScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
Log.d(TAG, "onSurfaceCreated")
// Set clear color
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f)
// Enable blending for crossfade
GLES20.glEnable(GLES20.GL_BLEND)
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA)
// Compile shader programs
compileShaders()
// Create geometry buffers
vertexBuffer = GLGeometry.createFloatBuffer(GLGeometry.VERTICES)
texCoordBuffer = GLGeometry.createFloatBuffer(GLGeometry.TEX_COORDS)
Log.d(TAG, "Surface created successfully")
}
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
Log.d(TAG, "onSurfaceChanged: ${width}x${height}")
surfaceWidth = width
surfaceHeight = height
GLES20.glViewport(0, 0, width, height)
// Recreate framebuffer for blur at new resolution
createBlurFramebuffer(width, height)
}
override fun onDrawFrame(gl: GL10) {
// Clear screen
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
val current = currentPicture
val next = nextPicture
if (current == null && next == null) {
// No wallpaper to display
return
}
// Determine if we need blur
val blurRadius = if (currentEffects.enableBlur) {
(currentEffects.blurPercentage / 100.0f) * 25.0f
} else {
0f
}
// Draw current picture
current?.let { picture ->
val alpha = if (next != null) 1.0f - crossfadeProgress else 1.0f
drawPictureWithEffects(picture, alpha, blurRadius)
}
// Draw next picture (if crossfading)
next?.let { picture ->
drawPictureWithEffects(picture, crossfadeProgress, blurRadius)
// Update crossfade progress
crossfadeProgress += (1f / CROSSFADE_DURATION_FRAMES)
if (crossfadeProgress >= 1.0f) {
// Crossfade complete
currentPicture?.recycle()
currentPicture = picture
nextPicture = null
crossfadeProgress = 0f
Log.d(TAG, "Crossfade complete")
} else {
// Continue animating
callbacks.requestRender()
}
}
}
/**
* Draw a picture with full effects pipeline.
*/
private fun drawPictureWithEffects(picture: GLPicture, alpha: Float, blurRadius: Float) {
// Update texture coordinates for parallax
updateTextureCoordinates(picture)
if (blurRadius > 0.01f && currentEffects.enableBlur) {
// Two-pass blur pipeline
drawWithBlur(picture, alpha, blurRadius)
} else {
// No blur - direct render with color effects
drawWithColorEffects(picture, alpha)
}
}
/**
* Draw picture with two-pass blur followed by color effects.
*/
private fun drawWithBlur(picture: GLPicture, alpha: Float, blurRadius: Float) {
// Pass 1: Horizontal blur to FBO
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo)
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.glUniform1f(blurHRadiusHandle, blurRadius)
picture.draw(blurHorizontalProgram, aPositionHandle, aTexCoordHandle, surfaceWidth, surfaceHeight)
// Pass 2: Vertical blur from FBO to another FBO (not screen yet)
// We need the blur result as a texture to apply color effects
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
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)
// Bind the blurred texture
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture)
GLES20.glUniform1i(uTextureHandle, 0)
drawQuad()
}
/**
* Draw picture with color effects only (no blur).
*/
private fun drawWithColorEffects(picture: GLPicture, alpha: Float) {
// Render to screen with effects
GLES20.glUseProgram(effectsProgram)
// Set uniforms
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)
picture.draw(effectsProgram, aPositionHandle, aTexCoordHandle, surfaceWidth, surfaceHeight)
}
/**
* Update texture coordinates for parallax effect.
*/
private fun updateTextureCoordinates(picture: GLPicture) {
if (!currentEffects.enableParallax || currentEffects.parallaxIntensity == 0) {
// No parallax - use standard coordinates
GLGeometry.updateFloatBuffer(texCoordBuffer, GLGeometry.TEX_COORDS)
return
}
// Calculate parallax coordinates
val parallaxCoords = GLGeometry.calculateParallaxTexCoords(
normalOffsetX,
currentEffects.parallaxIntensity,
picture.width,
picture.height,
surfaceWidth,
surfaceHeight
)
GLGeometry.updateFloatBuffer(texCoordBuffer, parallaxCoords)
}
/**
* Draw a full-screen quad with current buffers.
*/
private fun drawQuad() {
GLES20.glEnableVertexAttribArray(aPositionHandle)
GLES20.glEnableVertexAttribArray(aTexCoordHandle)
GLES20.glVertexAttribPointer(aPositionHandle, 2, GLES20.GL_FLOAT, false, 0, vertexBuffer)
GLES20.glVertexAttribPointer(aTexCoordHandle, 2, GLES20.GL_FLOAT, false, 0, texCoordBuffer)
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
GLES20.glDisableVertexAttribArray(aPositionHandle)
GLES20.glDisableVertexAttribArray(aTexCoordHandle)
}
/**
* Compile all shader programs.
*/
private fun compileShaders() {
// Simple program
simpleProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.SIMPLE_FRAGMENT_SHADER)
// Blur programs
blurHorizontalProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.BLUR_HORIZONTAL_FRAGMENT_SHADER)
blurVerticalProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.BLUR_VERTICAL_FRAGMENT_SHADER)
// Effects program
effectsProgram = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.EFFECTS_FRAGMENT_SHADER)
// Get uniform/attribute locations for effects program
aPositionHandle = GLES20.glGetAttribLocation(effectsProgram, "a_position")
aTexCoordHandle = GLES20.glGetAttribLocation(effectsProgram, "a_texCoord")
uTextureHandle = GLES20.glGetUniformLocation(effectsProgram, "u_texture")
uAlphaHandle = GLES20.glGetUniformLocation(effectsProgram, "u_alpha")
uDarkenFactorHandle = GLES20.glGetUniformLocation(effectsProgram, "u_darkenFactor")
uVignetteFactorHandle = GLES20.glGetUniformLocation(effectsProgram, "u_vignetteFactor")
uGrayscaleEnabledHandle = GLES20.glGetUniformLocation(effectsProgram, "u_grayscaleEnabled")
// Note: Blur program uniforms are queried dynamically when needed
Log.d(TAG, "Shaders compiled successfully")
}
/**
* Create framebuffer for blur intermediate pass.
*/
private fun createBlurFramebuffer(width: Int, height: Int) {
// Delete old resources
if (blurFbo != 0) {
GLUtil.deleteFramebuffer(blurFbo)
}
if (blurTexture != 0) {
GLUtil.deleteTexture(blurTexture)
}
// Create texture for FBO
val textureIds = IntArray(1)
GLES20.glGenTextures(1, textureIds, 0)
blurTexture = textureIds[0]
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, blurTexture)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA, width, height, 0,
GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, null)
// Create framebuffer
val fboIds = IntArray(1)
GLES20.glGenFramebuffers(1, fboIds, 0)
blurFbo = fboIds[0]
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, blurFbo)
GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0,
GLES20.GL_TEXTURE_2D, blurTexture, 0)
val status = GLES20.glCheckFramebufferStatus(GLES20.GL_FRAMEBUFFER)
if (status != GLES20.GL_FRAMEBUFFER_COMPLETE) {
throw RuntimeException("Framebuffer not complete: $status")
}
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0)
Log.d(TAG, "Blur framebuffer created: ${width}x${height}")
}
/**
* Queue a new wallpaper for loading and display.
* This method can be called from any thread.
*
* @param imageLoader Image loader to use
*/
fun queueWallpaper(imageLoader: ImageLoader) {
loadingScope.launch {
try {
Log.d(TAG, "Loading wallpaper...")
val bitmap = imageLoader.load(surfaceWidth, surfaceHeight)
if (bitmap != null) {
Log.d(TAG, "Wallpaper loaded: ${bitmap.width}x${bitmap.height}")
// Upload to GPU on GL thread
callbacks.queueEventOnGlThread {
uploadBitmap(bitmap)
}
} else {
Log.w(TAG, "Failed to load wallpaper (null bitmap)")
}
} catch (e: Exception) {
Log.e(TAG, "Error loading wallpaper", e)
}
}
}
/**
* Upload a bitmap to GPU and start crossfade.
* Must be called on GL thread.
*/
private fun uploadBitmap(bitmap: Bitmap) {
try {
val picture = GLPicture(bitmap)
// Recycle bitmap (no longer needed after GPU upload)
bitmap.recycle()
// Start crossfade
nextPicture = picture
crossfadeProgress = 0f
callbacks.requestRender()
Log.d(TAG, "Wallpaper uploaded to GPU: $picture")
} catch (e: Exception) {
Log.e(TAG, "Failed to upload bitmap to GPU", e)
bitmap.recycle()
}
}
/**
* Update effects settings.
* Can be called from any thread.
*/
fun updateEffects(effects: WallpaperEffects) {
this.currentEffects = effects
callbacks.requestRender()
}
/**
* Set parallax scroll offset.
* Can be called from any thread.
*
* @param offset Normalized offset (0.0 = left, 1.0 = right)
*/
fun setNormalOffsetX(offset: Float) {
if (normalOffsetX != offset) {
normalOffsetX = offset
callbacks.requestRender()
}
}
/**
* Cleanup resources.
* Must be called on GL thread.
*/
fun destroy() {
loadingScope.cancel()
currentPicture?.recycle()
currentPicture = null
nextPicture?.recycle()
nextPicture = null
GLUtil.deleteProgram(simpleProgram)
GLUtil.deleteProgram(blurHorizontalProgram)
GLUtil.deleteProgram(blurVerticalProgram)
GLUtil.deleteProgram(effectsProgram)
GLUtil.deleteFramebuffer(blurFbo)
GLUtil.deleteTexture(blurTexture)
Log.d(TAG, "Renderer destroyed")
}
}
@@ -92,6 +92,10 @@ class WallpaperChangeService : Service() {
val settings = settingsRepository.getScheduleSettings()
when (screenType) {
ScreenType.LIVE -> {
// Live wallpaper changes are handled by the live wallpaper service
Log.d(TAG, "Live wallpaper - no action needed in service")
}
ScreenType.HOME -> {
val homeAlbumId = settings.homeAlbumId
if (homeAlbumId != null) {
@@ -69,6 +69,11 @@ class WallpaperChangeWorker @AssistedInject constructor(
val wallpaperManager = WallpaperManager.getInstance(context)
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")
}
ScreenType.HOME -> {
val homeAlbumId = settings.homeAlbumId
if (homeAlbumId != null) {
@@ -271,6 +271,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
}
}
@@ -279,6 +280,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
}
}
+10 -2
View File
@@ -87,8 +87,7 @@
<string name="paperize_is_running">Paperize is running</string>
<string name="next_wallpaper_change">Next wallpaper change: %1$s</string>
<string name="theme">Theme</string>
<string name="amoled_mode">AMOLED Mode</string>
<string name="full_dark_mode">Full dark mode</string>
<string name="wallpaper_changer">Wallpaper Changer</string>
<string name="enable_wallpaper_changer">Enable Wallpaper Changer</string>
<string name="lock">Lock</string>
<string name="change_vignette">Vignette Effect</string>
@@ -105,6 +104,13 @@
<string name="add_blur_to_the_image">Add blur to the image</string>
<string name="darken_the_edges_of_the_image">Darken the edges of the image</string>
<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="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>
<string name="live_wallpaper_description">Dynamic wallpapers with effects and interactive features</string>
<string name="visual_effects_note_live_mode">Note: Visual effects (blur, darken, vignette, grayscale) apply to all wallpapers in live mode.</string>
<string name="adaptive_brightness">Adaptive Brightness</string>
<string name="adjust_brightness_based_on_mode">Adjust brightness based on dark/light mode</string>
<string name="randomly_shuffle_the_wallpapers">Randomly shuffle the wallpapers</string>
@@ -142,6 +148,8 @@
<string name="home_album_label">Home Album</string>
<string name="scaling">Scaling</string>
<string name="wallpaper_effects_title">Wallpaper Effects</string>
<string name="visual_effects">Visual Effects</string>
<string name="interactive_effects">Interactive Effects</string>
<string name="current_wallpapers">Current Wallpapers</string>
<!-- Tab Titles -->
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/live_wallpaper_description"
android:settingsActivity="com.anthonyla.paperize.presentation.MainActivity"
android:thumbnail="@mipmap/app_icon" />