From 391bbb6bc075993d158466119d347c1580782563 Mon Sep 17 00:00:00 2001 From: Anthonyy232 Date: Fri, 28 Nov 2025 17:46:44 -0800 Subject: [PATCH] add live wallpaper --- .claude/settings.local.json | 7 +- app/src/main/AndroidManifest.xml | 17 + .../com/anthonyla/paperize/core/ScreenType.kt | 3 +- .../paperize/core/WallpaperMediaType.kt | 54 + .../anthonyla/paperize/core/WallpaperMode.kt | 40 + .../paperize/core/constants/Constants.kt | 33 +- .../paperize/core/util/WallpaperUtil.kt | 85 +- .../database/converters/TypeConverters.kt | 8 + .../data/database/dao/WallpaperQueueDao.kt | 11 - .../data/database/entities/WallpaperEntity.kt | 17 +- .../data/datastore/PreferencesManager.kt | 191 ++- .../paperize/data/mapper/WallpaperMapper.kt | 6 +- .../data/repository/SettingsRepositoryImpl.kt | 19 +- .../repository/WallpaperRepositoryImpl.kt | 11 +- .../paperize/domain/model/AppSettings.kt | 1 - .../paperize/domain/model/ScheduleSettings.kt | 6 +- .../paperize/domain/model/Wallpaper.kt | 4 +- .../paperize/domain/model/WallpaperEffects.kt | 12 +- .../domain/repository/SettingsRepository.kt | 35 +- .../domain/repository/WallpaperRepository.kt | 5 - .../paperize/presentation/MainActivity.kt | 1 - .../common/components/AddAlbumAnimatedFab.kt | 1 - .../presentation/common/components/Dialogs.kt | 66 - .../presentation/common/components/Pickers.kt | 4 +- .../common/navigation/NavigationGraph.kt | 18 +- .../presentation/common/navigation/Routes.kt | 3 + .../presentation/common/theme/Theme.kt | 36 +- .../screens/album_view/AlbumViewScreen.kt | 3 +- .../screens/album_view/AlbumViewViewModel.kt | 15 +- .../album_view/components/SortBottomSheet.kt | 2 +- .../screens/folder_view/FolderViewScreen.kt | 2 +- .../presentation/screens/home/HomeScreen.kt | 79 ++ .../screens/home/HomeViewModel.kt | 151 ++- .../screens/home/components/HomeTopBar.kt | 2 +- .../NotificationPermissionScreen.kt | 24 +- .../screens/settings/SettingsScreen.kt | 116 +- .../screens/settings/SettingsViewModel.kt | 40 +- .../screens/sort/SortViewScreen.kt | 2 +- .../storage/StoragePermissionScreen.kt | 19 +- .../screens/wallpaper/WallpaperScreen.kt | 1095 +++++++++++------ .../WallpaperModeSelectionScreen.kt | 182 +++ .../WallpaperModeSelectionViewModel.kt | 39 + .../PaperizeLiveWallpaperService.kt | 332 +++++ .../service/livewallpaper/gl/GLPicture.kt | 210 ++++ .../livewallpaper/gl/GLTextureHandle.kt | 56 + .../service/livewallpaper/gl/GLUtil.kt | 160 +++ .../livewallpaper/gl/GLWallpaperService.kt | 426 +++++++ .../livewallpaper/renderer/GLGeometry.kt | 129 ++ .../livewallpaper/renderer/GLShaders.kt | 171 +++ .../livewallpaper/renderer/ImageLoader.kt | 158 +++ .../renderer/PaperizeRenderController.kt | 154 +++ .../renderer/PaperizeWallpaperRenderer.kt | 458 +++++++ .../wallpaper/WallpaperChangeService.kt | 4 + .../service/worker/WallpaperChangeWorker.kt | 5 + .../service/worker/WallpaperScheduler.kt | 2 + app/src/main/res/values/strings.xml | 12 +- app/src/main/res/xml/wallpaper.xml | 5 + gradle/libs.versions.toml | 3 + 58 files changed, 4102 insertions(+), 648 deletions(-) create mode 100644 app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt create mode 100644 app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt create mode 100644 app/src/main/res/xml/wallpaper.xml diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 396654a..4072ca4 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -7,7 +7,12 @@ "WebFetch(domain:github.com)", "WebFetch(domain:raw.githubusercontent.com)", "Bash(dir:*)", - "Bash(./gradlew assembleDebug:*)" + "Bash(./gradlew assembleDebug:*)", + "Bash(./gradlew.bat assembleDebug)", + "Bash(cat:*)", + "Bash(find:*)", + "Bash(./gradlew compileDebugKotlin:*)", + "Bash(./gradlew clean:*)" ], "deny": [], "ask": [] diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 79d6da5..a017ba3 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -11,6 +11,8 @@ + + + + + + + + + + diff --git a/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt b/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt index 9b1b407..a9020d2 100644 --- a/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt +++ b/app/src/main/java/com/anthonyla/paperize/core/ScreenType.kt @@ -6,7 +6,8 @@ package com.anthonyla.paperize.core enum class ScreenType { HOME, LOCK, - BOTH; + BOTH, + LIVE; companion object { fun fromString(value: String?): ScreenType { diff --git a/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt new file mode 100644 index 0000000..c7775fa --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMediaType.kt @@ -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 + 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) } + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt new file mode 100644 index 0000000..b32476e --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/core/WallpaperMode.kt @@ -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 + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt b/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt index f541f89..b9a5b1a 100644 --- a/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt +++ b/app/src/main/java/com/anthonyla/paperize/core/constants/Constants.kt @@ -6,7 +6,7 @@ package com.anthonyla.paperize.core.constants object Constants { // Database const val DATABASE_NAME = "paperize_database" - const val DATABASE_VERSION = 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" } diff --git a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt index dff654b..8e3b031 100644 --- a/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt +++ b/app/src/main/java/com/anthonyla/paperize/core/util/WallpaperUtil.kt @@ -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 + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt b/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt index 5ee2509..4476a68 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/converters/TypeConverters.kt @@ -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 } diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt index bab348a..048461d 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/dao/WallpaperQueueDao.kt @@ -58,17 +58,6 @@ interface WallpaperQueueDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertQueueItems(items: List) - /** - * 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 diff --git a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt index f881c5c..7968435 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/database/entities/WallpaperEntity.kt @@ -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 ) diff --git a/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt b/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt index 0b42869..4869593 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/datastore/PreferencesManager.kt @@ -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 = 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 = 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() } } diff --git a/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt b/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt index fb008d4..00c0676 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/mapper/WallpaperMapper.kt @@ -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.toDomainModels(): List = map { it.toDomainModel() } diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt index e3ef33c..e6bc97f 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/repository/SettingsRepositoryImpl.kt @@ -1,5 +1,6 @@ package com.anthonyla.paperize.data.repository +import com.anthonyla.paperize.core.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 = + 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) diff --git a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt index 67f0db8..31ba72f 100644 --- a/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt +++ b/app/src/main/java/com/anthonyla/paperize/data/repository/WallpaperRepositoryImpl.kt @@ -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 { - return try { - wallpaperQueueDao.dequeueWallpaper(albumId, screenType) - Result.Success(Unit) - } catch (e: Exception) { - Result.Error(e) - } - } - override suspend fun clearAllQueues(): Result { 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) diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt index 13636df..23c621b 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/model/AppSettings.kt @@ -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, diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt index 2db6c7e..dfcf3eb 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/model/ScheduleSettings.kt @@ -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 } diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt index e772e3c..0d5aadc 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/model/Wallpaper.kt @@ -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) diff --git a/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt b/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt index a1e3ae3..5de7d0e 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/model/WallpaperEffects.kt @@ -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 { diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt index 4b200ee..82ebd34 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/SettingsRepository.kt @@ -1,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 + + /** + * 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) diff --git a/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt b/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt index b58387b..dcd697b 100644 --- a/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt +++ b/app/src/main/java/com/anthonyla/paperize/domain/repository/WallpaperRepository.kt @@ -85,11 +85,6 @@ interface WallpaperRepository { shuffle: Boolean = false ): Result - /** - * Dequeue wallpaper (remove first from queue) - */ - suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType): Result - /** * Clear all queues for all albums * Used when shuffle setting changes to force rebuild with new mode diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt b/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt index 37c459c..431f398 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/MainActivity.kt @@ -56,7 +56,6 @@ class MainActivity : ComponentActivity() { PaperizeTheme( darkMode = appSettings.darkMode, - amoledMode = appSettings.amoledTheme, dynamicTheming = appSettings.dynamicTheming ) { Surface( diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt index 5fb853f..215cfbf 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/AddAlbumAnimatedFab.kt @@ -41,7 +41,6 @@ import com.anthonyla.paperize.R @Composable fun AddAlbumAnimatedFab( isLoading: Boolean, - animate: Boolean, onImageClick: () -> Unit, onFolderClick: () -> Unit, modifier: Modifier = Modifier diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt index f22cf76..9258506 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Dialogs.kt @@ -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 */ diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt index a7425fc..ce45d7f 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/components/Pickers.kt @@ -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)) } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt index 8cc80ce..84b62ac 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/NavigationGraph.kt @@ -60,13 +60,29 @@ fun NavigationGraph( ) { StartupScreen( onAgree = { - navController.navigate(NotificationRoute) { + navController.navigate(WallpaperModeSelectionRoute) { popUpTo { inclusive = true } } } ) } + // Wallpaper mode selection screen + composable( + enterTransition = enterForward, + exitTransition = exitForward, + popEnterTransition = enterBackward, + popExitTransition = exitBackward + ) { + com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection.WallpaperModeSelectionScreen( + onModeSelected = { + navController.navigate(NotificationRoute) { + popUpTo { inclusive = true } + } + } + ) + } + // Notification permission screen composable( enterTransition = enterForward, diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt index 2ee3bf4..fb6bf83 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/navigation/Routes.kt @@ -15,6 +15,9 @@ object NotificationRoute @Serializable object StoragePermissionRoute +@Serializable +object WallpaperModeSelectionRoute + @Serializable object HomeRoute diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt index 2d1ca7f..49dd3aa 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/common/theme/Theme.kt @@ -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 } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt index cc70380..9f4b890 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewScreen.kt @@ -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) } ) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt index 876f6f0..b3f3e32 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/AlbumViewViewModel.kt @@ -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) { 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 ) } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt index 029bd9d..63091aa 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/album_view/components/SortBottomSheet.kt @@ -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 diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt index 4f839ff..067d13f 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/folder_view/FolderViewScreen.kt @@ -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, diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt index b78df32..991485e 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeScreen.kt @@ -1,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") + } + } + ) + } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt index 0a771de..9cb0b91 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/HomeViewModel.kt @@ -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 = _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) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt index d248305..f9339e9 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/home/components/HomeTopBar.kt @@ -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) { diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt index 7a45590..b884e8a 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/notification/NotificationPermissionScreen.kt @@ -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() } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt index 2373b81..f41d00e 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsScreen.kt @@ -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(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)) + } + } + ) + } } } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt index de9eb6d..a93081a 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/settings/SettingsViewModel.kt @@ -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 = 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 diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt index 4bb49e9..7d93528 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/sort/SortViewScreen.kt @@ -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, diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt index f04395d..843e43f 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/storage/StoragePermissionScreen.kt @@ -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() } diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt index c1a7a99..dfaffa8 100644 --- a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper/WallpaperScreen.kt @@ -8,13 +8,11 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.Lock -import androidx.compose.runtime.mutableLongStateOf import androidx.compose.material3.AlertDialog import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults @@ -32,6 +30,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable @@ -41,12 +40,11 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp import com.anthonyla.paperize.R import com.anthonyla.paperize.core.ScalingType import com.anthonyla.paperize.core.ScreenType +import com.anthonyla.paperize.core.WallpaperMode import com.anthonyla.paperize.core.constants.Constants -import kotlinx.coroutines.delay import com.anthonyla.paperize.domain.model.Album import com.anthonyla.paperize.domain.model.AppSettings import com.anthonyla.paperize.domain.model.ScheduleSettings @@ -57,9 +55,10 @@ import com.anthonyla.paperize.presentation.screens.wallpaper.components.SettingS import com.anthonyla.paperize.presentation.screens.wallpaper.components.SettingSwitchWithSlider import com.anthonyla.paperize.presentation.screens.wallpaper.components.TimeIntervalPicker import com.anthonyla.paperize.presentation.theme.AppSpacing +import kotlinx.coroutines.delay enum class AlbumSelectionContext { - HOME, LOCK, BOTH + HOME, LOCK, BOTH, LIVE } @Composable @@ -67,11 +66,13 @@ fun WallpaperScreen( albums: List, scheduleSettings: ScheduleSettings, appSettings: AppSettings, + wallpaperMode: WallpaperMode, onToggleChanger: (Boolean) -> Unit, onSelectHomeAlbum: (Album?) -> Unit, onSelectLockAlbum: (Album?) -> Unit, + onSelectLiveAlbum: (Album?) -> Unit, onUpdateScheduleSettings: (ScheduleSettings) -> Unit, - onChangeWallpaperNow: (ScreenType) -> Unit, + @Suppress("UNUSED_PARAMETER") onChangeWallpaperNow: (ScreenType) -> Unit, modifier: Modifier = Modifier ) { var showAlbumSelectionSheet by rememberSaveable { mutableStateOf(false) } @@ -97,6 +98,15 @@ fun WallpaperScreen( lastSettingsChangeTimestamp = System.currentTimeMillis() } + // Wrapper for immediate updates that cancels pending debounced updates + fun updateSettingsImmediate(newSettings: ScheduleSettings) { + // Cancel any pending debounced updates + pendingSettings = null + lastSettingsChangeTimestamp = 0L + // Apply the update immediately + onUpdateScheduleSettings(newSettings) + } + val homeEnabled = scheduleSettings.homeEnabled val lockEnabled = scheduleSettings.lockEnabled @@ -111,39 +121,35 @@ fun WallpaperScreen( scheduleSettings.lockAlbumId?.let { id -> albums.find { it.id == id } } } } + val liveAlbum by remember(albums, scheduleSettings.liveAlbumId) { + derivedStateOf { + scheduleSettings.liveAlbumId?.let { id -> albums.find { it.id == id } } + } + } // Auto-toggle wallpaper changer based on album selection state - // IMPORTANT: Check if actual album OBJECTS exist, not just IDs - // IDs might be stale (album deleted) which would cause invalid state - LaunchedEffect(homeAlbum, lockAlbum, homeEnabled, lockEnabled, scheduleSettings.homeAlbumId, scheduleSettings.lockAlbumId, albums) { - // Clean up stale album IDs (ID exists but album doesn't) - // IMPORTANT: Only cleanup if albums list has loaded (not empty) - // Otherwise we might clear valid IDs during initial load race condition - if (albums.isNotEmpty()) { - if (homeEnabled && scheduleSettings.homeAlbumId != null && homeAlbum == null) { - // Home album ID is set but album doesn't exist in loaded list - clear it - onSelectHomeAlbum(null) + // Use IDs as source of truth - if ID is set, we trust it's valid + // The ID will only be cleared when user explicitly deselects, not due to loading race conditions + LaunchedEffect(scheduleSettings.homeAlbumId, scheduleSettings.lockAlbumId, scheduleSettings.liveAlbumId, homeEnabled, lockEnabled, wallpaperMode) { + val allRequiredAlbumsSet = if (wallpaperMode == WallpaperMode.STATIC) { + when { + homeEnabled && lockEnabled -> { + // Both are enabled, require both album IDs to be set + scheduleSettings.homeAlbumId != null && scheduleSettings.lockAlbumId != null + } + homeEnabled -> { + // Only home is enabled, require home album ID to be set + scheduleSettings.homeAlbumId != null + } + lockEnabled -> { + // Only lock is enabled, require lock album ID to be set + scheduleSettings.lockAlbumId != null + } + else -> false // Neither enabled, should be disabled } - if (lockEnabled && scheduleSettings.lockAlbumId != null && lockAlbum == null) { - // Lock album ID is set but album doesn't exist in loaded list - clear it - onSelectLockAlbum(null) - } - } - - val allRequiredAlbumsSet = when { - homeEnabled && lockEnabled -> { - // Both are enabled, require both album OBJECTS to exist - homeAlbum != null && lockAlbum != null - } - homeEnabled -> { - // Only home is enabled, require home album OBJECT to exist - homeAlbum != null - } - lockEnabled -> { - // Only lock is enabled, require lock album OBJECT to exist - lockAlbum != null - } - else -> false // Neither enabled, should be disabled + } else { + // Live mode: require live album ID to be set + scheduleSettings.liveAlbumId != null } // Only update if current state doesn't match desired state (prevents redundant calls) @@ -178,211 +184,276 @@ fun WallpaperScreen( verticalArrangement = Arrangement.spacedBy(AppSpacing.small) ) { // Home and Lock Screen Toggles - Enhanced with better styling - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall), - horizontalArrangement = Arrangement.spacedBy(AppSpacing.small) - ) { - Card( - modifier = Modifier.weight(1f), - onClick = { - onUpdateScheduleSettings(scheduleSettings.copy(lockEnabled = !lockEnabled)) - }, - shape = MaterialTheme.shapes.large, - colors = CardDefaults.cardColors( - containerColor = if (lockEnabled) - MaterialTheme.colorScheme.primaryContainer - else - MaterialTheme.colorScheme.surfaceContainerHigh - ) + // Only show in Static Mode + if (wallpaperMode == WallpaperMode.STATIC) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall), + horizontalArrangement = Arrangement.spacedBy(AppSpacing.small) ) { - Column( - modifier = Modifier.padding(AppSpacing.large), - verticalArrangement = Arrangement.spacedBy(AppSpacing.small) + Card( + modifier = Modifier.weight(1f), + onClick = { + updateSettingsImmediate(scheduleSettings.copy(lockEnabled = !lockEnabled)) + }, + shape = MaterialTheme.shapes.large, + colors = CardDefaults.cardColors( + containerColor = if (lockEnabled) + MaterialTheme.colorScheme.primaryContainer + else + MaterialTheme.colorScheme.surfaceContainerHigh + ) ) { - Icon( - Icons.Default.Lock, - contentDescription = null, - tint = if (lockEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - text = stringResource(R.string.lock), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = if (lockEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - Text( - text = if (lockEnabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), - style = MaterialTheme.typography.bodySmall, - color = if (lockEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) + Column( + modifier = Modifier.padding(AppSpacing.large), + verticalArrangement = Arrangement.spacedBy(AppSpacing.small) + ) { + Icon( + Icons.Default.Lock, + contentDescription = null, + tint = if (lockEnabled) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + text = stringResource(R.string.lock), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = if (lockEnabled) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = if (lockEnabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), + style = MaterialTheme.typography.bodySmall, + color = if (lockEnabled) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } } - } - Card( - modifier = Modifier.weight(1f), - onClick = { - onUpdateScheduleSettings(scheduleSettings.copy(homeEnabled = !homeEnabled)) - }, - shape = MaterialTheme.shapes.large, - colors = CardDefaults.cardColors( - containerColor = if (homeEnabled) - MaterialTheme.colorScheme.primaryContainer - else - MaterialTheme.colorScheme.surfaceContainerHigh - ) - ) { - Column( - modifier = Modifier.padding(AppSpacing.large), - verticalArrangement = Arrangement.spacedBy(AppSpacing.small) + Card( + modifier = Modifier.weight(1f), + onClick = { + updateSettingsImmediate(scheduleSettings.copy(homeEnabled = !homeEnabled)) + }, + shape = MaterialTheme.shapes.large, + colors = CardDefaults.cardColors( + containerColor = if (homeEnabled) + MaterialTheme.colorScheme.primaryContainer + else + MaterialTheme.colorScheme.surfaceContainerHigh + ) ) { - Icon( - Icons.Default.Home, - contentDescription = null, - tint = if (homeEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant - ) - Text( - text = stringResource(R.string.home), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = if (homeEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - Text( - text = if (homeEnabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), - style = MaterialTheme.typography.bodySmall, - color = if (homeEnabled) - MaterialTheme.colorScheme.onPrimaryContainer - else - MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) + Column( + modifier = Modifier.padding(AppSpacing.large), + verticalArrangement = Arrangement.spacedBy(AppSpacing.small) + ) { + Icon( + Icons.Default.Home, + contentDescription = null, + tint = if (homeEnabled) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + text = stringResource(R.string.home), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = if (homeEnabled) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + Text( + text = if (homeEnabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), + style = MaterialTheme.typography.bodySmall, + color = if (homeEnabled) + MaterialTheme.colorScheme.onPrimaryContainer + else + MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } } } } // Album Selection - Enhanced with better card styling - if (homeEnabled && lockEnabled) { - // Lock Screen Album - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small), - onClick = { - albumSelectionContext = AlbumSelectionContext.LOCK - showAlbumSelectionSheet = true - }, - shape = MaterialTheme.shapes.medium, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ) - ) { - Row( + // Album Selection - Enhanced with better card styling + if (wallpaperMode == WallpaperMode.STATIC) { + if (homeEnabled && lockEnabled) { + // Lock Screen Album + Card( modifier = Modifier .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween, - verticalAlignment = Alignment.CenterVertically + .padding(horizontal = AppSpacing.small), + onClick = { + albumSelectionContext = AlbumSelectionContext.LOCK + showAlbumSelectionSheet = true + }, + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ) ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = lockAlbum?.name ?: stringResource(R.string.no_album_selected), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 2, - overflow = TextOverflow.Ellipsis - ) - Text( - text = stringResource(R.string.lock_album_label), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis + Row( + modifier = Modifier + .fillMaxWidth() + .padding(AppSpacing.large), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = lockAlbum?.name ?: if (scheduleSettings.lockAlbumId != null) { + "..." // Loading placeholder + } else { + stringResource(R.string.no_album_selected) + }, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Text( + text = stringResource(R.string.lock_album_label), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowForward, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary ) } - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - tint = MaterialTheme.colorScheme.primary - ) } - } - // Home Screen Album - Card( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = AppSpacing.small), - onClick = { - albumSelectionContext = AlbumSelectionContext.HOME - showAlbumSelectionSheet = true - }, - shape = MaterialTheme.shapes.medium, - colors = CardDefaults.cardColors( - containerColor = MaterialTheme.colorScheme.surfaceContainerLow - ) - ) { - Row( + // Home Screen Album + Card( modifier = Modifier .fillMaxWidth() - .padding(AppSpacing.large), - horizontalArrangement = Arrangement.SpaceBetween + .padding(horizontal = AppSpacing.small), + onClick = { + albumSelectionContext = AlbumSelectionContext.HOME + showAlbumSelectionSheet = true + }, + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ) ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = homeAlbum?.name ?: stringResource(R.string.no_album_selected), - style = MaterialTheme.typography.titleMedium, - maxLines = 2, - overflow = TextOverflow.Ellipsis + Row( + modifier = Modifier + .fillMaxWidth() + .padding(AppSpacing.large), + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = homeAlbum?.name ?: if (scheduleSettings.homeAlbumId != null) { + "..." // Loading placeholder + } else { + stringResource(R.string.no_album_selected) + }, + style = MaterialTheme.typography.titleMedium, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Text( + text = stringResource(R.string.home_album_label), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowForward, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant ) - Text( - text = stringResource(R.string.home_album_label), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis + } + } + } else { + // Single album selector when only one screen enabled + Surface( + color = MaterialTheme.colorScheme.surfaceContainerLow, + shape = MaterialTheme.shapes.medium, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = AppSpacing.small), + onClick = { + albumSelectionContext = AlbumSelectionContext.BOTH + showAlbumSelectionSheet = true + } + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(AppSpacing.large), + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f)) { + val currentAlbum = if (homeEnabled) homeAlbum else lockAlbum + val currentAlbumId = if (homeEnabled) scheduleSettings.homeAlbumId else scheduleSettings.lockAlbumId + Text( + text = currentAlbum?.name ?: if (currentAlbumId != null) { + "..." // Loading placeholder + } else { + stringResource(R.string.no_album_selected) + }, + style = MaterialTheme.typography.titleMedium, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + Text( + text = when { + homeEnabled && !lockEnabled -> stringResource(R.string.home) + stringResource(R.string.album_suffix) + !homeEnabled && lockEnabled -> stringResource(R.string.lock) + stringResource(R.string.album_suffix) + else -> stringResource(R.string.currently_selected_album) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + } + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowForward, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant ) } - Icon( - imageVector = Icons.AutoMirrored.Filled.ArrowForward, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant - ) } } } else { - // Single album selector when only one screen enabled + // Live Mode: Single Album Selector Surface( color = MaterialTheme.colorScheme.surfaceContainerLow, shape = MaterialTheme.shapes.medium, modifier = Modifier .fillMaxWidth() - .padding(horizontal = AppSpacing.small), + .padding(top = AppSpacing.small, start = AppSpacing.small, end = AppSpacing.small), onClick = { - albumSelectionContext = AlbumSelectionContext.BOTH + albumSelectionContext = AlbumSelectionContext.LIVE showAlbumSelectionSheet = true } ) { @@ -393,19 +464,18 @@ fun WallpaperScreen( horizontalArrangement = Arrangement.SpaceBetween ) { Column(modifier = Modifier.weight(1f)) { - val currentAlbum = if (homeEnabled) homeAlbum else lockAlbum Text( - text = currentAlbum?.name ?: stringResource(R.string.no_album_selected), + text = liveAlbum?.name ?: if (scheduleSettings.liveAlbumId != null) { + "..." // Loading placeholder + } else { + stringResource(R.string.no_album_selected) + }, style = MaterialTheme.typography.titleMedium, maxLines = 2, overflow = TextOverflow.Ellipsis ) Text( - text = when { - homeEnabled && !lockEnabled -> stringResource(R.string.home) + stringResource(R.string.album_suffix) - !homeEnabled && lockEnabled -> stringResource(R.string.lock) + stringResource(R.string.album_suffix) - else -> stringResource(R.string.currently_selected_album) - }, + text = stringResource(R.string.currently_selected_album), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, @@ -422,23 +492,72 @@ fun WallpaperScreen( } // Individual scheduling (only show if both screens enabled and changer is enabled) - if (scheduleSettings.enableChanger && homeEnabled && lockEnabled) { + if (wallpaperMode == WallpaperMode.STATIC && scheduleSettings.enableChanger && homeEnabled && lockEnabled) { SettingSwitchItem( title = stringResource(R.string.individual_scheduling), description = stringResource(R.string.show_interval_sliders), checked = scheduleSettings.separateSchedules, onCheckedChange = { enabled -> - onUpdateScheduleSettings(scheduleSettings.copy(separateSchedules = enabled)) + updateSettingsImmediate(scheduleSettings.copy(separateSchedules = enabled)) } ) } - // Time interval pickers (only show if changer is enabled) - if (scheduleSettings.enableChanger) { - if (!scheduleSettings.separateSchedules || !homeEnabled || !lockEnabled) { + // Check if an album is selected (at least one screen enabled with album ID set) + val hasAlbumSelected = if (wallpaperMode == WallpaperMode.STATIC) { + (homeEnabled && scheduleSettings.homeAlbumId != null) || + (lockEnabled && scheduleSettings.lockAlbumId != null) + } else { + scheduleSettings.liveAlbumId != null + } + + // Time interval pickers (only show if album is selected) + if (hasAlbumSelected) { + if (wallpaperMode == WallpaperMode.STATIC) { + if (!scheduleSettings.separateSchedules || !homeEnabled || !lockEnabled) { + TimeIntervalPicker( + title = stringResource(R.string.interval_text), + minutes = scheduleSettings.homeIntervalMinutes, + onMinutesChange = { minutes -> + onUpdateScheduleSettings( + scheduleSettings.copy( + homeIntervalMinutes = minutes, + lockIntervalMinutes = minutes + ) + ) + } + ) + } else { + // Lock screen interval picker first (when individual scheduling is enabled) + if (lockEnabled) { + TimeIntervalPicker( + title = stringResource(R.string.lock_screen_btn), + minutes = scheduleSettings.lockIntervalMinutes, + onMinutesChange = { minutes -> + onUpdateScheduleSettings( + scheduleSettings.copy(lockIntervalMinutes = minutes) + ) + } + ) + } + // Home screen interval picker second + if (homeEnabled) { + TimeIntervalPicker( + title = stringResource(R.string.home_screen_btn), + minutes = scheduleSettings.homeIntervalMinutes, + onMinutesChange = { minutes -> + onUpdateScheduleSettings( + scheduleSettings.copy(homeIntervalMinutes = minutes) + ) + } + ) + } + } + } else { + // Live Mode: Single Interval Picker TimeIntervalPicker( title = stringResource(R.string.interval_text), - minutes = scheduleSettings.homeIntervalMinutes, + minutes = scheduleSettings.homeIntervalMinutes, // Reuse home interval for Live onMinutesChange = { minutes -> onUpdateScheduleSettings( scheduleSettings.copy( @@ -448,40 +567,16 @@ fun WallpaperScreen( ) } ) - } else { - // Lock screen interval picker first (when individual scheduling is enabled) - if (lockEnabled) { - TimeIntervalPicker( - title = stringResource(R.string.lock_screen_btn), - minutes = scheduleSettings.lockIntervalMinutes, - onMinutesChange = { minutes -> - onUpdateScheduleSettings( - scheduleSettings.copy(lockIntervalMinutes = minutes) - ) - } - ) - } - // Home screen interval picker second - if (homeEnabled) { - TimeIntervalPicker( - title = stringResource(R.string.home_screen_btn), - minutes = scheduleSettings.homeIntervalMinutes, - onMinutesChange = { minutes -> - onUpdateScheduleSettings( - scheduleSettings.copy(homeIntervalMinutes = minutes) - ) - } - ) - } } } HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small)) - // Current Wallpaper Preview - CurrentWallpaperPreview(animate = appSettings.animate) - - HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small)) + // Current Wallpaper Preview (Static Mode Only) + if (wallpaperMode == WallpaperMode.STATIC) { + CurrentWallpaperPreview(animate = appSettings.animate) + HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small)) + } // Effects Section Header Text( @@ -493,7 +588,7 @@ fun WallpaperScreen( overflow = TextOverflow.Ellipsis ) - // Scaling Options + // Scaling Options Card Card( shape = MaterialTheme.shapes.medium, colors = CardDefaults.cardColors( @@ -510,7 +605,7 @@ fun WallpaperScreen( Text( text = stringResource(R.string.scaling), style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.W500, + fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -549,154 +644,367 @@ fun WallpaperScreen( } } - // Darken/Brightness - SettingSwitchWithSlider( - title = R.string.change_brightness, - description = R.string.change_the_image_brightness, - checked = when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableDarken && scheduleSettings.lockEffects.enableDarken - homeEnabled -> scheduleSettings.homeEffects.enableDarken - else -> scheduleSettings.lockEffects.enableDarken - }, - onCheckedChange = { enabled -> - onUpdateScheduleSettings( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableDarken = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableDarken = enabled) else scheduleSettings.lockEffects - ) - ) - }, - // Show separate sliders only when both enabled AND separate schedules is on - bothEnabled = homeEnabled && lockEnabled && scheduleSettings.separateSchedules, - homePercentage = scheduleSettings.homeEffects.darkenPercentage, - lockPercentage = scheduleSettings.lockEffects.darkenPercentage, - onPercentageChange = { homePercent, lockPercent -> - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(darkenPercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(darkenPercentage = lockPercent) else scheduleSettings.lockEffects - ) + // Shuffle Card + Card( + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ), + modifier = Modifier + .fillMaxWidth() + .padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)) + ) { + Column( + modifier = Modifier.padding(AppSpacing.large), + verticalArrangement = Arrangement.spacedBy(AppSpacing.medium) + ) { + SettingSwitch( + title = R.string.shuffle, + description = if (scheduleSettings.shuffleEnabled && !scheduleSettings.separateSchedules) null else R.string.randomly_shuffle_the_wallpapers, + checked = scheduleSettings.shuffleEnabled, + onCheckedChange = { enabled -> + updateSettingsImmediate(scheduleSettings.copy(shuffleEnabled = enabled)) + } ) } - ) + } - // Blur - SettingSwitchWithSlider( - title = R.string.change_blur, - description = R.string.add_blur_to_the_image, - checked = when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableBlur && scheduleSettings.lockEffects.enableBlur - homeEnabled -> scheduleSettings.homeEffects.enableBlur - else -> scheduleSettings.lockEffects.enableBlur - }, - onCheckedChange = { enabled -> - onUpdateScheduleSettings( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableBlur = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableBlur = enabled) else scheduleSettings.lockEffects - ) + // Visual Effects Group + Card( + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ), + modifier = Modifier + .fillMaxWidth() + .padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)) + ) { + Column( + modifier = Modifier.padding(AppSpacing.large), + verticalArrangement = Arrangement.spacedBy(AppSpacing.small) + ) { + Text( + text = stringResource(R.string.visual_effects), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(bottom = AppSpacing.small), + maxLines = 1, + overflow = TextOverflow.Ellipsis ) - }, - // Show separate sliders only when both enabled AND separate schedules is on - bothEnabled = homeEnabled && lockEnabled && scheduleSettings.separateSchedules, - homePercentage = scheduleSettings.homeEffects.blurPercentage, - lockPercentage = scheduleSettings.lockEffects.blurPercentage, - onPercentageChange = { homePercent, lockPercent -> - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(blurPercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(blurPercentage = lockPercent) else scheduleSettings.lockEffects - ) - ) - } - ) - // Vignette - SettingSwitchWithSlider( - title = R.string.change_vignette, - description = R.string.darken_the_edges_of_the_image, - checked = when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableVignette && scheduleSettings.lockEffects.enableVignette - homeEnabled -> scheduleSettings.homeEffects.enableVignette - else -> scheduleSettings.lockEffects.enableVignette - }, - onCheckedChange = { enabled -> - onUpdateScheduleSettings( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableVignette = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableVignette = enabled) else scheduleSettings.lockEffects - ) + // Darken/Brightness + SettingSwitchWithSlider( + title = R.string.change_brightness, + description = R.string.change_the_image_brightness, + checked = if (wallpaperMode == WallpaperMode.STATIC) { + when { + homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableDarken && scheduleSettings.lockEffects.enableDarken + homeEnabled -> scheduleSettings.homeEffects.enableDarken + else -> scheduleSettings.lockEffects.enableDarken + } + } else { + scheduleSettings.liveEffects.enableDarken + }, + onCheckedChange = { enabled -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsImmediate( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableDarken = enabled) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableDarken = enabled) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsImmediate( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(enableDarken = enabled) + ) + ) + } + }, + // Show separate sliders only when both enabled AND separate schedules is on (Static only) + bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules, + homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.darkenPercentage else scheduleSettings.liveEffects.darkenPercentage, + lockPercentage = scheduleSettings.lockEffects.darkenPercentage, + onPercentageChange = { homePercent, lockPercent -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsDebounced( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(darkenPercentage = homePercent) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(darkenPercentage = lockPercent) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsDebounced( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(darkenPercentage = homePercent) + ) + ) + } + } ) - }, - // Show separate sliders only when both enabled AND separate schedules is on - bothEnabled = homeEnabled && lockEnabled && scheduleSettings.separateSchedules, - homePercentage = scheduleSettings.homeEffects.vignettePercentage, - lockPercentage = scheduleSettings.lockEffects.vignettePercentage, - onPercentageChange = { homePercent, lockPercent -> - updateSettingsDebounced( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(vignettePercentage = homePercent) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(vignettePercentage = lockPercent) else scheduleSettings.lockEffects - ) + + // Blur + SettingSwitchWithSlider( + title = R.string.change_blur, + description = R.string.add_blur_to_the_image, + checked = if (wallpaperMode == WallpaperMode.STATIC) { + when { + homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableBlur && scheduleSettings.lockEffects.enableBlur + homeEnabled -> scheduleSettings.homeEffects.enableBlur + else -> scheduleSettings.lockEffects.enableBlur + } + } else { + scheduleSettings.liveEffects.enableBlur + }, + onCheckedChange = { enabled -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsImmediate( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableBlur = enabled) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableBlur = enabled) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsImmediate( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(enableBlur = enabled) + ) + ) + } + }, + // Show separate sliders only when both enabled AND separate schedules is on (Static only) + bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules, + homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.blurPercentage else scheduleSettings.liveEffects.blurPercentage, + lockPercentage = scheduleSettings.lockEffects.blurPercentage, + onPercentageChange = { homePercent, lockPercent -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsDebounced( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(blurPercentage = homePercent) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(blurPercentage = lockPercent) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsDebounced( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(blurPercentage = homePercent) + ) + ) + } + } + ) + + // Vignette + SettingSwitchWithSlider( + title = R.string.change_vignette, + description = R.string.darken_the_edges_of_the_image, + checked = if (wallpaperMode == WallpaperMode.STATIC) { + when { + homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableVignette && scheduleSettings.lockEffects.enableVignette + homeEnabled -> scheduleSettings.homeEffects.enableVignette + else -> scheduleSettings.lockEffects.enableVignette + } + } else { + scheduleSettings.liveEffects.enableVignette + }, + onCheckedChange = { enabled -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsImmediate( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableVignette = enabled) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableVignette = enabled) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsImmediate( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(enableVignette = enabled) + ) + ) + } + }, + // Show separate sliders only when both enabled AND separate schedules is on (Static only) + bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules, + homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.vignettePercentage else scheduleSettings.liveEffects.vignettePercentage, + lockPercentage = scheduleSettings.lockEffects.vignettePercentage, + onPercentageChange = { homePercent, lockPercent -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsDebounced( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(vignettePercentage = homePercent) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(vignettePercentage = lockPercent) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsDebounced( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(vignettePercentage = homePercent) + ) + ) + } + } + ) + + // Grayscale + SettingSwitch( + title = R.string.gray_filter, + description = if ((if (wallpaperMode == WallpaperMode.STATIC) { + when { + homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale + homeEnabled -> scheduleSettings.homeEffects.enableGrayscale + else -> scheduleSettings.lockEffects.enableGrayscale + } + } else { + scheduleSettings.liveEffects.enableGrayscale + }) && !scheduleSettings.separateSchedules) null else R.string.make_the_colors_grayscale, + checked = if (wallpaperMode == WallpaperMode.STATIC) { + when { + homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale + homeEnabled -> scheduleSettings.homeEffects.enableGrayscale + else -> scheduleSettings.lockEffects.enableGrayscale + } + } else { + scheduleSettings.liveEffects.enableGrayscale + }, + onCheckedChange = { enabled -> + if (wallpaperMode == WallpaperMode.STATIC) { + updateSettingsImmediate( + scheduleSettings.copy( + homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableGrayscale = enabled) else scheduleSettings.homeEffects, + lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableGrayscale = enabled) else scheduleSettings.lockEffects + ) + ) + } else { + updateSettingsImmediate( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(enableGrayscale = enabled) + ) + ) + } + } + ) + + // Adaptive Brightness + SettingSwitch( + title = R.string.adaptive_brightness, + description = if (scheduleSettings.adaptiveBrightness && !scheduleSettings.separateSchedules) null else R.string.adjust_brightness_based_on_mode, + checked = scheduleSettings.adaptiveBrightness, + onCheckedChange = { enabled -> + updateSettingsImmediate(scheduleSettings.copy(adaptiveBrightness = enabled)) + } ) } - ) + } - // Grayscale - SettingSwitch( - title = R.string.gray_filter, - description = if (when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale - homeEnabled -> scheduleSettings.homeEffects.enableGrayscale - else -> scheduleSettings.lockEffects.enableGrayscale - } && !scheduleSettings.separateSchedules) null else R.string.make_the_colors_grayscale, - checked = when { - homeEnabled && lockEnabled -> scheduleSettings.homeEffects.enableGrayscale && scheduleSettings.lockEffects.enableGrayscale - homeEnabled -> scheduleSettings.homeEffects.enableGrayscale - else -> scheduleSettings.lockEffects.enableGrayscale - }, - onCheckedChange = { enabled -> - onUpdateScheduleSettings( - scheduleSettings.copy( - homeEffects = if (homeEnabled) scheduleSettings.homeEffects.copy(enableGrayscale = enabled) else scheduleSettings.homeEffects, - lockEffects = if (lockEnabled) scheduleSettings.lockEffects.copy(enableGrayscale = enabled) else scheduleSettings.lockEffects + // Interactive Effects Group (Live Wallpaper Mode Only) + if (wallpaperMode == WallpaperMode.LIVE) { + Card( + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLow + ), + modifier = Modifier + .fillMaxWidth() + .padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)) + ) { + Column( + modifier = Modifier.padding(AppSpacing.large), + verticalArrangement = Arrangement.spacedBy(AppSpacing.small) + ) { + Text( + text = stringResource(R.string.interactive_effects), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.padding(bottom = AppSpacing.small), + maxLines = 1, + overflow = TextOverflow.Ellipsis ) - ) - } - ) - // Adaptive Brightness - SettingSwitch( - title = R.string.adaptive_brightness, - description = if (scheduleSettings.adaptiveBrightness && !scheduleSettings.separateSchedules) null else R.string.adjust_brightness_based_on_mode, - checked = scheduleSettings.adaptiveBrightness, - onCheckedChange = { enabled -> - onUpdateScheduleSettings(scheduleSettings.copy(adaptiveBrightness = enabled)) - } - ) + // Double-tap to change wallpaper + SettingSwitch( + title = R.string.double_tap_to_change, + description = if (scheduleSettings.liveEffects.enableDoubleTap) null else R.string.double_tap_wallpaper_to_change_it, + checked = scheduleSettings.liveEffects.enableDoubleTap, + onCheckedChange = { enabled -> + updateSettingsImmediate( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(enableDoubleTap = enabled) + ) + ) + } + ) - // Shuffle - SettingSwitch( - title = R.string.shuffle, - description = if (scheduleSettings.shuffleEnabled && !scheduleSettings.separateSchedules) null else R.string.randomly_shuffle_the_wallpapers, - checked = scheduleSettings.shuffleEnabled, - onCheckedChange = { enabled -> - onUpdateScheduleSettings(scheduleSettings.copy(shuffleEnabled = enabled)) + // Parallax effect + SettingSwitchWithSlider( + title = R.string.parallax_effect, + description = R.string.wallpaper_moves_with_screen_scroll, + checked = scheduleSettings.liveEffects.enableParallax, + onCheckedChange = { enabled -> + updateSettingsImmediate( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(enableParallax = enabled) + ) + ) + }, + bothEnabled = false, // Never separate in Live Mode + homePercentage = scheduleSettings.liveEffects.parallaxIntensity, + lockPercentage = 0, + onPercentageChange = { homePercent, _ -> + updateSettingsDebounced( + scheduleSettings.copy( + liveEffects = scheduleSettings.liveEffects.copy(parallaxIntensity = homePercent) + ) + ) + } + ) + } } - ) + } } if (showAlbumSelectionSheet) { AlbumSelectionBottomSheet( albums = albums, selectedAlbums = when (albumSelectionContext) { - AlbumSelectionContext.HOME -> homeAlbum?.let { listOf(it) } ?: emptyList() - AlbumSelectionContext.LOCK -> lockAlbum?.let { listOf(it) } ?: emptyList() + AlbumSelectionContext.LIVE -> { + // Use ID as source of truth - if ID is set, ensure we mark it as selected + scheduleSettings.liveAlbumId?.let { id -> + // Try to find full album, or create stub with ID for selection marking + albums.find { it.id == id }?.let { listOf(it) } + ?: listOf(Album(id = id, name = "", coverUri = null)) + } ?: emptyList() + } + AlbumSelectionContext.HOME -> { + // Use ID as source of truth - if ID is set, ensure we mark it as selected + scheduleSettings.homeAlbumId?.let { id -> + // Try to find full album, or create stub with ID for selection marking + albums.find { it.id == id }?.let { listOf(it) } + ?: listOf(Album(id = id, name = "", coverUri = null)) + } ?: emptyList() + } + AlbumSelectionContext.LOCK -> { + // Use ID as source of truth - if ID is set, ensure we mark it as selected + scheduleSettings.lockAlbumId?.let { id -> + // Try to find full album, or create stub with ID for selection marking + albums.find { it.id == id }?.let { listOf(it) } + ?: listOf(Album(id = id, name = "", coverUri = null)) + } ?: emptyList() + } AlbumSelectionContext.BOTH -> { // When only one screen enabled, show that screen's selected album when { - homeEnabled -> homeAlbum?.let { listOf(it) } ?: emptyList() - lockEnabled -> lockAlbum?.let { listOf(it) } ?: emptyList() + homeEnabled -> { + scheduleSettings.homeAlbumId?.let { id -> + albums.find { it.id == id }?.let { listOf(it) } + ?: listOf(Album(id = id, name = "", coverUri = null)) + } ?: emptyList() + } + lockEnabled -> { + scheduleSettings.lockAlbumId?.let { id -> + albums.find { it.id == id }?.let { listOf(it) } + ?: listOf(Album(id = id, name = "", coverUri = null)) + } ?: emptyList() + } else -> emptyList() } } @@ -707,26 +1015,37 @@ fun WallpaperScreen( showEmptyAlbumWarning = true } else { when (albumSelectionContext) { + AlbumSelectionContext.LIVE -> { + // Toggle selection using ID as source of truth + val isCurrentlySelected = scheduleSettings.liveAlbumId == album.id + if (isCurrentlySelected) { + onSelectLiveAlbum(null) + } else { + onSelectLiveAlbum(album) + } + } AlbumSelectionContext.HOME -> { - // Toggle selection: unselect if already selected - if (homeAlbum?.id == album.id) { + // Toggle selection using ID as source of truth + val isCurrentlySelected = scheduleSettings.homeAlbumId == album.id + if (isCurrentlySelected) { onSelectHomeAlbum(null) } else { onSelectHomeAlbum(album) } } AlbumSelectionContext.LOCK -> { - // Toggle selection: unselect if already selected - if (lockAlbum?.id == album.id) { + // Toggle selection using ID as source of truth + val isCurrentlySelected = scheduleSettings.lockAlbumId == album.id + if (isCurrentlySelected) { onSelectLockAlbum(null) } else { onSelectLockAlbum(album) } } AlbumSelectionContext.BOTH -> { - // Toggle selection for the enabled screen(s) - val isCurrentlySelected = (homeEnabled && homeAlbum?.id == album.id) || - (lockEnabled && lockAlbum?.id == album.id) + // Toggle selection for the enabled screen(s) using IDs as source of truth + val isCurrentlySelected = (homeEnabled && scheduleSettings.homeAlbumId == album.id) || + (lockEnabled && scheduleSettings.lockAlbumId == album.id) if (isCurrentlySelected) { if (homeEnabled) onSelectHomeAlbum(null) if (lockEnabled) onSelectLockAlbum(null) @@ -736,9 +1055,9 @@ fun WallpaperScreen( } } } - // Dismiss the bottom sheet after selection - showAlbumSelectionSheet = false } + // Dismiss the bottom sheet after selection + showAlbumSelectionSheet = false }, onDismiss = { showAlbumSelectionSheet = false } ) diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt new file mode 100644 index 0000000..86bb212 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionScreen.kt @@ -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(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 + ) + } + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt new file mode 100644 index 0000000..15e1e2a --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/presentation/screens/wallpaper_mode_selection/WallpaperModeSelectionViewModel.kt @@ -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) + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt new file mode 100644 index 0000000..6c277f3 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/PaperizeLiveWallpaperService.kt @@ -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) + } + } + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt new file mode 100644 index 0000000..00cff4a --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLPicture.kt @@ -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 + 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})" + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt new file mode 100644 index 0000000..32c3085 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLTextureHandle.kt @@ -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)" + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt new file mode 100644 index 0000000..5cc014e --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLUtil.kt @@ -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") + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt new file mode 100644 index 0000000..d646fb5 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/gl/GLWallpaperService.kt @@ -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() + 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(numConfig[0]) + if (!egl.eglChooseConfig(display, configSpec, configs, numConfig[0], numConfig)) { + throw RuntimeException("eglChooseConfig failed") + } + + return configs[0] ?: throw RuntimeException("No config chosen") + } + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt new file mode 100644 index 0000000..f554ef6 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLGeometry.kt @@ -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) + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt new file mode 100644 index 0000000..af5b054 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/GLShaders.kt @@ -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; + } + """ +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt new file mode 100644 index 0000000..c865a1e --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/ImageLoader.kt @@ -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? { + 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) + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt new file mode 100644 index 0000000..d926f38 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeRenderController.kt @@ -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() diff --git a/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt new file mode 100644 index 0000000..df1c618 --- /dev/null +++ b/app/src/main/java/com/anthonyla/paperize/service/livewallpaper/renderer/PaperizeWallpaperRenderer.kt @@ -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") + } +} diff --git a/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt b/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt index 3f97577..b9bf4fb 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/wallpaper/WallpaperChangeService.kt @@ -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) { diff --git a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt index a329268..38c2b15 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperChangeWorker.kt @@ -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) { diff --git a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt index 76dabd2..1f2dc6b 100644 --- a/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt +++ b/app/src/main/java/com/anthonyla/paperize/service/worker/WallpaperScheduler.kt @@ -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 } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 248386c..3fb033b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -87,8 +87,7 @@ Paperize is running Next wallpaper change: %1$s Theme - AMOLED Mode - Full dark mode + Wallpaper Changer Enable Wallpaper Changer Lock Vignette Effect @@ -105,6 +104,13 @@ Add blur to the image Darken the edges of the image Make the colors grayscale + Double-Tap to Change + Double-tap wallpaper to change it + Parallax Effect + Wallpaper moves with screen scroll + Paperize Live Wallpaper + Dynamic wallpapers with effects and interactive features + Note: Visual effects (blur, darken, vignette, grayscale) apply to all wallpapers in live mode. Adaptive Brightness Adjust brightness based on dark/light mode Randomly shuffle the wallpapers @@ -142,6 +148,8 @@ Home Album Scaling Wallpaper Effects + Visual Effects + Interactive Effects Current Wallpapers diff --git a/app/src/main/res/xml/wallpaper.xml b/app/src/main/res/xml/wallpaper.xml new file mode 100644 index 0000000..93b3e92 --- /dev/null +++ b/app/src/main/res/xml/wallpaper.xml @@ -0,0 +1,5 @@ + + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 10b54f6..05d841e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -5,6 +5,7 @@ hilt = "2.57.2" ksp = "2.2.20-2.0.3" material = "1.13.0" coil = "3.3.0" +media3 = "1.7.1" [libraries] accompanist-permissions = { module = "com.google.accompanist:accompanist-permissions", version = "0.37.3" } @@ -58,6 +59,8 @@ reorderable = { group = "sh.calvin.reorderable", name = "reorderable", version = androidx-glance-appwidget = { group = "androidx.glance", name = "glance-appwidget", version = "1.1.1" } androidx-glance-material3 = { group = "androidx.glance", name = "glance-material3", version = "1.1.1" } androidx-glance-material = { group = "androidx.glance", name = "glance-material", version = "1.1.1" } +androidx-media3-exoplayer = { group = "androidx.media3", name = "media3-exoplayer", version.ref = "media3" } +androidx-media3-ui = { group = "androidx.media3", name = "media3-ui", version.ref = "media3" } [plugins] androidApplication = { id = "com.android.application", version.ref = "androidGradlePlugin" }