Rewrite initial commit
This commit is contained in:
1 parent
3b2f739254
commit
9079306f8f
281 files changed
+11920
-22105
No files matched your search
@@ -2,98 +2,90 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
|
||||
<uses-permission android:name="android.permission.USE_EXACT_ALARM" />
|
||||
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- Permissions -->
|
||||
<uses-permission android:name="android.permission.SET_WALLPAPER" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" tools:node="remove"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
|
||||
<!-- Features -->
|
||||
<uses-feature
|
||||
android:name="android.software.wallpaper"
|
||||
android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".PaperizeApplication"
|
||||
android:allowBackup="false"
|
||||
android:name=".App"
|
||||
android:persistent="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
android:fullBackupContent="false"
|
||||
android:icon="@mipmap/app_icon"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/app_icon_round"
|
||||
android:supportsRtl="true"
|
||||
android:enableOnBackInvokedCallback="true"
|
||||
android:theme="@style/Theme.Paperize" tools:targetApi="tiramisu">
|
||||
<activity
|
||||
android:name=".feature.wallpaper.presentation.MainActivity"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:exported="true"
|
||||
android:theme="@style/Theme.Paperize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data android:resource="@xml/shortcuts" android:name="android.app.shortcuts" />
|
||||
</activity>
|
||||
<activity android:name=".feature.wallpaper.app_shortcut.BroadcastActivity"
|
||||
android:theme="@android:style/Theme.NoDisplay">
|
||||
</activity>
|
||||
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver" />
|
||||
<service android:name=".feature.wallpaper.wallpaper_service.HomeWallpaperService"
|
||||
android:foregroundServiceType="dataSync|specialUse" />
|
||||
<service android:name=".feature.wallpaper.wallpaper_service.LockWallpaperService"
|
||||
android:foregroundServiceType="dataSync|specialUse" />
|
||||
<service
|
||||
android:name=".feature.wallpaper.wallpaper_tile.ChangeWallpaperTileService"
|
||||
android:exported="true"
|
||||
android:label="@string/change_wallpaper"
|
||||
android:icon="@drawable/notification_icon"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter> <action android:name="android.service.quicksettings.action.QS_TILE" /> </intent-filter>
|
||||
</service>
|
||||
<receiver android:name=".feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.TIME_SET" />
|
||||
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
|
||||
<action android:name="com.anthonyla.paperize.SHORTCUT" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<receiver android:name="com.anthonyla.paperize.feature.wallpaper.glance_widget.PaperizeWidgetReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
android:resource="@xml/paperize_widget_info" />
|
||||
</receiver>
|
||||
android:theme="@style/Theme.Paperize">
|
||||
|
||||
<!-- Disable default WorkManager initialization (using custom Configuration.Provider) -->
|
||||
<provider
|
||||
android:name="androidx.startup.InitializationProvider"
|
||||
android:authorities="${applicationId}.androidx-startup"
|
||||
android:exported="false"
|
||||
tools:node="merge">
|
||||
<meta-data android:name="androidx.emoji2.text.EmojiCompatInitializer"
|
||||
<meta-data
|
||||
android:name="androidx.work.WorkManagerInitializer"
|
||||
android:value="androidx.startup"
|
||||
tools:node="remove" />
|
||||
</provider>
|
||||
|
||||
<!-- Main Activity -->
|
||||
<activity
|
||||
android:name=".feature.wallpaper.tasker_shortcut.ActivityConfigBasicAction"
|
||||
android:name=".presentation.MainActivity"
|
||||
android:exported="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="Change wallpaper">
|
||||
android:configChanges="uiMode|density|orientation|screenSize|screenLayout|keyboardHidden|keyboard"
|
||||
android:theme="@style/Theme.Paperize">
|
||||
<intent-filter>
|
||||
<action android:name="com.twofortyfouram.locale.intent.action.EDIT_SETTING" />
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".feature.wallpaper.tasker_shortcut.ActivityConfigBasicEvent"
|
||||
android:exported="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="Change wallpaper event">
|
||||
<intent-filter>
|
||||
<action android:name="net.dinglisch.android.tasker.ACTION_EDIT_EVENT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
<!-- Wallpaper Service -->
|
||||
<service
|
||||
android:name=".service.wallpaper.WallpaperChangeService"
|
||||
android:enabled="true"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Wallpaper changer" />
|
||||
</service>
|
||||
|
||||
<!-- Broadcast Receivers -->
|
||||
<receiver
|
||||
android:name=".service.alarm.BootReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- Quick Settings Tile -->
|
||||
<service
|
||||
android:name=".service.tile.WallpaperTileService"
|
||||
android:exported="true"
|
||||
android:icon="@drawable/ic_launcher_foreground"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.anthonyla.paperize
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.database.CursorWindow
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import java.lang.reflect.Field
|
||||
|
||||
|
||||
/**
|
||||
* Application class for Hilt
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class App: Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
// Increase CursorWindow size to handle large datasets
|
||||
// Default is usually 2MB, increasing to 10MB
|
||||
try {
|
||||
val field: Field = CursorWindow::class.java.getDeclaredField("sCursorWindowSize")
|
||||
field.isAccessible = true
|
||||
field.set(null, 10 * 1024 * 1024) // 10MB
|
||||
} catch (e: Exception) {
|
||||
// Fallback for newer Android versions where field might be different
|
||||
try {
|
||||
val field: Field = CursorWindow::class.java.getDeclaredField("CURSOR_WINDOW_SIZE")
|
||||
field.isAccessible = true
|
||||
field.set(null, 10 * 1024 * 1024) // 10MB
|
||||
} catch (e2: Exception) {
|
||||
e2.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
val channel = NotificationChannel("wallpaper_service_channel", "Paperize", NotificationManager.IMPORTANCE_LOW)
|
||||
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.anthonyla.paperize
|
||||
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import androidx.hilt.work.HiltWorkerFactory
|
||||
import androidx.work.Configuration
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.service.worker.AlbumRefreshWorker
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Application class for Paperize
|
||||
*
|
||||
* Annotated with @HiltAndroidApp to enable dependency injection
|
||||
* Implements Configuration.Provider for WorkManager with Hilt support
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class PaperizeApplication : Application(), Configuration.Provider {
|
||||
|
||||
@Inject
|
||||
lateinit var workerFactory: HiltWorkerFactory
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
|
||||
// Create notification channel (minSdk is 31, so always supported)
|
||||
createNotificationChannel()
|
||||
|
||||
// Trigger album refresh on app cold start to validate and update all albums
|
||||
refreshAlbumsOnStartup()
|
||||
}
|
||||
|
||||
override val workManagerConfiguration: Configuration
|
||||
get() = Configuration.Builder()
|
||||
.setWorkerFactory(workerFactory)
|
||||
.build()
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val channel = NotificationChannel(
|
||||
Constants.NOTIFICATION_CHANNEL_ID,
|
||||
getString(R.string.app_name),
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
).apply {
|
||||
description = getString(R.string.notification_channel_description)
|
||||
setShowBadge(false)
|
||||
}
|
||||
|
||||
val notificationManager = getSystemService(NotificationManager::class.java)
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh all albums on app startup to validate and update wallpapers/folders
|
||||
*
|
||||
* This runs in the background without blocking app startup and ensures:
|
||||
* - Invalid wallpapers/folders are removed
|
||||
* - New wallpapers are discovered in existing folders
|
||||
* - Album covers are up-to-date
|
||||
*/
|
||||
private fun refreshAlbumsOnStartup() {
|
||||
val workManager = WorkManager.getInstance(this)
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
|
||||
.build()
|
||||
|
||||
val refreshWorkRequest = OneTimeWorkRequestBuilder<AlbumRefreshWorker>()
|
||||
.setConstraints(constraints)
|
||||
.addTag("startup_refresh")
|
||||
.build()
|
||||
|
||||
// Use KEEP policy to avoid duplicate refreshes if app is quickly reopened
|
||||
workManager.enqueueUniqueWork(
|
||||
"album_refresh_on_startup",
|
||||
ExistingWorkPolicy.KEEP,
|
||||
refreshWorkRequest
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* A generic class that holds a value or an error
|
||||
*/
|
||||
sealed class Result<out T> {
|
||||
data class Success<T>(val data: T) : Result<T>()
|
||||
data class Error(val exception: Throwable, val message: String? = exception.message) : Result<Nothing>()
|
||||
data object Loading : Result<Nothing>()
|
||||
|
||||
val isSuccess: Boolean get() = this is Success
|
||||
val isError: Boolean get() = this is Error
|
||||
val isLoading: Boolean get() = this is Loading
|
||||
|
||||
fun getOrNull(): T? = if (this is Success) data else null
|
||||
fun exceptionOrNull(): Throwable? = if (this is Error) exception else null
|
||||
|
||||
inline fun onSuccess(action: (T) -> Unit): Result<T> {
|
||||
if (this is Success) action(data)
|
||||
return this
|
||||
}
|
||||
|
||||
inline fun onError(action: (Throwable) -> Unit): Result<T> {
|
||||
if (this is Error) action(exception)
|
||||
return this
|
||||
}
|
||||
|
||||
companion object {
|
||||
inline fun <T> runCatching(block: () -> T): Result<T> {
|
||||
return try {
|
||||
Success(block())
|
||||
} catch (e: Exception) {
|
||||
Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a Result to another type
|
||||
*/
|
||||
inline fun <T, R> Result<T>.map(transform: (T) -> R): Result<R> {
|
||||
return when (this) {
|
||||
is Result.Success -> Result.Success(transform(data))
|
||||
is Result.Error -> Result.Error(exception, message)
|
||||
is Result.Loading -> Result.Loading
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat map a Result
|
||||
*/
|
||||
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> {
|
||||
return when (this) {
|
||||
is Result.Success -> transform(data)
|
||||
is Result.Error -> Result.Error(exception, message)
|
||||
is Result.Loading -> Result.Loading
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
enum class ScalingConstants {
|
||||
FIT,
|
||||
FILL,
|
||||
STRETCH,
|
||||
NONE
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Wallpaper scaling options
|
||||
*/
|
||||
enum class ScalingType {
|
||||
/**
|
||||
* Fill the screen, cropping if necessary
|
||||
*/
|
||||
FILL,
|
||||
|
||||
/**
|
||||
* Fit the entire image, adding letterboxing/pillarboxing if necessary
|
||||
*/
|
||||
FIT,
|
||||
|
||||
/**
|
||||
* Stretch the image to fill the screen
|
||||
*/
|
||||
STRETCH,
|
||||
|
||||
/**
|
||||
* Display at original size
|
||||
*/
|
||||
NONE;
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String?): ScalingType {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) } ?: FILL
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Screen types for wallpaper setting
|
||||
*/
|
||||
enum class ScreenType {
|
||||
HOME,
|
||||
LOCK,
|
||||
BOTH;
|
||||
|
||||
companion object {
|
||||
fun fromString(value: String?): ScreenType {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) } ?: BOTH
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Constants for application settings
|
||||
*/
|
||||
object SettingsConstants {
|
||||
const val SETTINGS_DATASTORE = "settings_datastore"
|
||||
const val DARK_MODE_TYPE = "dark_mode_type"
|
||||
const val AMOLED_THEME_TYPE = "amoled_theme_type"
|
||||
const val DYNAMIC_THEME_TYPE = "dynamic_theme_type"
|
||||
const val ANIMATE_TYPE = "animate_type"
|
||||
const val ENABLE_CHANGER = "enable_changer"
|
||||
const val ENABLE_HOME_WALLPAPER = "home_wallpaper"
|
||||
const val ENABLE_LOCK_WALLPAPER = "lock_wallpaper"
|
||||
const val CURRENT_HOME_WALLPAPER = "current_home_wallpaper"
|
||||
const val CURRENT_LOCK_WALLPAPER = "current_lock_wallpaper"
|
||||
const val HOME_ALBUM_NAME = "home_album_name"
|
||||
const val LOCK_ALBUM_NAME = "lock_album_name"
|
||||
const val HOME_WALLPAPER_CHANGE_INTERVAL = "home_wallpaper_change_interval"
|
||||
const val LOCK_WALLPAPER_CHANGE_INTERVAL = "lock_wallpaper_change_interval"
|
||||
const val REFRESH = "refresh"
|
||||
const val WALLPAPER_CHANGE_INTERVAL_DEFAULT = 15
|
||||
const val WALLPAPER_CHANGE_INTERVAL_MIN = 1
|
||||
const val FIRST_LAUNCH = "first_launch"
|
||||
const val FIRST_SET = "first_set"
|
||||
const val LAST_SET_TIME = "last_set_time"
|
||||
const val NEXT_SET_TIME = "next_set_time"
|
||||
const val HOME_DARKEN_PERCENTAGE = "home_darken_percentage"
|
||||
const val LOCK_DARKEN_PERCENTAGE = "darken_darken_percentage"
|
||||
const val DARKEN = "darken"
|
||||
const val WALLPAPER_SCALING = "wallpaper_scaling"
|
||||
const val SCHEDULE_SEPARATELY = "schedule_separately"
|
||||
const val BLUR = "blur"
|
||||
const val HOME_BLUR_PERCENTAGE = "home_blur_percentage"
|
||||
const val LOCK_BLUR_PERCENTAGE = "lock_blur_percentage"
|
||||
const val VIGNETTE = "vignette"
|
||||
const val HOME_VIGNETTE_PERCENTAGE = "home_vignette_percentage"
|
||||
const val LOCK_VIGNETTE_PERCENTAGE = "lock_vignette_percentage"
|
||||
const val HOME_NEXT_SET_TIME = "next_set_time_1"
|
||||
const val LOCK_NEXT_SET_TIME = "next_set_time_2"
|
||||
const val NEXT_HOME_WALLPAPER = "next_home_wallpaper"
|
||||
const val NEXT_LOCK_WALLPAPER = "next_lock_wallpaper"
|
||||
const val GRAYSCALE = "grayscale"
|
||||
const val HOME_GRAYSCALE_PERCENTAGE = "home_grayscale_percentage"
|
||||
const val LOCK_GRAYSCALE_PERCENTAGE = "lock_grayscale_percentage"
|
||||
const val CHANGE_START_TIME = "change_start_time"
|
||||
const val START_HOUR = "start_hour"
|
||||
const val START_MINUTE = "start_minute"
|
||||
const val SHUFFLE = "shuffle"
|
||||
const val SKIP_LANDSCAPE = "skip_landscape"
|
||||
const val SKIP_NON_INTERACTIVE = "skip_non_interactive"
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
|
||||
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
|
||||
import com.bumptech.glide.util.Util
|
||||
import java.security.MessageDigest
|
||||
|
||||
/**
|
||||
* A BitmapTransformation that applies a vignette effect to a bitmap to be used with Glide
|
||||
*/
|
||||
class VignetteBitmapTransformation(private val percent: Int): BitmapTransformation() {
|
||||
|
||||
override fun transform(
|
||||
pool: BitmapPool,
|
||||
toTransform: Bitmap,
|
||||
outWidth: Int,
|
||||
outHeight: Int
|
||||
): Bitmap {
|
||||
return vignetteBitmap(toTransform, percent)
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
return other is VignetteBitmapTransformation && other.percent == percent
|
||||
}
|
||||
|
||||
override fun hashCode(): Int {
|
||||
return Util.hashCode(percent)
|
||||
}
|
||||
|
||||
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
|
||||
messageDigest.update((ID + percent).toByteArray(CHARSET))
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val ID = "com.bumptech.glide.transformations.VignettedBitmapTransformation"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Source type for wallpapers
|
||||
*/
|
||||
enum class WallpaperSourceType {
|
||||
/**
|
||||
* Directly selected wallpaper files
|
||||
*/
|
||||
DIRECT,
|
||||
|
||||
/**
|
||||
* Wallpapers from monitored folders
|
||||
*/
|
||||
FOLDER
|
||||
}
|
||||
@@ -1,752 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.content.res.Resources
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.ColorMatrix
|
||||
import android.graphics.ColorMatrixColorFilter
|
||||
import android.graphics.HardwareRenderer
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.Shader
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.provider.DocumentsContract
|
||||
import android.util.Base64
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.Log
|
||||
import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.core.net.toUri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScreenMetricsCompat.getScreenSize
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Metadata
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.lazygeniouz.dfc.file.DocumentFileCompat
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.nio.charset.Charset
|
||||
import java.util.zip.DeflaterOutputStream
|
||||
import java.util.zip.InflaterInputStream
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.RenderEffect
|
||||
import android.graphics.RenderNode
|
||||
import android.hardware.HardwareBuffer
|
||||
import android.media.ImageReader
|
||||
import kotlin.compareTo
|
||||
import kotlin.or
|
||||
|
||||
enum class Type { HOME, LOCK, SINGLE, REFRESH }
|
||||
|
||||
/**
|
||||
* Get the dimensions of the image from the uri
|
||||
*/
|
||||
fun Uri.getImageDimensions(context: Context): Size? {
|
||||
try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val exif = ExifInterface(inputStream)
|
||||
val width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
|
||||
val height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
|
||||
if (width > 0 && height > 0) {
|
||||
return Size(width, height)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error reading EXIF dimensions for $this, falling back: $e")
|
||||
}
|
||||
|
||||
try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
if (options.outWidth > 0 && options.outHeight > 0) {
|
||||
return Size(options.outWidth, options.outHeight)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error getting image dimensions with BitmapFactory for $this: $e")
|
||||
return null
|
||||
}
|
||||
Log.w("WallpaperUtil", "Could not get image dimensions for $this")
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Calculate the inSampleSize for the image
|
||||
*/
|
||||
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
|
||||
if (imageSize.width == 0 || imageSize.height == 0) return 1
|
||||
if (width == 0 || height == 0) return 1
|
||||
|
||||
if (imageSize.width > width || imageSize.height > height) {
|
||||
val heightRatio = (imageSize.height.toFloat() / height.toFloat()).fastRoundToInt()
|
||||
val widthRatio = (imageSize.width.toFloat() / width.toFloat()).fastRoundToInt()
|
||||
return (if (heightRatio < widthRatio) heightRatio else widthRatio).coerceAtLeast(1)
|
||||
}
|
||||
else { return 1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the screen size of the device without orientation
|
||||
* https://stackoverflow.com/a/70087378
|
||||
*/
|
||||
object ScreenMetricsCompat {
|
||||
private val api: Api = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) ApiLevel30() else Api()
|
||||
fun getScreenSize(context: Context): Size = api.getScreenSize(context)
|
||||
@Suppress("DEPRECATION")
|
||||
private open class Api {
|
||||
open fun getScreenSize(context: Context): Size {
|
||||
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val display = windowManager.defaultDisplay
|
||||
val metrics = if (display != null) {
|
||||
DisplayMetrics().also { display.getRealMetrics(it) }
|
||||
} else {
|
||||
Resources.getSystem().displayMetrics
|
||||
}
|
||||
return Size(metrics.widthPixels, metrics.heightPixels)
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresApi(Build.VERSION_CODES.R)
|
||||
private class ApiLevel30 : Api() {
|
||||
override fun getScreenSize(context: Context): Size {
|
||||
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val metrics: WindowMetrics = windowManager.currentWindowMetrics
|
||||
return Size(metrics.bounds.width(), metrics.bounds.height())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get device screen size with orientation
|
||||
*/
|
||||
fun getDeviceScreenSize(context: Context): Size {
|
||||
val orientation = context.resources.configuration.orientation
|
||||
val size = getScreenSize(context)
|
||||
return if (orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Size(minOf(size.width, size.height), maxOf(size.width, size.height))
|
||||
} else {
|
||||
Size(maxOf(size.width, size.height), minOf(size.width, size.height))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a bitmap from a URI that is scaled down to the device's screen size
|
||||
*/
|
||||
fun retrieveBitmap(
|
||||
context: Context,
|
||||
wallpaper: Uri,
|
||||
width: Int,
|
||||
height: Int,
|
||||
scaling: ScalingConstants = ScalingConstants.FIT
|
||||
): Bitmap? {
|
||||
val imageSize = wallpaper.getImageDimensions(context) ?: return null
|
||||
if (imageSize.width <= 0 || imageSize.height <= 0) {
|
||||
Log.e("WallpaperUtil", "Invalid image dimensions from URI: $imageSize")
|
||||
return null
|
||||
}
|
||||
|
||||
val sampleSize = if (scaling == ScalingConstants.NONE) {
|
||||
1
|
||||
} else {
|
||||
calculateInSampleSize(imageSize, width, height)
|
||||
}
|
||||
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, wallpaper)
|
||||
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
decoder.setTargetSampleSize(sampleSize)
|
||||
decoder.isMutableRequired = true
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "ImageDecoder failed, falling back to BitmapFactory: $e")
|
||||
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
context.contentResolver.openInputStream(wallpaper)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val SharedPaintFilterAntiAlias = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fit width method
|
||||
* The bitmap will fit into the given width while maintaining the same aspect ratio
|
||||
*/
|
||||
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
|
||||
Log.w("WallpaperUtil", "Invalid dimensions for fitBitmap, returning source.")
|
||||
return source
|
||||
}
|
||||
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val scale = width.toFloat() / source.width
|
||||
val scaledSourceHeight = source.height * scale
|
||||
val yOffset = (height - scaledSourceHeight) / 2f
|
||||
val matrix = Matrix().apply {
|
||||
postScale(scale, scale)
|
||||
postTranslate(0f, yOffset)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error fitting bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fill method
|
||||
*/
|
||||
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val sourceAspect = source.width.toFloat() / source.height.toFloat()
|
||||
val targetAspect = width.toFloat() / height.toFloat()
|
||||
|
||||
val scale: Float
|
||||
val xOffset: Float
|
||||
val yOffset: Float
|
||||
|
||||
if (sourceAspect >= targetAspect) {
|
||||
scale = height.toFloat() / source.height.toFloat()
|
||||
xOffset = (width - source.width * scale) / 2f
|
||||
yOffset = 0f
|
||||
} else {
|
||||
scale = width.toFloat() / source.width.toFloat()
|
||||
xOffset = 0f
|
||||
yOffset = (height - source.height * scale) / 2f
|
||||
}
|
||||
|
||||
val matrix = Matrix().apply {
|
||||
postScale(scale, scale)
|
||||
postTranslate(xOffset, yOffset)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error filling bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stretch the bitmap to fit the given width and height
|
||||
*/
|
||||
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val matrix = Matrix().apply {
|
||||
setScale(
|
||||
width.toFloat() / source.width,
|
||||
height.toFloat() / source.height
|
||||
)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error stretching bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Darken the bitmap by a certain percentage - 0 is darkest, 100 is original
|
||||
*/
|
||||
fun darkenBitmap(source: Bitmap, brightnessToRetainPercent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w("WallpaperUtil", "darkenBitmap received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return darkenBitmap(mutableCopy, brightnessToRetainPercent)
|
||||
}
|
||||
|
||||
val targetBrightnessFactor = brightnessToRetainPercent.coerceIn(0, 100) / 100f
|
||||
if (targetBrightnessFactor >= 1.0f) {
|
||||
return source
|
||||
}
|
||||
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(targetBrightnessFactor, targetBrightnessFactor, targetBrightnessFactor, 1f)
|
||||
})
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
}
|
||||
|
||||
/**
|
||||
* Blur the bitmap by a certain percentage
|
||||
*/
|
||||
fun blurBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
val clampedPercent = percent.coerceIn(0, 100)
|
||||
if (clampedPercent == 0) {
|
||||
return source
|
||||
}
|
||||
|
||||
val maxBlurRadius = 25.0f
|
||||
val radius = (clampedPercent / 100.0f) * maxBlurRadius
|
||||
|
||||
val imageReader = ImageReader.newInstance(
|
||||
source.width, source.height,
|
||||
PixelFormat.RGBA_8888, 1,
|
||||
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
|
||||
)
|
||||
|
||||
val renderNode = RenderNode("BlurEffect")
|
||||
val hardwareRenderer = HardwareRenderer()
|
||||
|
||||
var resultBitmap: Bitmap?
|
||||
try {
|
||||
hardwareRenderer.setSurface(imageReader.surface)
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
renderNode.setPosition(0, 0, source.width, source.height)
|
||||
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.MIRROR)
|
||||
renderNode.setRenderEffect(blurEffect)
|
||||
|
||||
val canvas = renderNode.beginRecording()
|
||||
canvas.drawBitmap(source, 0f, 0f, null)
|
||||
renderNode.endRecording()
|
||||
|
||||
hardwareRenderer.createRenderRequest()
|
||||
.setWaitForPresent(true)
|
||||
.syncAndDraw()
|
||||
|
||||
val image = imageReader.acquireNextImage()
|
||||
?: throw IllegalStateException("Failed to acquire blurred image")
|
||||
|
||||
val hardwareBuffer = image.hardwareBuffer
|
||||
?: throw IllegalStateException("Failed to acquire hardware buffer")
|
||||
|
||||
val hardwareBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
|
||||
?: throw IllegalStateException("Failed to create bitmap from hardware buffer")
|
||||
|
||||
// Convert hardware bitmap to regular bitmap for further processing
|
||||
resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, false)
|
||||
|
||||
hardwareBuffer.close()
|
||||
image.close()
|
||||
|
||||
} finally {
|
||||
hardwareRenderer.destroy()
|
||||
renderNode.discardDisplayList()
|
||||
imageReader.close()
|
||||
}
|
||||
|
||||
return resultBitmap
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a vignette effect to the bitmap
|
||||
*/
|
||||
fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (percent <= 0) return source
|
||||
if (!source.isMutable) {
|
||||
Log.w("WallpaperUtil", "vignetteBitmap received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return vignetteBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
try {
|
||||
val canvas = Canvas(source)
|
||||
val dim = if (source.width < source.height) source.height else source.width
|
||||
val rad = (dim * (1 - (percent.coerceIn(0, 100) / 150f))).coerceAtLeast(0.1f)
|
||||
val centerX = source.width / 2f
|
||||
val centerY = source.height / 2f
|
||||
|
||||
val colors = intArrayOf(
|
||||
Color.TRANSPARENT,
|
||||
Color.argb((0.1f * 255).toInt(), 0, 0, 0),
|
||||
Color.argb((0.8f * 255).toInt(), 0, 0, 0)
|
||||
)
|
||||
val pos = floatArrayOf(0f, 0.7f, 1f)
|
||||
|
||||
|
||||
val vignettePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
shader = RadialGradient(
|
||||
centerX, centerY, rad,
|
||||
colors, pos, Shader.TileMode.CLAMP
|
||||
)
|
||||
}
|
||||
canvas.drawRect(0f, 0f, source.width.toFloat(), source.height.toFloat(), vignettePaint)
|
||||
return source
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error applying vignette: $e")
|
||||
return source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a grey filter to the bitmap based on a percentage
|
||||
*/
|
||||
fun grayBitmap(bitmap: Bitmap, percent: Int): Bitmap {
|
||||
if (percent <= 0) return bitmap
|
||||
if (!bitmap.isMutable) {
|
||||
Log.w("WallpaperUtil", "grayBitmap received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = bitmap.copy(bitmap.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return grayBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
val factor = percent.coerceIn(0, 100) / 100f
|
||||
if (factor <= 0f) return bitmap
|
||||
|
||||
val colorMatrix = ColorMatrix().apply { setSaturation(1 - factor) }
|
||||
val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(colorMatrix) }
|
||||
|
||||
Canvas(bitmap).drawBitmap(bitmap, 0f, 0f, paint)
|
||||
return bitmap
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all wallpapers from a folder URI
|
||||
*/
|
||||
suspend fun getWallpaperFromFolder(folderUri: String, context: Context): List<Wallpaper> = withContext(Dispatchers.IO) {
|
||||
val allowedExtensions = setOf("jpg", "jpeg", "png", "heif", "heic", "webp")
|
||||
val contentResolver = context.contentResolver
|
||||
val wallpapers = mutableListOf<Wallpaper>()
|
||||
|
||||
if (folderUri.isEmpty()) {
|
||||
return@withContext emptyList<Wallpaper>()
|
||||
}
|
||||
val rootUri = folderUri.toUri()
|
||||
val foldersToVisit = ArrayDeque<Uri>()
|
||||
foldersToVisit.add(rootUri)
|
||||
|
||||
val projection = arrayOf(
|
||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED,
|
||||
)
|
||||
|
||||
try {
|
||||
while (foldersToVisit.isNotEmpty()) {
|
||||
val currentFolderDocumentUri = foldersToVisit.removeFirst()
|
||||
val currentFolderTreeDocId = DocumentsContract.getTreeDocumentId(currentFolderDocumentUri)
|
||||
?: DocumentsContract.getDocumentId(currentFolderDocumentUri)
|
||||
|
||||
if (currentFolderTreeDocId == null) {
|
||||
Log.w("WallpaperUtil", "Could not get tree document ID for $currentFolderDocumentUri")
|
||||
continue
|
||||
}
|
||||
|
||||
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
|
||||
rootUri,
|
||||
currentFolderTreeDocId
|
||||
)
|
||||
|
||||
contentResolver.query(childrenUri, projection, null, null, null)?.use { cursor ->
|
||||
val idIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
|
||||
val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
||||
val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
|
||||
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val documentId = cursor.getString(idIndex)
|
||||
val displayName = cursor.getString(nameIndex)
|
||||
val mimeType = cursor.getString(mimeTypeIndex)
|
||||
val dateModified = cursor.getLong(lastModifiedIndex)
|
||||
|
||||
val documentUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, documentId)
|
||||
|
||||
if (DocumentsContract.Document.MIME_TYPE_DIR == mimeType) {
|
||||
val dirTreeUri = DocumentsContract.buildTreeDocumentUri(rootUri.authority, documentId)
|
||||
foldersToVisit.add(dirTreeUri)
|
||||
} else {
|
||||
val extension = displayName.substringAfterLast('.', "").lowercase()
|
||||
if (extension in allowedExtensions) {
|
||||
wallpapers.add(
|
||||
Wallpaper(
|
||||
initialAlbumName = "",
|
||||
wallpaperUri = documentUri.toString().compress("content://com.android.externalstorage.documents/"),
|
||||
fileName = displayName.substringBeforeLast('.', displayName),
|
||||
dateModified = dateModified,
|
||||
order = wallpapers.size,
|
||||
key = 0
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error getting wallpapers from folder '$folderUri': ", e)
|
||||
return@withContext emptyList<Wallpaper>()
|
||||
}
|
||||
return@withContext wallpapers
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the folder name from the folder URI
|
||||
*/
|
||||
suspend fun getFolderMetadata(folderUri: String, context: Context): Metadata = withContext(Dispatchers.IO) {
|
||||
if (folderUri.isEmpty()) return@withContext Metadata("", 0)
|
||||
return@withContext try {
|
||||
val uri = folderUri.toUri()
|
||||
val file = DocumentFileCompat.fromTreeUri(context, uri)
|
||||
val name = file?.name?.substringBeforeLast('.', file.name) ?: ""
|
||||
val lastModified = file?.lastModified ?: 0
|
||||
Metadata(name, lastModified)
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error getting folder metadata with DocumentFileCompat for '$folderUri': $e, trying DocumentFile")
|
||||
try {
|
||||
val uri = folderUri.toUri()
|
||||
val file = DocumentFile.fromTreeUri(context, uri)
|
||||
val name = file?.name?.substringBeforeLast('.', file.name.orEmpty()) ?: ""
|
||||
val lastModified = file?.lastModified() ?: 0
|
||||
Metadata(name, lastModified)
|
||||
} catch (e2: Exception) {
|
||||
Log.e("WallpaperUtil", "Error getting folder metadata with DocumentFile for '$folderUri': $e2")
|
||||
Metadata("", 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get filename and last modified date from an image URI
|
||||
* @param context Android context
|
||||
* @param uriString URI string of the image
|
||||
*/
|
||||
suspend fun getImageMetadata(context: Context, uriString: String): Metadata = withContext(Dispatchers.IO) {
|
||||
if (uriString.isEmpty()) return@withContext Metadata("", 0)
|
||||
return@withContext try {
|
||||
val uri = uriString.toUri()
|
||||
val file = DocumentFileCompat.fromSingleUri(context, uri)
|
||||
val name = file?.name?.substringBeforeLast('.', file.name) ?: ""
|
||||
val lastModified = file?.lastModified ?: 0
|
||||
Metadata(name, lastModified)
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error getting image metadata with DocumentFileCompat for '$uriString': $e, trying DocumentFile")
|
||||
try {
|
||||
val uri = uriString.toUri()
|
||||
val file = DocumentFile.fromSingleUri(context, uri)
|
||||
val name = file?.name?.substringBeforeLast('.', file.name.orEmpty()) ?: ""
|
||||
val lastModified = file?.lastModified() ?: 0
|
||||
Metadata(name, lastModified)
|
||||
} catch (e2: Exception) {
|
||||
Log.e("WallpaperUtil", "Error getting image metadata with DocumentFile for '$uriString': $e2")
|
||||
Metadata("", 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to find the first valid URI from a list of wallpapers and folders
|
||||
*/
|
||||
suspend fun findFirstValidUri(
|
||||
context: Context,
|
||||
folders: List<Folder>,
|
||||
wallpapers: List<Wallpaper>
|
||||
): String? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
for (folder in folders) {
|
||||
for (wallpaper in folder.wallpapers) {
|
||||
try {
|
||||
if (isValidUri(context, wallpaper.wallpaperUri)) {
|
||||
return@withContext wallpaper.wallpaperUri
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error checking URI validity for folder wallpaper: ${wallpaper.wallpaperUri}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (wallpaper in wallpapers) {
|
||||
try {
|
||||
if (isValidUri(context, wallpaper.wallpaperUri)) {
|
||||
return@withContext wallpaper.wallpaperUri
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error checking URI validity for standalone wallpaper: ${wallpaper.wallpaperUri}", e)
|
||||
}
|
||||
}
|
||||
return@withContext null
|
||||
} catch (e: Exception) {
|
||||
Log.e("WallpaperUtil", "Error finding valid URI", e)
|
||||
return@withContext null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URI is valid
|
||||
*/
|
||||
fun isValidUri(context: Context, uriString: String?): Boolean {
|
||||
if (uriString.isNullOrEmpty()) return false
|
||||
val decompressedUriString = try {
|
||||
uriString.decompress("content://com.android.externalstorage.documents/")
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Failed to decompress URI string: $uriString", e)
|
||||
uriString
|
||||
}
|
||||
val uri = decompressedUriString.toUri()
|
||||
|
||||
return try {
|
||||
DocumentFileCompat.fromSingleUri(context, uri)?.exists() == true
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error checking URI validity with DocumentFileCompat for '$uri': $e, trying DocumentFile")
|
||||
try {
|
||||
DocumentFile.fromSingleUri(context, uri)?.exists() == true
|
||||
} catch (e2: Exception) {
|
||||
Log.w("WallpaperUtil", "Error checking URI validity with DocumentFile for '$uri': $e2")
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URI is a directory
|
||||
*/
|
||||
fun isDirectory(context: Context, uriString: String?): Boolean {
|
||||
if (uriString.isNullOrEmpty()) return false
|
||||
val uri = uriString.toUri()
|
||||
return try {
|
||||
DocumentFile.fromSingleUri(context, uri)?.isDirectory == true
|
||||
} catch (e: Exception) {
|
||||
Log.w("WallpaperUtil", "Error checking if URI is a directory for '$uri': $e")
|
||||
try {
|
||||
DocumentFile.fromTreeUri(context, uri)?.isDirectory == true
|
||||
} catch (e2: Exception) {
|
||||
Log.w("WallpaperUtil", "Error checking tree URI directory status for '$uri': $e2")
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compress a string
|
||||
*/
|
||||
fun String.compress(prefixToRemove: String, charset: Charset = Charsets.UTF_8): String {
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompress a string
|
||||
*/
|
||||
fun String.decompress(prefixToAdd: String, charset: Charset = Charsets.UTF_8): String {
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Darkens the bitmap by the given percentage and returns it
|
||||
* 0 - lightest, 100 - darkest
|
||||
*/
|
||||
fun processBitmap(
|
||||
width: Int,
|
||||
height: Int,
|
||||
source: Bitmap,
|
||||
darken: Boolean,
|
||||
darkenPercent: Int,
|
||||
scaling: ScalingConstants,
|
||||
blur: Boolean,
|
||||
blurPercent: Int,
|
||||
vignette: Boolean,
|
||||
vignettePercent: Int,
|
||||
grayscale: Boolean,
|
||||
grayscalePercent: Int
|
||||
): Bitmap? {
|
||||
try {
|
||||
var processedBitmap = source
|
||||
|
||||
// Apply blur first on the original size for better quality
|
||||
if (blur && blurPercent > 0) {
|
||||
processedBitmap = blurBitmap(processedBitmap, blurPercent)
|
||||
}
|
||||
|
||||
// Then scale the bitmap
|
||||
processedBitmap = when (scaling) {
|
||||
ScalingConstants.FILL -> fillBitmap(processedBitmap, width, height)
|
||||
ScalingConstants.FIT -> fitBitmap(processedBitmap, width, height)
|
||||
ScalingConstants.STRETCH -> stretchBitmap(processedBitmap, width, height)
|
||||
ScalingConstants.NONE -> processedBitmap
|
||||
}
|
||||
|
||||
// Ensure mutability for color effects
|
||||
if (!processedBitmap.isMutable && (darken || vignette || grayscale)) {
|
||||
Log.w("ProcessBitmap", "Bitmap became immutable. Making a mutable copy.")
|
||||
processedBitmap = processedBitmap.copy(processedBitmap.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
}
|
||||
|
||||
if (darken && darkenPercent > 0) {
|
||||
processedBitmap = darkenBitmap(processedBitmap, darkenPercent)
|
||||
}
|
||||
|
||||
if (vignette && vignettePercent > 0) {
|
||||
processedBitmap = vignetteBitmap(processedBitmap, vignettePercent)
|
||||
}
|
||||
|
||||
if (grayscale && grayscalePercent > 0) {
|
||||
processedBitmap = grayBitmap(processedBitmap, grayscalePercent)
|
||||
}
|
||||
|
||||
return processedBitmap
|
||||
}
|
||||
catch (e: OutOfMemoryError) {
|
||||
Log.e("PaperizeWallpaperChanger", "Error: Ran out of memory during bitmap processing. Attempting with smaller dimensions.", e)
|
||||
if (width / 2 > 0 && height / 2 > 0) {
|
||||
return processBitmap(
|
||||
width / 2,
|
||||
height / 2,
|
||||
source,
|
||||
darken,
|
||||
darkenPercent,
|
||||
scaling,
|
||||
blur,
|
||||
blurPercent,
|
||||
vignette,
|
||||
vignettePercent,
|
||||
grayscale,
|
||||
grayscalePercent
|
||||
)
|
||||
} else {
|
||||
Log.e("PaperizeWallpaperChanger", "Cannot reduce dimensions further for OOM recovery.")
|
||||
return null
|
||||
}
|
||||
}
|
||||
catch (e: Exception) {
|
||||
Log.e("PaperizeWallpaperChanger", "Error processing bitmap", e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package com.anthonyla.paperize.core.constants
|
||||
|
||||
/**
|
||||
* Application-wide constants
|
||||
*/
|
||||
object Constants {
|
||||
// Database
|
||||
const val DATABASE_NAME = "paperize_database"
|
||||
const val DATABASE_VERSION = 1
|
||||
|
||||
// DataStore
|
||||
const val PREFERENCES_NAME = "paperize_preferences"
|
||||
|
||||
// Notifications
|
||||
const val NOTIFICATION_CHANNEL_ID = "paperize_channel"
|
||||
const val NOTIFICATION_ID = 1
|
||||
|
||||
// Services
|
||||
const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER"
|
||||
|
||||
// WorkManager
|
||||
const val WORK_NAME_HOME = "wallpaper_change_home"
|
||||
const val WORK_NAME_LOCK = "wallpaper_change_lock"
|
||||
const val WORK_NAME_BOTH = "wallpaper_change_both"
|
||||
const val WORK_NAME_REFRESH = "album_refresh"
|
||||
const val WORK_TAG_HOME = "wallpaper_change_home_tag"
|
||||
const val WORK_TAG_LOCK = "wallpaper_change_lock_tag"
|
||||
const val WORK_TAG_BOTH = "wallpaper_change_both_tag"
|
||||
const val WORK_TAG_REFRESH = "album_refresh_tag"
|
||||
const val WORK_TAG_IMMEDIATE = "immediate_change"
|
||||
const val MAX_WORK_RETRY_ATTEMPTS = 3
|
||||
|
||||
// Intents
|
||||
const val EXTRA_SCREEN_TYPE = "screen_type"
|
||||
|
||||
// Wallpaper
|
||||
const val DEFAULT_BLUR_PERCENTAGE = 0
|
||||
const val DEFAULT_DARKEN_PERCENTAGE = 0
|
||||
const val DEFAULT_VIGNETTE_PERCENTAGE = 0
|
||||
const val MAX_EFFECT_PERCENTAGE = 100
|
||||
const val MIN_EFFECT_PERCENTAGE = 0
|
||||
|
||||
// Scheduling
|
||||
const val MIN_INTERVAL_MINUTES = 15
|
||||
const val MAX_INTERVAL_MINUTES = 43200 // 30 days in minutes
|
||||
const val DEFAULT_INTERVAL_MINUTES = 60
|
||||
|
||||
// UI
|
||||
const val ANIMATION_DURATION_LONG_MS = 800 // For item reordering animations
|
||||
const val DEBOUNCE_DELAY_MS = 500L
|
||||
const val PERMISSION_SCREEN_TRANSITION_DELAY_MS = 300L // Brief delay for permission screen transitions
|
||||
const val SETTINGS_DEBOUNCE_MS = 2000L // Debounce for settings changes before persisting
|
||||
const val WALLPAPER_CHANGE_DEBOUNCE_MS = 2000L
|
||||
const val WALLPAPER_ASPECT_RATIO = 9f / 16f // Standard phone aspect ratio
|
||||
|
||||
// Time conversion
|
||||
const val MINUTES_PER_HOUR = 60
|
||||
const val MINUTES_PER_DAY = 1440
|
||||
|
||||
// Image processing
|
||||
const val MAX_BLUR_RADIUS = 25.0f
|
||||
const val RGB_MAX_VALUE = 255.0
|
||||
const val BRIGHTNESS_SAMPLE_SIZE = 10 // Pixel sample size for brightness calculation
|
||||
const val DEFAULT_BRIGHTNESS = 0.5f // Default brightness fallback
|
||||
|
||||
// Luminance coefficients (ITU-R BT.709 standard)
|
||||
const val LUMINANCE_RED = 0.2126
|
||||
const val LUMINANCE_GREEN = 0.7152
|
||||
const val LUMINANCE_BLUE = 0.0722
|
||||
|
||||
// Adaptive brightness thresholds (based on WallYou implementation)
|
||||
const val LIGHT_BRIGHTNESS_MIN = 0.8f // Threshold for bright images in dark mode
|
||||
const val DARK_BRIGHTNESS_MAX = 0.3f // Threshold for dark images in light mode
|
||||
const val TARGET_BRIGHTNESS_DARK = 0.7f // Target brightness in dark mode
|
||||
const val TARGET_BRIGHTNESS_LIGHT = 0.4f // Target brightness in light mode
|
||||
|
||||
// Vignette effect
|
||||
const val VIGNETTE_DIVISOR = 150f // Radius calculation divisor
|
||||
const val VIGNETTE_MIN_RADIUS = 0.1f // Minimum vignette radius
|
||||
const val VIGNETTE_INNER_ALPHA = 0.1f // Inner alpha for vignette gradient
|
||||
const val VIGNETTE_OUTER_ALPHA = 0.8f // Outer alpha for vignette gradient
|
||||
val VIGNETTE_GRADIENT_POSITIONS = floatArrayOf(0f, 0.7f, 1f) // Vignette gradient positions
|
||||
|
||||
// Wallpaper loading retry
|
||||
const val WALLPAPER_READ_MAX_ATTEMPTS = 4 // Maximum retry attempts for wallpaper loading
|
||||
const val WALLPAPER_READ_INITIAL_DELAY_MS = 500L // Initial retry delay (with linear backoff)
|
||||
|
||||
// Render nodes
|
||||
const val RENDER_NODE_BLUR = "BlurEffect" // Identifier for blur render node
|
||||
|
||||
// Input validation
|
||||
const val MAX_DAYS_INPUT_LENGTH = 3
|
||||
const val MAX_HOURS_MINUTES_INPUT_LENGTH = 2
|
||||
|
||||
// File types
|
||||
val SUPPORTED_IMAGE_EXTENSIONS = setOf("jpg", "jpeg", "png", "webp", "avif")
|
||||
}
|
||||
|
||||
/**
|
||||
* Preference keys for DataStore
|
||||
*/
|
||||
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"
|
||||
|
||||
// Scheduling
|
||||
const val ENABLE_CHANGER = "enable_changer"
|
||||
const val SEPARATE_SCHEDULES = "separate_schedules"
|
||||
const val SHUFFLE_ENABLED = "shuffle_enabled"
|
||||
const val HOME_ENABLED = "home_enabled"
|
||||
const val LOCK_ENABLED = "lock_enabled"
|
||||
const val HOME_ALBUM_ID = "home_album_id"
|
||||
const val LOCK_ALBUM_ID = "lock_album_id"
|
||||
const val HOME_INTERVAL_MINUTES = "home_interval_minutes"
|
||||
const val LOCK_INTERVAL_MINUTES = "lock_interval_minutes"
|
||||
|
||||
// Effects - Home
|
||||
const val HOME_ENABLE_BLUR = "home_enable_blur"
|
||||
const val HOME_BLUR = "home_blur"
|
||||
const val HOME_ENABLE_DARKEN = "home_enable_darken"
|
||||
const val HOME_DARKEN = "home_darken"
|
||||
const val HOME_ENABLE_VIGNETTE = "home_enable_vignette"
|
||||
const val HOME_VIGNETTE = "home_vignette"
|
||||
const val HOME_GRAYSCALE = "home_grayscale"
|
||||
|
||||
// Effects - Lock
|
||||
const val LOCK_ENABLE_BLUR = "lock_enable_blur"
|
||||
const val LOCK_BLUR = "lock_blur"
|
||||
const val LOCK_ENABLE_DARKEN = "lock_enable_darken"
|
||||
const val LOCK_DARKEN = "lock_darken"
|
||||
const val LOCK_ENABLE_VIGNETTE = "lock_enable_vignette"
|
||||
const val LOCK_VIGNETTE = "lock_vignette"
|
||||
const val LOCK_GRAYSCALE = "lock_grayscale"
|
||||
|
||||
// Scaling
|
||||
const val HOME_SCALING_TYPE = "home_scaling_type"
|
||||
const val LOCK_SCALING_TYPE = "lock_scaling_type"
|
||||
|
||||
// Current wallpapers
|
||||
const val CURRENT_HOME_WALLPAPER_ID = "current_home_wallpaper_id"
|
||||
const val CURRENT_LOCK_WALLPAPER_ID = "current_lock_wallpaper_id"
|
||||
|
||||
// Behavior
|
||||
const val ADAPTIVE_BRIGHTNESS = "adaptive_brightness"
|
||||
|
||||
// First launch
|
||||
const val FIRST_LAUNCH = "first_launch"
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.anthonyla.paperize.core.di
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.datastore.PreferencesManager
|
||||
import com.anthonyla.paperize.data.repository.AlbumRepositoryImpl
|
||||
import com.anthonyla.paperize.data.repository.SettingsRepositoryImpl
|
||||
import com.anthonyla.paperize.data.repository.WallpaperRepositoryImpl
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Hilt dependency injection module
|
||||
*
|
||||
* Provides all application-wide dependencies
|
||||
*/
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object AppModule {
|
||||
|
||||
/**
|
||||
* Provide Room database
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun providePaperizeDatabase(app: Application): PaperizeDatabase {
|
||||
return Room.databaseBuilder(
|
||||
app,
|
||||
PaperizeDatabase::class.java,
|
||||
Constants.DATABASE_NAME
|
||||
)
|
||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide DAOs
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumDao(database: PaperizeDatabase): AlbumDao =
|
||||
database.albumDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperDao(database: PaperizeDatabase): WallpaperDao =
|
||||
database.wallpaperDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideFolderDao(database: PaperizeDatabase): FolderDao =
|
||||
database.folderDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperQueueDao(database: PaperizeDatabase): WallpaperQueueDao =
|
||||
database.wallpaperQueueDao()
|
||||
|
||||
/**
|
||||
* Provide PreferencesManager
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun providePreferencesManager(@ApplicationContext context: Context): PreferencesManager =
|
||||
PreferencesManager(context)
|
||||
|
||||
/**
|
||||
* Provide Repositories
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumRepository(
|
||||
@ApplicationContext context: Context,
|
||||
database: PaperizeDatabase,
|
||||
albumDao: AlbumDao,
|
||||
wallpaperDao: WallpaperDao,
|
||||
folderDao: FolderDao
|
||||
): AlbumRepository = AlbumRepositoryImpl(context, database, albumDao, wallpaperDao, folderDao)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperRepository(
|
||||
@ApplicationContext context: Context,
|
||||
wallpaperDao: WallpaperDao,
|
||||
wallpaperQueueDao: WallpaperQueueDao
|
||||
): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSettingsRepository(
|
||||
preferencesManager: PreferencesManager
|
||||
): SettingsRepository = SettingsRepositoryImpl(preferencesManager)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* URI extensions
|
||||
*/
|
||||
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
|
||||
return try {
|
||||
contentResolver.openInputStream(this)?.use { true } ?: false
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun Uri.getFileName(context: Context): String? {
|
||||
return DocumentFile.fromSingleUri(context, this)?.name
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a folder URI and return all image file URIs
|
||||
*/
|
||||
fun Uri.scanFolderForImages(context: Context): List<Uri> {
|
||||
val documentFile = DocumentFile.fromTreeUri(context, this) ?: return emptyList()
|
||||
if (!documentFile.isDirectory) return emptyList()
|
||||
|
||||
val imageUris = mutableListOf<Uri>()
|
||||
val supportedTypes = setOf(
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
"image/avif"
|
||||
)
|
||||
|
||||
fun scanDirectory(directory: DocumentFile) {
|
||||
directory.listFiles().forEach { file ->
|
||||
when {
|
||||
file.isDirectory -> scanDirectory(file) // Recursively scan subdirectories
|
||||
file.isFile && file.type in supportedTypes -> {
|
||||
file.uri?.let { imageUris.add(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scanDirectory(documentFile)
|
||||
return imageUris.sortedBy { it.toString() } // Sort for consistency
|
||||
}
|
||||
|
||||
/**
|
||||
* UUID generation
|
||||
*/
|
||||
fun generateId(): String = UUID.randomUUID().toString()
|
||||
@@ -0,0 +1,662 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.ColorMatrix
|
||||
import android.graphics.ColorMatrixColorFilter
|
||||
import android.graphics.HardwareRenderer
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RenderEffect
|
||||
import android.graphics.RenderNode
|
||||
import android.graphics.Shader
|
||||
import android.hardware.HardwareBuffer
|
||||
import android.media.ImageReader
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.util.Size
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
|
||||
/**
|
||||
* Wallpaper utility functions for bitmap processing and effects
|
||||
*
|
||||
* Improvements:
|
||||
* - Added EXIF orientation handling
|
||||
* - API-safe blur with fallback for Android < S
|
||||
* - Memory management with bitmap recycling
|
||||
* - Effect enable flags respected
|
||||
* - Quality optimization options
|
||||
*/
|
||||
|
||||
private const val TAG = "WallpaperUtil"
|
||||
private val SharedPaintFilterAntiAlias = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
|
||||
|
||||
/**
|
||||
* Get the dimensions of the image from the URI
|
||||
*/
|
||||
fun Uri.getImageDimensions(context: Context): Size? {
|
||||
// Try EXIF first
|
||||
try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val exif = ExifInterface(inputStream)
|
||||
val width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
|
||||
val height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
|
||||
if (width > 0 && height > 0) {
|
||||
return Size(width, height)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Error reading EXIF dimensions for $this, falling back: $e")
|
||||
}
|
||||
|
||||
// Fallback to BitmapFactory
|
||||
try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
if (options.outWidth > 0 && options.outHeight > 0) {
|
||||
return Size(options.outWidth, options.outHeight)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error getting image dimensions with BitmapFactory for $this: $e")
|
||||
return null
|
||||
}
|
||||
|
||||
Log.w(TAG, "Could not get image dimensions for $this")
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get EXIF orientation from URI
|
||||
*/
|
||||
fun Uri.getExifOrientation(context: Context): Int {
|
||||
return try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val exif = ExifInterface(inputStream)
|
||||
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)
|
||||
} ?: ExifInterface.ORIENTATION_UNDEFINED
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Error reading EXIF orientation: $e")
|
||||
ExifInterface.ORIENTATION_UNDEFINED
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create transformation matrix for EXIF orientation
|
||||
*/
|
||||
fun getExifTransformationMatrix(orientation: Int, width: Int, height: Int): Matrix {
|
||||
val matrix = Matrix()
|
||||
|
||||
when (orientation) {
|
||||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> {
|
||||
matrix.setScale(-1f, 1f)
|
||||
matrix.postTranslate(width.toFloat(), 0f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> {
|
||||
matrix.setRotate(180f)
|
||||
matrix.postTranslate(width.toFloat(), height.toFloat())
|
||||
}
|
||||
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
|
||||
matrix.setScale(1f, -1f)
|
||||
matrix.postTranslate(0f, height.toFloat())
|
||||
}
|
||||
ExifInterface.ORIENTATION_TRANSPOSE -> {
|
||||
matrix.setRotate(90f)
|
||||
matrix.postScale(-1f, 1f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> {
|
||||
matrix.setRotate(90f)
|
||||
matrix.postTranslate(height.toFloat(), 0f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_TRANSVERSE -> {
|
||||
matrix.setRotate(-90f)
|
||||
matrix.postScale(-1f, 1f)
|
||||
}
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> {
|
||||
matrix.setRotate(-90f)
|
||||
matrix.postTranslate(0f, width.toFloat())
|
||||
}
|
||||
}
|
||||
|
||||
return matrix
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the inSampleSize for the image
|
||||
*/
|
||||
fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
|
||||
if (imageSize.width == 0 || imageSize.height == 0) return 1
|
||||
if (width == 0 || height == 0) return 1
|
||||
|
||||
if (imageSize.width > width || imageSize.height > height) {
|
||||
val heightRatio = (imageSize.height.toFloat() / height.toFloat()).fastRoundToInt()
|
||||
val widthRatio = (imageSize.width.toFloat() / width.toFloat()).fastRoundToInt()
|
||||
return (if (heightRatio < widthRatio) heightRatio else widthRatio).coerceAtLeast(1)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Get device screen size without orientation
|
||||
*/
|
||||
object ScreenMetricsCompat {
|
||||
fun getScreenSize(context: Context): Size {
|
||||
val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
|
||||
val metrics: WindowMetrics = windowManager.currentWindowMetrics
|
||||
return Size(metrics.bounds.width(), metrics.bounds.height())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get device screen size with orientation
|
||||
*/
|
||||
fun getDeviceScreenSize(context: Context): Size {
|
||||
val orientation = context.resources.configuration.orientation
|
||||
val size = ScreenMetricsCompat.getScreenSize(context)
|
||||
return if (orientation == Configuration.ORIENTATION_PORTRAIT) {
|
||||
Size(minOf(size.width, size.height), maxOf(size.width, size.height))
|
||||
} else {
|
||||
Size(maxOf(size.width, size.height), minOf(size.width, size.height))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a bitmap from a URI that is scaled down to the device's screen size
|
||||
* Now with EXIF orientation support
|
||||
*/
|
||||
fun retrieveBitmap(
|
||||
context: Context,
|
||||
wallpaperUri: Uri,
|
||||
width: Int,
|
||||
height: Int,
|
||||
scaling: ScalingType = ScalingType.FIT
|
||||
): Bitmap? {
|
||||
val imageSize = wallpaperUri.getImageDimensions(context) ?: return null
|
||||
if (imageSize.width <= 0 || imageSize.height <= 0) {
|
||||
Log.e(TAG, "Invalid image dimensions from URI: $imageSize")
|
||||
return null
|
||||
}
|
||||
|
||||
val sampleSize = if (scaling == ScalingType.NONE) {
|
||||
1
|
||||
} else {
|
||||
calculateInSampleSize(imageSize, width, height)
|
||||
}
|
||||
|
||||
val bitmap = try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
|
||||
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
decoder.setTargetSampleSize(sampleSize)
|
||||
decoder.isMutableRequired = true
|
||||
// Use high quality when possible
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "ImageDecoder failed, falling back to BitmapFactory: $e")
|
||||
context.contentResolver.openInputStream(wallpaperUri)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle EXIF orientation
|
||||
return bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply EXIF orientation to bitmap
|
||||
*/
|
||||
private fun applyExifOrientation(source: Bitmap, uri: Uri, context: Context): Bitmap {
|
||||
val orientation = uri.getExifOrientation(context)
|
||||
if (orientation == ExifInterface.ORIENTATION_UNDEFINED || orientation == ExifInterface.ORIENTATION_NORMAL) {
|
||||
return source
|
||||
}
|
||||
|
||||
return try {
|
||||
val matrix = getExifTransformationMatrix(orientation, source.width, source.height)
|
||||
val rotated = Bitmap.createBitmap(source, 0, 0, source.width, source.height, matrix, true)
|
||||
if (rotated != source) {
|
||||
source.recycle() // Recycle old bitmap to free memory
|
||||
}
|
||||
rotated
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error applying EXIF orientation: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fit method
|
||||
* The bitmap will fit into the given dimensions while maintaining aspect ratio
|
||||
*/
|
||||
fun fitBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
if (source.width <= 0 || source.height <= 0 || width <= 0 || height <= 0) {
|
||||
Log.w(TAG, "Invalid dimensions for fitBitmap, returning source.")
|
||||
return source
|
||||
}
|
||||
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val scale = width.toFloat() / source.width
|
||||
val scaledSourceHeight = source.height * scale
|
||||
val yOffset = (height - scaledSourceHeight) / 2f
|
||||
val matrix = Matrix().apply {
|
||||
postScale(scale, scale)
|
||||
postTranslate(0f, yOffset)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error fitting bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale a bitmap using the fill method (crop to fill dimensions)
|
||||
*/
|
||||
fun fillBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val sourceAspect = source.width.toFloat() / source.height.toFloat()
|
||||
val targetAspect = width.toFloat() / height.toFloat()
|
||||
|
||||
val scale: Float
|
||||
val xOffset: Float
|
||||
val yOffset: Float
|
||||
|
||||
if (sourceAspect >= targetAspect) {
|
||||
scale = height.toFloat() / source.height.toFloat()
|
||||
xOffset = (width - source.width * scale) / 2f
|
||||
yOffset = 0f
|
||||
} else {
|
||||
scale = width.toFloat() / source.width.toFloat()
|
||||
xOffset = 0f
|
||||
yOffset = (height - source.height * scale) / 2f
|
||||
}
|
||||
|
||||
val matrix = Matrix().apply {
|
||||
postScale(scale, scale)
|
||||
postTranslate(xOffset, yOffset)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error filling bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stretch the bitmap to fit the given dimensions
|
||||
*/
|
||||
fun stretchBitmap(source: Bitmap, width: Int, height: Int): Bitmap {
|
||||
if (source.width == width && source.height == height) {
|
||||
return source
|
||||
}
|
||||
return try {
|
||||
val bitmap = createBitmap(width, height, source.config ?: Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
val matrix = Matrix().apply {
|
||||
setScale(
|
||||
width.toFloat() / source.width,
|
||||
height.toFloat() / source.height
|
||||
)
|
||||
}
|
||||
canvas.drawBitmap(source, matrix, SharedPaintFilterAntiAlias)
|
||||
bitmap
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error stretching bitmap: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Darken the bitmap by a certain percentage
|
||||
* @param brightnessToRetainPercent 0-100 (0 is darkest, 100 is original)
|
||||
*/
|
||||
fun darkenBitmap(source: Bitmap, brightnessToRetainPercent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "darkenBitmap received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return darkenBitmap(mutableCopy, brightnessToRetainPercent)
|
||||
}
|
||||
|
||||
val targetBrightnessFactor = brightnessToRetainPercent.coerceIn(0, 100) / 100f
|
||||
if (targetBrightnessFactor >= 1.0f) {
|
||||
return source
|
||||
}
|
||||
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(targetBrightnessFactor, targetBrightnessFactor, targetBrightnessFactor, 1f)
|
||||
})
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
}
|
||||
|
||||
/**
|
||||
* Blur the bitmap using GPU acceleration
|
||||
* @param percent 0-100
|
||||
*/
|
||||
fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
val clampedPercent = percent.coerceIn(0, 100)
|
||||
if (clampedPercent == 0) {
|
||||
return source
|
||||
}
|
||||
|
||||
val maxBlurRadius = 25.0f
|
||||
val radius = (clampedPercent / 100.0f) * maxBlurRadius
|
||||
|
||||
val imageReader = ImageReader.newInstance(
|
||||
source.width, source.height,
|
||||
PixelFormat.RGBA_8888, 1,
|
||||
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
|
||||
)
|
||||
|
||||
val renderNode = RenderNode("BlurEffect")
|
||||
val hardwareRenderer = HardwareRenderer()
|
||||
|
||||
var resultBitmap: Bitmap?
|
||||
try {
|
||||
hardwareRenderer.setSurface(imageReader.surface)
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
renderNode.setPosition(0, 0, source.width, source.height)
|
||||
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.MIRROR)
|
||||
renderNode.setRenderEffect(blurEffect)
|
||||
|
||||
val canvas = renderNode.beginRecording()
|
||||
canvas.drawBitmap(source, 0f, 0f, null)
|
||||
renderNode.endRecording()
|
||||
|
||||
hardwareRenderer.createRenderRequest()
|
||||
.setWaitForPresent(true)
|
||||
.syncAndDraw()
|
||||
|
||||
val image = imageReader.acquireNextImage()
|
||||
?: throw IllegalStateException("Failed to acquire blurred image")
|
||||
|
||||
val hardwareBuffer = image.hardwareBuffer
|
||||
?: throw IllegalStateException("Failed to acquire hardware buffer")
|
||||
|
||||
val hardwareBitmap = Bitmap.wrapHardwareBuffer(hardwareBuffer, null)
|
||||
?: throw IllegalStateException("Failed to create bitmap from hardware buffer")
|
||||
|
||||
// Convert hardware bitmap to regular bitmap for further processing
|
||||
// Use mutable=true to allow subsequent effects to modify in-place
|
||||
resultBitmap = hardwareBitmap.copy(Bitmap.Config.ARGB_8888, true)
|
||||
?: throw IllegalStateException("Failed to copy hardware bitmap to software bitmap")
|
||||
|
||||
hardwareBuffer.close()
|
||||
image.close()
|
||||
|
||||
} finally {
|
||||
hardwareRenderer.destroy()
|
||||
renderNode.discardDisplayList()
|
||||
imageReader.close()
|
||||
}
|
||||
|
||||
return resultBitmap
|
||||
}
|
||||
|
||||
/**
|
||||
* Blur bitmap using GPU acceleration
|
||||
*/
|
||||
fun blurBitmap(context: Context, source: Bitmap, percent: Int): Bitmap {
|
||||
return blurBitmapHardware(source, percent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a vignette effect to the bitmap
|
||||
* @param percent 0-100
|
||||
*/
|
||||
fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (percent <= 0) return source
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "vignetteBitmap received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return vignetteBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
return try {
|
||||
val canvas = Canvas(source)
|
||||
val dim = if (source.width < source.height) source.height else source.width
|
||||
val rad = (dim * (1 - (percent.coerceIn(0, 100) / 150f))).coerceAtLeast(0.1f)
|
||||
val centerX = source.width / 2f
|
||||
val centerY = source.height / 2f
|
||||
|
||||
val colors = intArrayOf(
|
||||
Color.TRANSPARENT,
|
||||
Color.argb((0.1f * 255).toInt(), 0, 0, 0),
|
||||
Color.argb((0.8f * 255).toInt(), 0, 0, 0)
|
||||
)
|
||||
val pos = floatArrayOf(0f, 0.7f, 1f)
|
||||
|
||||
val vignettePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
shader = RadialGradient(
|
||||
centerX, centerY, rad,
|
||||
colors, pos, Shader.TileMode.CLAMP
|
||||
)
|
||||
}
|
||||
canvas.drawRect(0f, 0f, source.width.toFloat(), source.height.toFloat(), vignettePaint)
|
||||
source
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error applying vignette: $e")
|
||||
source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a grayscale filter to the bitmap
|
||||
* @param percent 0-100 (0 is original, 100 is full grayscale)
|
||||
*/
|
||||
fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (percent <= 0) return source
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "grayscaleBitmap received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return grayscaleBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
val factor = percent.coerceIn(0, 100) / 100f
|
||||
if (factor <= 0f) return source
|
||||
|
||||
val colorMatrix = ColorMatrix().apply { setSaturation(1 - factor) }
|
||||
val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(colorMatrix) }
|
||||
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate brightness estimate of bitmap (0.0 - 1.0)
|
||||
* Uses luminance calculation based on RGB values
|
||||
*/
|
||||
fun calculateBitmapBrightness(bitmap: Bitmap): Float {
|
||||
// Sample pixels to estimate brightness (sampling for performance)
|
||||
val sampleSize = 10
|
||||
var totalLuminance = 0.0
|
||||
var pixelCount = 0
|
||||
|
||||
for (x in 0 until bitmap.width step sampleSize) {
|
||||
for (y in 0 until bitmap.height step sampleSize) {
|
||||
val pixel = bitmap.getPixel(x, y)
|
||||
val r = Color.red(pixel) / 255.0
|
||||
val g = Color.green(pixel) / 255.0
|
||||
val b = Color.blue(pixel) / 255.0
|
||||
|
||||
// Calculate relative luminance using ITU-R BT.709 standard
|
||||
val luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||
totalLuminance += luminance
|
||||
pixelCount++
|
||||
}
|
||||
}
|
||||
|
||||
return if (pixelCount > 0) {
|
||||
(totalLuminance / pixelCount).toFloat()
|
||||
} else {
|
||||
0.5f
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust bitmap brightness by a multiplier
|
||||
* @param brightnessFactor Brightness multiplier (e.g., 0.7 to darken, 1.5 to brighten)
|
||||
*/
|
||||
fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
if (brightnessFactor == 1.0f) return source
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "adjustBitmapBrightness received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
return adjustBitmapBrightness(mutableCopy, brightnessFactor)
|
||||
}
|
||||
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(brightnessFactor, brightnessFactor, brightnessFactor, 1f)
|
||||
})
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
}
|
||||
|
||||
/**
|
||||
* Adaptive brightness adjustment based on system dark/light mode
|
||||
* In dark mode: darkens bright images for better viewing
|
||||
* In light mode: brightens dark images for better visibility
|
||||
*
|
||||
* @param context Application context
|
||||
* @param source Source bitmap
|
||||
* @return Adjusted bitmap (or original if no adjustment needed)
|
||||
*/
|
||||
fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
|
||||
val isDarkMode = (context.resources.configuration.uiMode and
|
||||
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
|
||||
|
||||
val currentBrightness = calculateBitmapBrightness(source)
|
||||
|
||||
// Thresholds from WallYou
|
||||
val lightBrightnessMin = 0.8f
|
||||
val darkBrightnessMax = 0.3f
|
||||
val targetBrightnessDark = 0.7f
|
||||
val targetBrightnessLight = 0.4f
|
||||
|
||||
return when {
|
||||
// In dark mode with very bright image: darken it
|
||||
isDarkMode && currentBrightness > lightBrightnessMin -> {
|
||||
val adjustmentFactor = targetBrightnessDark / currentBrightness
|
||||
Log.d(TAG, "Dark mode: Darkening bright image from $currentBrightness to $targetBrightnessDark")
|
||||
adjustBitmapBrightness(source, adjustmentFactor)
|
||||
}
|
||||
// In light mode with very dark image: brighten it
|
||||
!isDarkMode && currentBrightness < darkBrightnessMax -> {
|
||||
val adjustmentFactor = targetBrightnessLight / currentBrightness
|
||||
Log.d(TAG, "Light mode: Brightening dark image from $currentBrightness to $targetBrightnessLight")
|
||||
adjustBitmapBrightness(source, adjustmentFactor)
|
||||
}
|
||||
// No adjustment needed
|
||||
else -> {
|
||||
Log.d(TAG, "No adaptive brightness adjustment needed (brightness: $currentBrightness, dark mode: $isDarkMode)")
|
||||
source
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply scaling to bitmap based on ScalingType
|
||||
*/
|
||||
fun scaleBitmap(source: Bitmap, width: Int, height: Int, scaling: ScalingType): Bitmap {
|
||||
return when (scaling) {
|
||||
ScalingType.FILL -> fillBitmap(source, width, height)
|
||||
ScalingType.FIT -> fitBitmap(source, width, height)
|
||||
ScalingType.STRETCH -> stretchBitmap(source, width, height)
|
||||
ScalingType.NONE -> source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process bitmap with all effects - now respects enable flags
|
||||
* Properly manages bitmap lifecycle by recycling intermediate results
|
||||
*/
|
||||
fun processBitmap(
|
||||
context: Context,
|
||||
source: Bitmap,
|
||||
enableDarken: Boolean = false,
|
||||
darkenPercent: Int = 0,
|
||||
enableBlur: Boolean = false,
|
||||
blurPercent: Int = 0,
|
||||
enableVignette: Boolean = false,
|
||||
vignettePercent: Int = 0,
|
||||
enableGrayscale: Boolean = false,
|
||||
grayscalePercent: Int = 0
|
||||
): Bitmap {
|
||||
var result = source
|
||||
var previous: Bitmap
|
||||
|
||||
// Apply effects in order, respecting enable flags
|
||||
// Recycle intermediate bitmaps to prevent memory leaks
|
||||
if (enableDarken && darkenPercent > 0) {
|
||||
previous = result
|
||||
result = darkenBitmap(result, 100 - darkenPercent)
|
||||
// Darken modifies in-place for mutable bitmaps, no need to recycle
|
||||
}
|
||||
|
||||
if (enableBlur && blurPercent > 0) {
|
||||
previous = result
|
||||
result = blurBitmap(context, result, blurPercent)
|
||||
// Blur always creates a new bitmap, recycle the previous one if different
|
||||
if (result !== previous && previous !== source) {
|
||||
previous.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
if (enableVignette && vignettePercent > 0) {
|
||||
previous = result
|
||||
result = vignetteBitmap(result, vignettePercent)
|
||||
// Vignette modifies in-place for mutable bitmaps, may create copy for immutable
|
||||
if (result !== previous && previous !== source) {
|
||||
previous.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
if (enableGrayscale && grayscalePercent > 0) {
|
||||
previous = result
|
||||
result = grayscaleBitmap(result, grayscalePercent)
|
||||
// Grayscale modifies in-place for mutable bitmaps, may create copy for immutable
|
||||
if (result !== previous && previous !== source) {
|
||||
previous.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.data
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.core.content.ContextCompat.startActivity
|
||||
|
||||
/**
|
||||
* Opens an email intent to contact the developer.
|
||||
*/
|
||||
fun SendContactIntent(context: Context) {
|
||||
val authorEmail = "anthonyyla.dev@gmail.com"
|
||||
val cc = ""
|
||||
val subject = "[Support] Paperize"
|
||||
val bodyText = "This is regarding the Paperize app for Android:\n"
|
||||
val mailto = "mailto:" + Uri.encode(authorEmail) +
|
||||
"?cc=" + Uri.encode(cc) +
|
||||
"&subject=" + Uri.encode(subject) +
|
||||
"&body=" + Uri.encode(bodyText)
|
||||
|
||||
val emailIntent = Intent(Intent.ACTION_SENDTO)
|
||||
emailIntent.setData(Uri.parse(mailto))
|
||||
startActivity(context, emailIntent, null)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.anthonyla.paperize.data.database
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.data.database.converters.TypeConverters as PaperizeTypeConverters
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
* Paperize Room Database
|
||||
*
|
||||
* **MAJOR ARCHITECTURAL IMPROVEMENT:**
|
||||
* - Properly normalized schema (no nested collections in entities)
|
||||
* - NO CursorWindow reflection hack needed!
|
||||
* - Proper foreign keys with cascade delete
|
||||
* - Indexed columns for performance
|
||||
* - Separate queue management table
|
||||
* - Room migrations support (no destructive migrations!)
|
||||
*
|
||||
* Version: 1
|
||||
*/
|
||||
@Database(
|
||||
entities = [
|
||||
AlbumEntity::class,
|
||||
WallpaperEntity::class,
|
||||
FolderEntity::class,
|
||||
WallpaperQueueEntity::class
|
||||
],
|
||||
version = Constants.DATABASE_VERSION,
|
||||
exportSchema = true
|
||||
)
|
||||
@TypeConverters(PaperizeTypeConverters::class)
|
||||
abstract class PaperizeDatabase : RoomDatabase() {
|
||||
abstract fun albumDao(): AlbumDao
|
||||
abstract fun wallpaperDao(): WallpaperDao
|
||||
abstract fun folderDao(): FolderDao
|
||||
abstract fun wallpaperQueueDao(): WallpaperQueueDao
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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.WallpaperSourceType
|
||||
|
||||
/**
|
||||
* Room type converters for enum types
|
||||
*/
|
||||
class TypeConverters {
|
||||
@TypeConverter
|
||||
fun fromScreenType(value: ScreenType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toScreenType(value: String): ScreenType = ScreenType.fromString(value)
|
||||
|
||||
@TypeConverter
|
||||
fun fromScalingType(value: ScalingType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toScalingType(value: String): ScalingType = ScalingType.fromString(value)
|
||||
|
||||
@TypeConverter
|
||||
fun fromWallpaperSourceType(value: WallpaperSourceType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toWallpaperSourceType(value: String): WallpaperSourceType =
|
||||
WallpaperSourceType.entries.find { it.name == value } ?: WallpaperSourceType.DIRECT
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Album operations
|
||||
*/
|
||||
@Dao
|
||||
interface AlbumDao {
|
||||
/**
|
||||
* Get all albums with their wallpapers and folders
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM albums ORDER BY modifiedAt DESC")
|
||||
fun getAllAlbumsWithDetails(): Flow<List<AlbumWithDetails>>
|
||||
|
||||
/**
|
||||
* Get a specific album by ID with details
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM albums WHERE id = :albumId")
|
||||
fun getAlbumWithDetails(albumId: String): Flow<AlbumWithDetails?>
|
||||
|
||||
/**
|
||||
* Get all albums (without relations)
|
||||
*/
|
||||
@Query("SELECT * FROM albums ORDER BY modifiedAt DESC")
|
||||
fun getAllAlbums(): Flow<List<AlbumEntity>>
|
||||
|
||||
/**
|
||||
* Get a specific album by ID
|
||||
*/
|
||||
@Query("SELECT * FROM albums WHERE id = :albumId")
|
||||
suspend fun getAlbumById(albumId: String): AlbumEntity?
|
||||
|
||||
/**
|
||||
* Get album count
|
||||
*/
|
||||
@Query("SELECT COUNT(*) FROM albums")
|
||||
suspend fun getAlbumCount(): Int
|
||||
|
||||
/**
|
||||
* Insert album
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAlbum(album: AlbumEntity)
|
||||
|
||||
/**
|
||||
* Update album
|
||||
*/
|
||||
@Update
|
||||
suspend fun updateAlbum(album: AlbumEntity)
|
||||
|
||||
/**
|
||||
* Delete album
|
||||
*/
|
||||
@Delete
|
||||
suspend fun deleteAlbum(album: AlbumEntity)
|
||||
|
||||
/**
|
||||
* Delete album by ID
|
||||
*/
|
||||
@Query("DELETE FROM albums WHERE id = :albumId")
|
||||
suspend fun deleteAlbumById(albumId: String)
|
||||
|
||||
/**
|
||||
* Update album name
|
||||
*/
|
||||
@Query("UPDATE albums SET name = :name, modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumName(albumId: String, name: String, modifiedAt: Long)
|
||||
|
||||
/**
|
||||
* Update album cover
|
||||
*/
|
||||
@Query("UPDATE albums SET coverUri = :coverUri, modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumCover(albumId: String, coverUri: String?, modifiedAt: Long)
|
||||
|
||||
/**
|
||||
* Update album modified time
|
||||
*/
|
||||
@Query("UPDATE albums SET modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumModifiedTime(albumId: String, modifiedAt: Long)
|
||||
|
||||
/**
|
||||
* Delete all albums
|
||||
*/
|
||||
@Query("DELETE FROM albums")
|
||||
suspend fun deleteAllAlbums()
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Folder operations
|
||||
*/
|
||||
@Dao
|
||||
interface FolderDao {
|
||||
/**
|
||||
* Get all folders for an album with their wallpapers
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM folders WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
fun getFoldersWithWallpapersByAlbum(albumId: String): Flow<List<FolderWithWallpapers>>
|
||||
|
||||
/**
|
||||
* Get a specific folder by ID with wallpapers
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM folders WHERE id = :folderId")
|
||||
fun getFolderWithWallpapers(folderId: String): Flow<FolderWithWallpapers?>
|
||||
|
||||
/**
|
||||
* Get a specific folder by ID
|
||||
*/
|
||||
@Query("SELECT * FROM folders WHERE id = :folderId")
|
||||
suspend fun getFolderById(folderId: String): FolderEntity?
|
||||
|
||||
/**
|
||||
* Get folder by URI
|
||||
*/
|
||||
@Query("SELECT * FROM folders WHERE uri = :uri LIMIT 1")
|
||||
suspend fun getFolderByUri(uri: String): FolderEntity?
|
||||
|
||||
/**
|
||||
* Insert folder
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertFolder(folder: FolderEntity)
|
||||
|
||||
/**
|
||||
* Update folder
|
||||
*/
|
||||
@Update
|
||||
suspend fun updateFolder(folder: FolderEntity)
|
||||
|
||||
/**
|
||||
* Update folder cover
|
||||
*/
|
||||
@Query("UPDATE folders SET coverUri = :coverUri WHERE id = :folderId")
|
||||
suspend fun updateFolderCover(folderId: String, coverUri: String?)
|
||||
|
||||
/**
|
||||
* Delete folder by ID
|
||||
*/
|
||||
@Query("DELETE FROM folders WHERE id = :folderId")
|
||||
suspend fun deleteFolderById(folderId: String)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Wallpaper operations
|
||||
*/
|
||||
@Dao
|
||||
interface WallpaperDao {
|
||||
/**
|
||||
* Get all wallpapers for an album
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
fun getWallpapersByAlbum(albumId: String): Flow<List<WallpaperEntity>>
|
||||
|
||||
/**
|
||||
* Get direct wallpapers for an album (not from folders)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND folderId IS NULL ORDER BY displayOrder ASC")
|
||||
fun getDirectWallpapersByAlbum(albumId: String): Flow<List<WallpaperEntity>>
|
||||
|
||||
/**
|
||||
* Get all wallpapers for an album (synchronous for transactions)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
suspend fun getWallpapersByAlbumSync(albumId: String): List<WallpaperEntity>
|
||||
|
||||
/**
|
||||
* Get direct wallpapers for an album (synchronous for transactions)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND folderId IS NULL ORDER BY displayOrder ASC")
|
||||
suspend fun getDirectWallpapersByAlbumSync(albumId: String): List<WallpaperEntity>
|
||||
|
||||
/**
|
||||
* Get wallpapers for a folder
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE folderId = :folderId ORDER BY displayOrder ASC")
|
||||
fun getWallpapersByFolder(folderId: String): Flow<List<WallpaperEntity>>
|
||||
|
||||
/**
|
||||
* Get a specific wallpaper by ID
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE id = :wallpaperId")
|
||||
suspend fun getWallpaperById(wallpaperId: String): WallpaperEntity?
|
||||
|
||||
/**
|
||||
* Get wallpaper by URI
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE uri = :uri LIMIT 1")
|
||||
suspend fun getWallpaperByUri(uri: String): WallpaperEntity?
|
||||
|
||||
/**
|
||||
* Insert wallpaper
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
/**
|
||||
* Insert multiple wallpapers
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertWallpapers(wallpapers: List<WallpaperEntity>)
|
||||
|
||||
/**
|
||||
* Update wallpaper
|
||||
*/
|
||||
@Update
|
||||
suspend fun updateWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
/**
|
||||
* Update wallpaper display order
|
||||
*/
|
||||
@Query("UPDATE wallpapers SET displayOrder = :order WHERE id = :wallpaperId")
|
||||
suspend fun updateWallpaperOrder(wallpaperId: String, order: Int)
|
||||
|
||||
/**
|
||||
* Delete wallpaper
|
||||
*/
|
||||
@Delete
|
||||
suspend fun deleteWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
/**
|
||||
* Delete wallpaper by ID
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE id = :wallpaperId")
|
||||
suspend fun deleteWallpaperById(wallpaperId: String)
|
||||
|
||||
/**
|
||||
* Delete wallpapers by IDs (batch operation)
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE id IN (:wallpaperIds)")
|
||||
suspend fun deleteWallpapersByIds(wallpaperIds: List<String>)
|
||||
|
||||
/**
|
||||
* Delete all wallpapers for a folder
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE folderId = :folderId")
|
||||
suspend fun deleteWallpapersByFolder(folderId: String)
|
||||
|
||||
/**
|
||||
* Delete wallpapers by URIs
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE uri IN (:uris)")
|
||||
suspend fun deleteWallpapersByUris(uris: List<String>)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Wallpaper Queue operations
|
||||
*
|
||||
* This replaces the manual queue management in the old Album entity
|
||||
*/
|
||||
@Dao
|
||||
interface WallpaperQueueDao {
|
||||
/**
|
||||
* Get next wallpaper in queue
|
||||
*/
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_queue wq ON w.id = wq.wallpaperId
|
||||
WHERE wq.albumId = :albumId AND wq.screenType = :screenType
|
||||
ORDER BY wq.queuePosition ASC
|
||||
LIMIT 1
|
||||
""")
|
||||
suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): WallpaperEntity?
|
||||
|
||||
/**
|
||||
* Atomically get and remove next wallpaper from queue
|
||||
* This prevents race conditions when multiple services try to get wallpapers simultaneously
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? {
|
||||
val wallpaper = getNextWallpaperInQueue(albumId, screenType)
|
||||
if (wallpaper != null) {
|
||||
// Delete the first item
|
||||
deleteFirstQueueItem(albumId, screenType)
|
||||
// Normalize positions to fix any gaps from CASCADE deletes
|
||||
// This ensures positions are always 0, 1, 2, 3... without gaps
|
||||
normalizeQueuePositions(albumId, screenType)
|
||||
}
|
||||
return wallpaper
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue items for album and screen type
|
||||
*/
|
||||
@Query("SELECT * FROM wallpaper_queue WHERE albumId = :albumId AND screenType = :screenType ORDER BY queuePosition ASC")
|
||||
suspend fun getQueueItems(albumId: String, screenType: ScreenType): List<WallpaperQueueEntity>
|
||||
|
||||
/**
|
||||
* Insert multiple queue items
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertQueueItems(items: List<WallpaperQueueEntity>)
|
||||
|
||||
/**
|
||||
* Remove first item from queue and normalize positions
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType) {
|
||||
// Delete the first item
|
||||
deleteFirstQueueItem(albumId, screenType)
|
||||
// Normalize positions to fix any gaps from CASCADE deletes
|
||||
normalizeQueuePositions(albumId, screenType)
|
||||
}
|
||||
|
||||
@Query("""
|
||||
DELETE FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
AND queuePosition = (
|
||||
SELECT MIN(queuePosition)
|
||||
FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
)
|
||||
""")
|
||||
suspend fun deleteFirstQueueItem(albumId: String, screenType: ScreenType)
|
||||
|
||||
/**
|
||||
* Normalize queue positions to be sequential starting from 0
|
||||
* This fixes gaps created by CASCADE deletes when wallpapers are removed
|
||||
* Called after every dequeue to ensure queue integrity
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun normalizeQueuePositions(albumId: String, screenType: ScreenType) {
|
||||
val items = getQueueItems(albumId, screenType)
|
||||
if (items.isEmpty()) return
|
||||
|
||||
// Check if normalization is needed (positions should be 0, 1, 2, ...)
|
||||
val needsNormalization = items.any { it.queuePosition != items.indexOf(it) }
|
||||
if (!needsNormalization) return
|
||||
|
||||
// Rebuild queue with normalized positions
|
||||
clearQueue(albumId, screenType)
|
||||
val normalizedItems = items.mapIndexed { index, item ->
|
||||
item.copy(queuePosition = index)
|
||||
}
|
||||
insertQueueItems(normalizedItems)
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear queue for album and screen type
|
||||
*/
|
||||
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId AND screenType = :screenType")
|
||||
suspend fun clearQueue(albumId: String, screenType: ScreenType)
|
||||
|
||||
/**
|
||||
* Clear all queues for an album
|
||||
*/
|
||||
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId")
|
||||
suspend fun clearAllQueues(albumId: String)
|
||||
|
||||
/**
|
||||
* Delete all queue items
|
||||
*/
|
||||
@Query("DELETE FROM wallpaper_queue")
|
||||
suspend fun deleteAllQueueItems()
|
||||
|
||||
/**
|
||||
* Rebuild queue with wallpaper IDs
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun rebuildQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperIds: List<String>
|
||||
) {
|
||||
clearQueue(albumId, screenType)
|
||||
val items = wallpaperIds.mapIndexed { index, wallpaperId ->
|
||||
WallpaperQueueEntity(
|
||||
albumId = albumId,
|
||||
wallpaperId = wallpaperId,
|
||||
screenType = screenType,
|
||||
queuePosition = index
|
||||
)
|
||||
}
|
||||
insertQueueItems(items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Room entity for Album
|
||||
*
|
||||
* Stores album metadata without nested collections to avoid CursorWindow issues
|
||||
*/
|
||||
@Entity(tableName = "albums")
|
||||
data class AlbumEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
val modifiedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Room entity for Folder
|
||||
*
|
||||
* No longer stores nested wallpapers - they're separate entities with foreign keys
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "folders",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [
|
||||
Index(value = ["albumId"]),
|
||||
Index(value = ["uri"])
|
||||
]
|
||||
)
|
||||
data class FolderEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
val name: String,
|
||||
val uri: String,
|
||||
val coverUri: String?,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
|
||||
/**
|
||||
* Room entity for Wallpaper
|
||||
*
|
||||
* Properly indexed foreign key to Album and optional foreign key to Folder
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "wallpapers",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
),
|
||||
ForeignKey(
|
||||
entity = FolderEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["folderId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [
|
||||
Index(value = ["albumId"]),
|
||||
Index(value = ["folderId"]),
|
||||
Index(value = ["uri"])
|
||||
]
|
||||
)
|
||||
data class WallpaperEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
@ColumnInfo(name = "folderId")
|
||||
val folderId: String? = null,
|
||||
|
||||
val uri: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/**
|
||||
* Room entity for Wallpaper Queue
|
||||
*
|
||||
* Properly manages wallpaper queues instead of storing them as JSON lists in Album
|
||||
* Separate queues for HOME and LOCK screens
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "wallpaper_queue",
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
),
|
||||
ForeignKey(
|
||||
entity = WallpaperEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["wallpaperId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [
|
||||
Index(value = ["albumId", "screenType"]),
|
||||
Index(value = ["wallpaperId"]),
|
||||
Index(value = ["queuePosition"])
|
||||
]
|
||||
)
|
||||
data class WallpaperQueueEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
@ColumnInfo(name = "wallpaperId")
|
||||
val wallpaperId: String,
|
||||
|
||||
val screenType: ScreenType,
|
||||
val queuePosition: Int,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.anthonyla.paperize.data.database.relations
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
/**
|
||||
* Room relation combining Album with its Wallpapers and Folders
|
||||
*
|
||||
* This replaces the old AlbumWithWallpaperAndFolder but with proper foreign keys
|
||||
* No nested collections in entities - avoiding CursorWindow issues!
|
||||
*/
|
||||
data class AlbumWithDetails(
|
||||
@Embedded
|
||||
val album: AlbumEntity,
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "albumId",
|
||||
entity = WallpaperEntity::class
|
||||
)
|
||||
val wallpapers: List<WallpaperEntity> = emptyList(),
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "albumId",
|
||||
entity = FolderEntity::class
|
||||
)
|
||||
val folders: List<FolderEntity> = emptyList()
|
||||
) {
|
||||
/**
|
||||
* Get direct wallpapers (not from folders)
|
||||
*/
|
||||
val directWallpapers: List<WallpaperEntity>
|
||||
get() = wallpapers.filter { it.folderId == null }
|
||||
|
||||
/**
|
||||
* Get total count including folder wallpapers
|
||||
*/
|
||||
fun getTotalWallpaperCount(folderWallpapers: Map<String, Int>): Int {
|
||||
val directCount = directWallpapers.size
|
||||
val folderCount = folders.sumOf { folderWallpapers[it.id] ?: 0 }
|
||||
return directCount + folderCount
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.anthonyla.paperize.data.database.relations
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
/**
|
||||
* Room relation combining Folder with its Wallpapers
|
||||
*/
|
||||
data class FolderWithWallpapers(
|
||||
@Embedded
|
||||
val folder: FolderEntity,
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "folderId",
|
||||
entity = WallpaperEntity::class
|
||||
)
|
||||
val wallpapers: List<WallpaperEntity> = emptyList()
|
||||
)
|
||||
@@ -0,0 +1,350 @@
|
||||
package com.anthonyla.paperize.data.datastore
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.constants.PreferenceKeys
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.WallpaperEffects
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Context extension for DataStore
|
||||
*/
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = Constants.PREFERENCES_NAME
|
||||
)
|
||||
|
||||
/**
|
||||
* PreferencesManager - Clean interface for DataStore operations
|
||||
*
|
||||
* Replaces the old SettingsDataStore with better organization and type safety
|
||||
*/
|
||||
@Singleton
|
||||
class PreferencesManager @Inject constructor(
|
||||
private val context: Context
|
||||
) {
|
||||
private val dataStore = context.dataStore
|
||||
|
||||
// ============ App Settings ============
|
||||
|
||||
suspend fun getAppSettings(): AppSettings {
|
||||
val prefs = dataStore.data.first()
|
||||
return AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: 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,
|
||||
currentHomeWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)],
|
||||
currentLockWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)]
|
||||
)
|
||||
}
|
||||
|
||||
fun getAppSettingsFlow(): Flow<AppSettings> = dataStore.data.map { prefs ->
|
||||
AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
|
||||
amoledTheme = prefs[booleanPreferencesKey(PreferenceKeys.AMOLED_THEME)] ?: false,
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: true,
|
||||
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
|
||||
currentHomeWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)],
|
||||
currentLockWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)]
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
settings.currentHomeWallpaperId?.let {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)] = it
|
||||
}
|
||||
settings.currentLockWallpaperId?.let {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)] = it
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Schedule Settings ============
|
||||
|
||||
suspend fun getScheduleSettings(): ScheduleSettings {
|
||||
val prefs = dataStore.data.first()
|
||||
return ScheduleSettings(
|
||||
enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
|
||||
separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
|
||||
shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
|
||||
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: true,
|
||||
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: true,
|
||||
homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
|
||||
lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
|
||||
homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
|
||||
lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
|
||||
homeEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: false
|
||||
),
|
||||
lockEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: false
|
||||
),
|
||||
adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
|
||||
)
|
||||
}
|
||||
|
||||
fun getScheduleSettingsFlow(): Flow<ScheduleSettings> = dataStore.data.map { prefs ->
|
||||
ScheduleSettings(
|
||||
enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
|
||||
separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
|
||||
shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
|
||||
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: true,
|
||||
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: true,
|
||||
homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
|
||||
lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
|
||||
homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
|
||||
lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
|
||||
homeEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: false
|
||||
),
|
||||
lockEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: false
|
||||
),
|
||||
adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun updateScheduleSettings(settings: ScheduleSettings) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] = settings.enableChanger
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] = settings.separateSchedules
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] = settings.shuffleEnabled
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] = settings.homeEnabled
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] = settings.lockEnabled
|
||||
if (settings.homeAlbumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)] = settings.homeAlbumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
}
|
||||
if (settings.lockAlbumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)] = settings.lockAlbumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_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
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)] = settings.lockScalingType.name
|
||||
|
||||
// Home effects
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] = settings.homeEffects.enableBlur
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] = settings.homeEffects.blurPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] = settings.homeEffects.enableDarken
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] = settings.homeEffects.darkenPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] = settings.homeEffects.enableVignette
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] = settings.homeEffects.vignettePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] = settings.homeEffects.enableGrayscale
|
||||
|
||||
// Lock effects
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] = settings.lockEffects.enableBlur
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] = settings.lockEffects.blurPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] = settings.lockEffects.enableDarken
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] = settings.lockEffects.darkenPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] = settings.lockEffects.enableVignette
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] = settings.lockEffects.vignettePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] = settings.lockEffects.enableGrayscale
|
||||
|
||||
// Adaptive brightness
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] = settings.adaptiveBrightness
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Atomic Album Selection Operations ============
|
||||
|
||||
/**
|
||||
* Atomically update home album ID without race conditions
|
||||
* This prevents lost updates when both home and lock albums are selected simultaneously
|
||||
*/
|
||||
suspend fun updateHomeAlbumId(albumId: String?) {
|
||||
dataStore.edit { prefs ->
|
||||
if (albumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)] = albumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update lock album ID without race conditions
|
||||
* This prevents lost updates when both home and lock albums are selected simultaneously
|
||||
*/
|
||||
suspend fun updateLockAlbumId(albumId: String?) {
|
||||
dataStore.edit { prefs ->
|
||||
if (albumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)] = albumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically clear album selections if they match the given album ID
|
||||
* Used when deleting an album to prevent race conditions
|
||||
* Returns true if any selections were cleared
|
||||
*/
|
||||
suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean {
|
||||
var wasCleared = false
|
||||
dataStore.edit { prefs ->
|
||||
val homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)]
|
||||
val lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)]
|
||||
|
||||
// Clear home album if it matches
|
||||
if (homeAlbumId == albumId) {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
wasCleared = true
|
||||
}
|
||||
|
||||
// Clear lock album if it matches
|
||||
if (lockAlbumId == albumId) {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
|
||||
wasCleared = true
|
||||
}
|
||||
}
|
||||
return wasCleared
|
||||
}
|
||||
|
||||
// ============ Atomic AppSettings Operations ============
|
||||
|
||||
/**
|
||||
* Atomically update dark mode setting without race conditions
|
||||
*/
|
||||
suspend fun updateDarkMode(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
suspend fun updateDynamicTheming(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update animate setting without race conditions
|
||||
*/
|
||||
suspend fun updateAnimate(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update first launch setting without race conditions
|
||||
*/
|
||||
suspend fun updateFirstLaunch(isFirstLaunch: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = isFirstLaunch
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Individual Preference Operations ============
|
||||
|
||||
suspend fun <T> setValue(key: String, value: T) {
|
||||
dataStore.edit { prefs ->
|
||||
when (value) {
|
||||
is Boolean -> prefs[booleanPreferencesKey(key)] = value
|
||||
is Int -> prefs[intPreferencesKey(key)] = value
|
||||
is Long -> prefs[longPreferencesKey(key)] = value
|
||||
is String -> prefs[stringPreferencesKey(key)] = value
|
||||
else -> throw IllegalArgumentException("Unsupported preference type")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun <T> getValue(key: String, defaultValue: T): T {
|
||||
val prefs = dataStore.data.first()
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return when (defaultValue) {
|
||||
is Boolean -> prefs[booleanPreferencesKey(key)] ?: defaultValue
|
||||
is Int -> prefs[intPreferencesKey(key)] ?: defaultValue
|
||||
is Long -> prefs[longPreferencesKey(key)] ?: defaultValue
|
||||
is String -> prefs[stringPreferencesKey(key)] ?: defaultValue
|
||||
else -> throw IllegalArgumentException("Unsupported preference type")
|
||||
} as T
|
||||
}
|
||||
|
||||
fun <T> getValueFlow(key: String, defaultValue: T): Flow<T> = dataStore.data.map { prefs ->
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
when (defaultValue) {
|
||||
is Boolean -> prefs[booleanPreferencesKey(key)] ?: defaultValue
|
||||
is Int -> prefs[intPreferencesKey(key)] ?: defaultValue
|
||||
is Long -> prefs[longPreferencesKey(key)] ?: defaultValue
|
||||
is String -> prefs[stringPreferencesKey(key)] ?: defaultValue
|
||||
else -> throw IllegalArgumentException("Unsupported preference type")
|
||||
} as T
|
||||
}
|
||||
|
||||
suspend fun clear() {
|
||||
dataStore.edit { it.clear() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
|
||||
/**
|
||||
* Mappers for Album entity <-> domain model conversion
|
||||
*/
|
||||
|
||||
fun AlbumEntity.toDomainModel(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList(),
|
||||
folders: List<com.anthonyla.paperize.domain.model.Folder> = emptyList()
|
||||
): Album = Album(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
wallpapers = wallpapers,
|
||||
folders = folders,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
)
|
||||
|
||||
fun Album.toEntity(): AlbumEntity = AlbumEntity(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
)
|
||||
|
||||
fun AlbumWithDetails.toDomainModel(): Album {
|
||||
val domainWallpapers = wallpapers
|
||||
.filter { it.folderId == null } // Only direct wallpapers
|
||||
.map { it.toDomainModel() }
|
||||
|
||||
val domainFolders = folders.map { folderEntity ->
|
||||
val folderWallpapers = wallpapers
|
||||
.filter { it.folderId == folderEntity.id }
|
||||
.map { it.toDomainModel() }
|
||||
folderEntity.toDomainModel(folderWallpapers)
|
||||
}
|
||||
|
||||
return album.toDomainModel(
|
||||
wallpapers = domainWallpapers,
|
||||
folders = domainFolders
|
||||
)
|
||||
}
|
||||
|
||||
fun List<AlbumEntity>.toDomainModels(): List<Album> = map { it.toDomainModel() }
|
||||
|
||||
fun List<AlbumWithDetails>.toDomainModelsFromRelations(): List<Album> = map { it.toDomainModel() }
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
|
||||
/**
|
||||
* Mappers for Folder entity <-> domain model conversion
|
||||
*/
|
||||
|
||||
fun FolderEntity.toDomainModel(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList()
|
||||
): Folder = Folder(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
name = name,
|
||||
uri = uri,
|
||||
coverUri = coverUri,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
wallpapers = wallpapers,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun Folder.toEntity(): FolderEntity = FolderEntity(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
name = name,
|
||||
uri = uri,
|
||||
coverUri = coverUri,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun FolderWithWallpapers.toDomainModel(): Folder = folder.toDomainModel(
|
||||
wallpapers = wallpapers.map { it.toDomainModel() }
|
||||
)
|
||||
|
||||
fun List<FolderEntity>.toDomainModels(): List<Folder> = map { it.toDomainModel() }
|
||||
|
||||
fun List<FolderWithWallpapers>.toDomainModelsFromRelations(): List<Folder> = map { it.toDomainModel() }
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Mappers for Wallpaper entity <-> domain model conversion
|
||||
*/
|
||||
|
||||
fun WallpaperEntity.toDomainModel(): Wallpaper = Wallpaper(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
folderId = folderId,
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
sourceType = sourceType,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
folderId = folderId,
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
sourceType = sourceType,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun List<WallpaperEntity>.toDomainModels(): List<Wallpaper> = map { it.toDomainModel() }
|
||||
|
||||
fun List<Wallpaper>.toEntities(): List<WallpaperEntity> = map { it.toEntity() }
|
||||
@@ -1,62 +0,0 @@
|
||||
package com.anthonyla.paperize.data
|
||||
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.State
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
|
||||
/**
|
||||
* Remember the current offset of a [LazyListState].
|
||||
* Source:
|
||||
* https://stackoverflow.com/a/75677163
|
||||
* https://stackoverflow.com/a/70558512
|
||||
*/
|
||||
@Composable
|
||||
fun rememberCurrentOffset(state: LazyListState): State<Int> {
|
||||
val position = remember { derivedStateOf { state.firstVisibleItemIndex } }
|
||||
val itemOffset = remember { derivedStateOf { state.firstVisibleItemScrollOffset } }
|
||||
val lastPosition = rememberPrevious(position.value)
|
||||
val lastItemOffset = rememberPrevious(itemOffset.value)
|
||||
val currentOffset = remember { mutableIntStateOf(0) }
|
||||
|
||||
LaunchedEffect(position.value, itemOffset.value) {
|
||||
currentOffset.intValue = when {
|
||||
lastPosition == null || position.value == 0 -> itemOffset.value
|
||||
lastPosition == position.value -> currentOffset.intValue + (itemOffset.value - (lastItemOffset ?: 0))
|
||||
lastPosition > position.value -> currentOffset.intValue - (lastItemOffset ?: 0)
|
||||
else -> currentOffset.intValue + itemOffset.value
|
||||
}
|
||||
}
|
||||
|
||||
return currentOffset
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun <T> rememberPrevious(
|
||||
current: T,
|
||||
shouldUpdate: (prev: T?, curr: T) -> Boolean = { prev, curr -> prev != curr },
|
||||
): T? {
|
||||
val ref = rememberRef<T>()
|
||||
SideEffect {
|
||||
if (shouldUpdate(ref.value, current)) {
|
||||
ref.value = current
|
||||
}
|
||||
}
|
||||
return ref.value
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun <T> rememberRef(): MutableState<T?> {
|
||||
return remember {
|
||||
object : MutableState<T?> {
|
||||
override var value: T? = null
|
||||
override fun component1(): T? = value
|
||||
override fun component2(): (T?) -> Unit = { value = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import androidx.room.withTransaction
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.util.generateId
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModel
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModelsFromRelations
|
||||
import com.anthonyla.paperize.data.mapper.toEntities
|
||||
import com.anthonyla.paperize.data.mapper.toEntity
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Implementation of AlbumRepository
|
||||
*
|
||||
* Handles data operations for albums using Room database
|
||||
*/
|
||||
@Singleton
|
||||
class AlbumRepositoryImpl @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val database: PaperizeDatabase,
|
||||
private val albumDao: AlbumDao,
|
||||
private val wallpaperDao: WallpaperDao,
|
||||
private val folderDao: FolderDao
|
||||
) : AlbumRepository {
|
||||
|
||||
override fun getAllAlbums(): Flow<List<Album>> =
|
||||
albumDao.getAllAlbumsWithDetails().map { it.toDomainModelsFromRelations() }
|
||||
|
||||
override fun getAlbumById(albumId: String): Flow<Album?> =
|
||||
albumDao.getAlbumWithDetails(albumId).map { it?.toDomainModel() }
|
||||
|
||||
override fun getFolderById(folderId: String): Flow<Folder?> =
|
||||
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
|
||||
|
||||
override suspend fun createAlbum(name: String, coverUri: String?): Result<Album> {
|
||||
return try {
|
||||
val album = Album(
|
||||
id = generateId(),
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
modifiedAt = System.currentTimeMillis()
|
||||
)
|
||||
albumDao.insertAlbum(album.toEntity())
|
||||
Result.Success(album)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateAlbum(album: Album): Result<Unit> {
|
||||
return try {
|
||||
albumDao.updateAlbum(album.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteAlbum(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
albumDao.deleteAlbumById(albumId)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateAlbumName(albumId: String, name: String): Result<Unit> {
|
||||
return try {
|
||||
albumDao.updateAlbumName(albumId, name, System.currentTimeMillis())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result<Unit> {
|
||||
return try {
|
||||
albumDao.updateAlbumCover(albumId, coverUri, System.currentTimeMillis())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - insert wallpapers, update timestamp, and update cover
|
||||
database.withTransaction {
|
||||
wallpaperDao.insertWallpapers(wallpapers.toEntities())
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Update album cover if it doesn't have one
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun addFolderToAlbum(albumId: String, folder: Folder): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - folder, wallpapers, timestamp, and cover all succeed or all fail
|
||||
database.withTransaction {
|
||||
folderDao.insertFolder(folder.toEntity())
|
||||
// Insert folder wallpapers
|
||||
wallpaperDao.insertWallpapers(folder.wallpapers.toEntities())
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Update album cover if it doesn't have one
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateFolder(folder: Folder): Result<Unit> {
|
||||
return try {
|
||||
folderDao.updateFolder(folder.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeWallpaperFromAlbum(
|
||||
albumId: String,
|
||||
wallpaperId: String
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - delete wallpaper, update timestamp, and refresh cover
|
||||
database.withTransaction {
|
||||
val wallpaper = wallpaperDao.getWallpaperById(wallpaperId)
|
||||
wallpaperDao.deleteWallpaperById(wallpaperId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Refresh cover if deleted wallpaper was the cover
|
||||
val album = albumDao.getAlbumById(albumId)
|
||||
if (album?.coverUri == wallpaper?.uri) {
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeWallpapersFromAlbum(
|
||||
albumId: String,
|
||||
wallpaperIds: List<String>
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
if (wallpaperIds.isEmpty()) {
|
||||
return Result.Success(Unit)
|
||||
}
|
||||
|
||||
// Atomic transaction - delete wallpapers, update timestamp, and refresh cover
|
||||
database.withTransaction {
|
||||
val album = albumDao.getAlbumById(albumId)
|
||||
val currentCoverUri = album?.coverUri
|
||||
|
||||
// Batch delete wallpapers
|
||||
wallpaperDao.deleteWallpapersByIds(wallpaperIds)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Refresh cover if any deleted wallpaper was the cover
|
||||
// (we check by querying the album cover to see if it still exists)
|
||||
if (currentCoverUri != null) {
|
||||
val coverStillExists = wallpaperDao.getWallpaperByUri(currentCoverUri) != null
|
||||
if (!coverStillExists) {
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
}
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeFolderFromAlbum(albumId: String, folderId: String): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - delete folder, update timestamp, and refresh cover
|
||||
database.withTransaction {
|
||||
folderDao.deleteFolderById(folderId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Always refresh cover after folder deletion (folder wallpapers might be cover)
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getAlbumCount(): Int = albumDao.getAlbumCount()
|
||||
|
||||
override suspend fun deleteAllAlbums(): Result<Unit> {
|
||||
return try {
|
||||
albumDao.deleteAllAlbums()
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun validateAndRemoveInvalidFolders(albumId: String): Result<Int> {
|
||||
return try {
|
||||
val album = albumDao.getAlbumWithDetails(albumId).first() ?: return Result.Success(0)
|
||||
val folders = album.folders.map { it.toDomainModel() }
|
||||
|
||||
val invalidFolderIds = folders.filter { folder ->
|
||||
// Check if folder URI is still valid
|
||||
val uri = Uri.parse(folder.uri)
|
||||
val documentFile = DocumentFile.fromTreeUri(context, uri)
|
||||
documentFile == null || !documentFile.exists() || !documentFile.canRead()
|
||||
}.map { it.id }
|
||||
|
||||
if (invalidFolderIds.isNotEmpty()) {
|
||||
// Atomic transaction - delete all invalid folders or none
|
||||
database.withTransaction {
|
||||
invalidFolderIds.forEach { folderId ->
|
||||
folderDao.deleteFolderById(folderId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result.Success(invalidFolderIds.size)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun refreshAlbumCover(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
database.withTransaction {
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun refreshFolderCovers(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
// Get all folders in the album with their wallpapers
|
||||
val folders = folderDao.getFoldersWithWallpapersByAlbum(albumId).first()
|
||||
|
||||
// Update each folder's cover to its first wallpaper
|
||||
folders.forEach { folderWithWallpapers ->
|
||||
val folder = folderWithWallpapers.folder
|
||||
val wallpapers = folderWithWallpapers.wallpapers
|
||||
val newCoverUri = wallpapers.firstOrNull()?.uri
|
||||
|
||||
// Only update if cover changed
|
||||
if (folder.coverUri != newCoverUri) {
|
||||
folderDao.updateFolderCover(folder.id, newCoverUri)
|
||||
}
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update album cover art based on available wallpapers
|
||||
* Priority: 1) First direct wallpaper, 2) First wallpaper from first folder
|
||||
* NOTE: This must be called within a transaction
|
||||
*/
|
||||
private suspend fun updateAlbumCoverIfNeeded(albumId: String) {
|
||||
val album = albumDao.getAlbumById(albumId) ?: return
|
||||
|
||||
// Try to get first direct wallpaper (uploaded directly, not from folder)
|
||||
val directWallpapers = wallpaperDao.getDirectWallpapersByAlbumSync(albumId)
|
||||
val newCoverUri = when {
|
||||
// Priority 1: First direct wallpaper
|
||||
directWallpapers.isNotEmpty() -> directWallpapers.first().uri
|
||||
|
||||
// Priority 2: First wallpaper from any folder
|
||||
else -> {
|
||||
val allWallpapers = wallpaperDao.getWallpapersByAlbumSync(albumId)
|
||||
allWallpapers.firstOrNull()?.uri
|
||||
}
|
||||
}
|
||||
|
||||
// Only update if cover changed
|
||||
if (album.coverUri != newCoverUri) {
|
||||
albumDao.updateAlbumCover(albumId, newCoverUri, System.currentTimeMillis())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import com.anthonyla.paperize.data.datastore.PreferencesManager
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Implementation of SettingsRepository
|
||||
*/
|
||||
@Singleton
|
||||
class SettingsRepositoryImpl @Inject constructor(
|
||||
private val preferencesManager: PreferencesManager
|
||||
) : SettingsRepository {
|
||||
|
||||
override suspend fun getAppSettings(): AppSettings =
|
||||
preferencesManager.getAppSettings()
|
||||
|
||||
override fun getAppSettingsFlow(): Flow<AppSettings> =
|
||||
preferencesManager.getAppSettingsFlow()
|
||||
|
||||
override suspend fun updateAppSettings(settings: AppSettings) =
|
||||
preferencesManager.updateAppSettings(settings)
|
||||
|
||||
override suspend fun getScheduleSettings(): ScheduleSettings =
|
||||
preferencesManager.getScheduleSettings()
|
||||
|
||||
override fun getScheduleSettingsFlow(): Flow<ScheduleSettings> =
|
||||
preferencesManager.getScheduleSettingsFlow()
|
||||
|
||||
override suspend fun updateScheduleSettings(settings: ScheduleSettings) =
|
||||
preferencesManager.updateScheduleSettings(settings)
|
||||
|
||||
override suspend fun clearAllSettings() =
|
||||
preferencesManager.clear()
|
||||
|
||||
override suspend fun updateHomeAlbumId(albumId: String?) =
|
||||
preferencesManager.updateHomeAlbumId(albumId)
|
||||
|
||||
override suspend fun updateLockAlbumId(albumId: String?) =
|
||||
preferencesManager.updateLockAlbumId(albumId)
|
||||
|
||||
override suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean =
|
||||
preferencesManager.clearAlbumSelectionsIfMatches(albumId)
|
||||
|
||||
// ============ Atomic AppSettings Operations ============
|
||||
|
||||
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)
|
||||
|
||||
override suspend fun updateAnimate(enabled: Boolean) =
|
||||
preferencesManager.updateAnimate(enabled)
|
||||
|
||||
override suspend fun updateFirstLaunch(isFirstLaunch: Boolean) =
|
||||
preferencesManager.updateFirstLaunch(isFirstLaunch)
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.generateId
|
||||
import com.anthonyla.paperize.core.util.isValid
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModel
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModels
|
||||
import com.anthonyla.paperize.data.mapper.toEntity
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* Implementation of WallpaperRepository
|
||||
*/
|
||||
@Singleton
|
||||
class WallpaperRepositoryImpl @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val wallpaperDao: WallpaperDao,
|
||||
private val wallpaperQueueDao: WallpaperQueueDao
|
||||
) : WallpaperRepository {
|
||||
|
||||
private val contentResolver: ContentResolver = context.contentResolver
|
||||
|
||||
/**
|
||||
* Mutexes to synchronize queue rebuild operations per (albumId, screenType)
|
||||
* Prevents duplicate rebuilds when multiple threads detect empty queue simultaneously
|
||||
*/
|
||||
private val queueRebuildMutexes = ConcurrentHashMap<String, Mutex>()
|
||||
|
||||
override fun getWallpapersByAlbum(albumId: String): Flow<List<Wallpaper>> =
|
||||
wallpaperDao.getWallpapersByAlbum(albumId).map { it.toDomainModels() }
|
||||
|
||||
override fun getDirectWallpapersByAlbum(albumId: String): Flow<List<Wallpaper>> =
|
||||
wallpaperDao.getDirectWallpapersByAlbum(albumId).map { it.toDomainModels() }
|
||||
|
||||
override fun getWallpapersByFolder(folderId: String): Flow<List<Wallpaper>> =
|
||||
wallpaperDao.getWallpapersByFolder(folderId).map { it.toDomainModels() }
|
||||
|
||||
override suspend fun getWallpaperById(wallpaperId: String): Wallpaper? =
|
||||
wallpaperDao.getWallpaperById(wallpaperId)?.toDomainModel()
|
||||
|
||||
override suspend fun addWallpaper(wallpaper: Wallpaper): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.insertWallpaper(wallpaper.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateWallpaper(wallpaper: Wallpaper): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.updateWallpaper(wallpaper.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaper(wallpaperId: String): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.deleteWallpaperById(wallpaperId)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpapers(wallpaperIds: List<String>): Result<Unit> {
|
||||
return try {
|
||||
if (wallpaperIds.isEmpty()) {
|
||||
return Result.Success(Unit)
|
||||
}
|
||||
wallpaperDao.deleteWallpapersByIds(wallpaperIds)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpapersByFolderId(folderId: String): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.deleteWallpapersByFolder(folderId)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateWallpaperOrder(wallpaperId: String, order: Int): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.updateWallpaperOrder(wallpaperId, order)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result<Int> {
|
||||
return try {
|
||||
val wallpapers = wallpaperDao.getWallpapersByAlbum(albumId).first()
|
||||
val invalidUris = wallpapers
|
||||
.filter { !Uri.parse(it.uri).isValid(contentResolver) }
|
||||
.map { it.uri }
|
||||
|
||||
if (invalidUris.isNotEmpty()) {
|
||||
wallpaperDao.deleteWallpapersByUris(invalidUris)
|
||||
}
|
||||
|
||||
Result.Success(invalidUris.size)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getAndDequeueWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun buildWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
shuffle: Boolean
|
||||
): Result<Unit> {
|
||||
// In shuffle mode, use album-level mutex to ensure synchronized shuffle order
|
||||
// In sequential mode, use per-screen mutex for independent rebuilds
|
||||
val mutexKey = if (shuffle) albumId else "$albumId:$screenType"
|
||||
val mutex = queueRebuildMutexes.getOrPut(mutexKey) { Mutex() }
|
||||
|
||||
return mutex.withLock {
|
||||
try {
|
||||
val wallpapers = wallpaperDao.getWallpapersByAlbum(albumId).first()
|
||||
|
||||
// If shuffle is enabled, check if there's an existing queue for another screen type
|
||||
// with the same album to maintain synchronized order
|
||||
val wallpaperIds = if (shuffle) {
|
||||
// Check other screen types for existing queue with same album
|
||||
val otherScreenType = when (screenType) {
|
||||
ScreenType.HOME -> ScreenType.LOCK
|
||||
ScreenType.LOCK -> ScreenType.HOME
|
||||
ScreenType.BOTH -> null
|
||||
}
|
||||
|
||||
val existingQueueIds = otherScreenType?.let {
|
||||
try {
|
||||
wallpaperQueueDao.getQueueItems(albumId, it)
|
||||
.map { queueItem -> queueItem.wallpaperId }
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
// If another screen type has a queue for the same album, use that order
|
||||
// Otherwise, create a new shuffled order
|
||||
if (existingQueueIds != null && existingQueueIds.isNotEmpty()) {
|
||||
// Filter to only include IDs that still exist in the current wallpaper list
|
||||
val currentWallpaperIds = wallpapers.map { it.id }.toSet()
|
||||
val filteredIds = existingQueueIds.filter { it in currentWallpaperIds }
|
||||
|
||||
// Add any new wallpapers that aren't in the existing queue
|
||||
val newWallpaperIds = wallpapers
|
||||
.map { it.id }
|
||||
.filter { it !in existingQueueIds }
|
||||
.shuffled()
|
||||
|
||||
filteredIds + newWallpaperIds
|
||||
} else {
|
||||
wallpapers.map { it.id }.shuffled()
|
||||
}
|
||||
} else {
|
||||
wallpapers.sortedBy { it.displayOrder }.map { it.id }
|
||||
}
|
||||
|
||||
wallpaperQueueDao.rebuildQueue(albumId, screenType, wallpaperIds)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType): Result<Unit> {
|
||||
return try {
|
||||
wallpaperQueueDao.dequeueWallpaper(albumId, screenType)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clearAllQueues(): Result<Unit> {
|
||||
return try {
|
||||
wallpaperQueueDao.deleteAllQueueItems()
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun normalizeAllQueuesForAlbum(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
// Normalize both HOME and LOCK queues for this album
|
||||
// This fixes gaps in queue positions caused by CASCADE deletes
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.HOME)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LOCK)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun scanFolderForWallpapers(folderUri: Uri): Result<List<Wallpaper>> {
|
||||
return try {
|
||||
val documentFile = DocumentFile.fromTreeUri(context, folderUri)
|
||||
?: return Result.Error(Exception("Invalid folder URI"))
|
||||
|
||||
val wallpapers = documentFile.listFiles()
|
||||
.filter { it.isFile && it.name?.let { name -> isImageFile(name) } == true }
|
||||
.mapNotNull { file ->
|
||||
try {
|
||||
val uri = file.uri.toString()
|
||||
val fileName = file.name ?: return@mapNotNull null
|
||||
val dateModified = file.lastModified()
|
||||
|
||||
Wallpaper(
|
||||
id = generateId(),
|
||||
albumId = "", // Will be set when adding to album
|
||||
folderId = null, // Will be set when adding to folder
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
Result.Success(wallpapers)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun isImageFile(fileName: String): Boolean {
|
||||
val extension = fileName.substringAfterLast('.', "").lowercase()
|
||||
return extension in Constants.SUPPORTED_IMAGE_EXTENSIONS
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.anthonyla.paperize.data.settings
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Interface for the data store that handles the settings for application
|
||||
*/
|
||||
interface SettingsDataStore {
|
||||
suspend fun putBoolean(key: String, value: Boolean)
|
||||
suspend fun putString(key: String, value: String)
|
||||
suspend fun putInt(key: String, value: Int)
|
||||
suspend fun getBoolean(key: String): Boolean?
|
||||
suspend fun getString(key: String): String?
|
||||
suspend fun getInt(key: String): Int?
|
||||
fun getBooleanFlow(key: String): Flow<Boolean?>
|
||||
fun getStringFlow(key: String): Flow<String?>
|
||||
fun getIntFlow(key: String): Flow<Int?>
|
||||
suspend fun deleteBoolean(key: String)
|
||||
suspend fun deleteString(key: String)
|
||||
suspend fun deleteInt(key: String)
|
||||
suspend fun clear(keys: List<String>)
|
||||
suspend fun clearPreferences()
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
package com.anthonyla.paperize.data.settings
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.anthonyla.paperize.core.SettingsConstants.SETTINGS_DATASTORE
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = SETTINGS_DATASTORE)
|
||||
|
||||
class SettingsDataStoreImpl(private val context: Context) : SettingsDataStore {
|
||||
override suspend fun putBoolean(key: String, value: Boolean) {
|
||||
val preferencesKey = booleanPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
it[preferencesKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun putString(key: String, value: String) {
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
it[preferencesKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun putInt(key: String, value: Int) {
|
||||
val preferencesKey = intPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
it[preferencesKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getBoolean(key: String): Boolean? {
|
||||
val head = context.dataStore.data.first()
|
||||
val preferencesKey = booleanPreferencesKey(key)
|
||||
return head[preferencesKey]
|
||||
}
|
||||
|
||||
override suspend fun getString(key: String): String? {
|
||||
return try {
|
||||
val head = context.dataStore.data.first()
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
head[preferencesKey]
|
||||
} catch (exception: Exception) {
|
||||
exception.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getInt(key: String): Int? {
|
||||
return try {
|
||||
val preferences = context.dataStore.data.first()
|
||||
val intKey = intPreferencesKey(key)
|
||||
val stringKey = stringPreferencesKey(key)
|
||||
|
||||
preferences[intKey] ?: preferences[stringKey]?.toIntOrNull()
|
||||
} catch (exception: Exception) {
|
||||
exception.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
override fun getBooleanFlow(key: String): Flow<Boolean?> = context.dataStore.data
|
||||
.catch { exception ->
|
||||
exception.printStackTrace()
|
||||
emit(emptyPreferences())
|
||||
}
|
||||
.map { preferences ->
|
||||
preferences[booleanPreferencesKey(key)]
|
||||
}
|
||||
|
||||
override fun getStringFlow(key: String): Flow<String?> = context.dataStore.data
|
||||
.catch { exception ->
|
||||
exception.printStackTrace()
|
||||
emit(emptyPreferences())
|
||||
}
|
||||
.map { preferences ->
|
||||
preferences[stringPreferencesKey(key)]
|
||||
}
|
||||
|
||||
override fun getIntFlow(key: String): Flow<Int?> {
|
||||
val intKey = intPreferencesKey(key)
|
||||
val stringKey = stringPreferencesKey(key)
|
||||
|
||||
return context.dataStore.data
|
||||
.catch { exception ->
|
||||
exception.printStackTrace()
|
||||
emit(emptyPreferences())
|
||||
}
|
||||
.map { preferences ->
|
||||
val valueAsInt = preferences[intKey]
|
||||
|
||||
if (valueAsInt != null) {
|
||||
valueAsInt
|
||||
} else {
|
||||
val valueAsString = preferences[stringKey]
|
||||
valueAsString?.toIntOrNull()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteBoolean(key: String) {
|
||||
val preferencesKey = booleanPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
if (it.contains(preferencesKey)) {
|
||||
it.remove(preferencesKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteString(key: String) {
|
||||
val preferencesKey = stringPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
if (it.contains(preferencesKey)) {
|
||||
it.remove(preferencesKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteInt(key: String) {
|
||||
val preferencesKey = intPreferencesKey(key)
|
||||
context.dataStore.edit {
|
||||
if (it.contains(preferencesKey)) {
|
||||
it.remove(preferencesKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clearPreferences() {
|
||||
context.dataStore.edit {
|
||||
it.clear()
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clear(keys: List<String>) {
|
||||
context.dataStore.edit { preferences ->
|
||||
keys.forEach { key ->
|
||||
if (preferences.contains(booleanPreferencesKey(key))) {
|
||||
preferences.remove(booleanPreferencesKey(key))
|
||||
}
|
||||
else if (preferences.contains(stringPreferencesKey(key))) {
|
||||
preferences.remove(stringPreferencesKey(key))
|
||||
}
|
||||
else if (preferences.contains(intPreferencesKey(key))) {
|
||||
preferences.remove(intPreferencesKey(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.anthonyla.paperize.di
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import com.anthonyla.paperize.data.settings.SettingsDataStore
|
||||
import com.anthonyla.paperize.data.settings.SettingsDataStoreImpl
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDatabase
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.repository.AlbumRepositoryImpl
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* AppModule provides dependencies for the application for Dagger Hilt to inject
|
||||
*/
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object AppModule {
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumDatabase(app: Application): AlbumDatabase {
|
||||
return Room.databaseBuilder(
|
||||
app,
|
||||
AlbumDatabase::class.java,
|
||||
AlbumDatabase.DATABASE_NAME
|
||||
).fallbackToDestructiveMigration(true).build()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumDao(db: AlbumDatabase) = db.albumDao
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumRepository(
|
||||
db: AlbumDatabase
|
||||
): AlbumRepository {
|
||||
return AlbumRepositoryImpl(db.albumDao)
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSettingsDataStore (
|
||||
@ApplicationContext context: Context
|
||||
): SettingsDataStore = SettingsDataStoreImpl(context)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideContext(
|
||||
@ApplicationContext context: Context,
|
||||
): Context { return context }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
/**
|
||||
* Domain model for Album
|
||||
*
|
||||
* Pure Kotlin data class without Room annotations
|
||||
*/
|
||||
data class Album(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
val folders: List<Folder> = emptyList(),
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
val modifiedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
/**
|
||||
* Get total wallpaper count (direct + in folders)
|
||||
*/
|
||||
val totalWallpaperCount: Int
|
||||
get() = wallpapers.size + folders.sumOf { it.wallpapers.size }
|
||||
|
||||
/**
|
||||
* Get all wallpapers (direct + from folders)
|
||||
*/
|
||||
val allWallpapers: List<Wallpaper>
|
||||
get() = wallpapers + folders.flatMap { it.wallpapers }
|
||||
|
||||
/**
|
||||
* Get all wallpapers sorted by display order
|
||||
*/
|
||||
val sortedWallpapers: List<Wallpaper>
|
||||
get() = allWallpapers.sortedBy { it.displayOrder }
|
||||
|
||||
/**
|
||||
* Check if album is empty
|
||||
*/
|
||||
val isEmpty: Boolean
|
||||
get() = totalWallpaperCount == 0
|
||||
|
||||
companion object {
|
||||
fun empty(id: String = "", name: String = "") = Album(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = null
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
/**
|
||||
* Domain model for App Settings (theme, preferences, etc.)
|
||||
*/
|
||||
data class AppSettings(
|
||||
val darkMode: Boolean? = null, // null = system default, true = dark, false = light
|
||||
val amoledTheme: Boolean = false,
|
||||
val dynamicTheming: Boolean = true,
|
||||
val animate: Boolean = true,
|
||||
val firstLaunch: Boolean = true,
|
||||
val currentHomeWallpaperId: String? = null,
|
||||
val currentLockWallpaperId: String? = null
|
||||
) {
|
||||
companion object {
|
||||
fun default() = AppSettings()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.net.Uri
|
||||
|
||||
/**
|
||||
* Domain model for Folder
|
||||
*
|
||||
* Pure Kotlin data class without Room annotations
|
||||
*/
|
||||
data class Folder(
|
||||
val id: String,
|
||||
val albumId: String,
|
||||
val name: String,
|
||||
val uri: String,
|
||||
val coverUri: String?,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
/**
|
||||
* Get URL-decoded name for display (last path segment only)
|
||||
*/
|
||||
val displayName: String
|
||||
get() = try {
|
||||
val decoded = Uri.decode(name)
|
||||
// Extract just the folder name (last segment after / or :)
|
||||
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
|
||||
} catch (e: Exception) {
|
||||
name
|
||||
}
|
||||
|
||||
/**
|
||||
* Get wallpaper count
|
||||
*/
|
||||
val wallpaperCount: Int
|
||||
get() = wallpapers.size
|
||||
|
||||
/**
|
||||
* Check if folder is empty
|
||||
*/
|
||||
val isEmpty: Boolean
|
||||
get() = wallpapers.isEmpty()
|
||||
|
||||
/**
|
||||
* Get sorted wallpapers
|
||||
*/
|
||||
val sortedWallpapers: List<Wallpaper>
|
||||
get() = wallpapers.sortedBy { it.displayOrder }
|
||||
|
||||
companion object {
|
||||
fun empty(id: String = "", albumId: String = "") = Folder(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
name = "",
|
||||
uri = "",
|
||||
coverUri = null,
|
||||
dateModified = 0L
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
* Domain model for Wallpaper Schedule Settings
|
||||
*/
|
||||
data class ScheduleSettings(
|
||||
val enableChanger: Boolean = false,
|
||||
val separateSchedules: Boolean = false,
|
||||
val shuffleEnabled: Boolean = false,
|
||||
val homeEnabled: Boolean = false,
|
||||
val lockEnabled: Boolean = false,
|
||||
val homeAlbumId: String? = null,
|
||||
val lockAlbumId: String? = null,
|
||||
val homeIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
val lockIntervalMinutes: Int = Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
val homeScalingType: ScalingType = ScalingType.FILL,
|
||||
val lockScalingType: ScalingType = ScalingType.FILL,
|
||||
val homeEffects: WallpaperEffects = WallpaperEffects.none(),
|
||||
val lockEffects: WallpaperEffects = WallpaperEffects.none(),
|
||||
val adaptiveBrightness: Boolean = false
|
||||
) {
|
||||
/**
|
||||
* Validate interval values
|
||||
*/
|
||||
fun validate(): ScheduleSettings = copy(
|
||||
homeIntervalMinutes = homeIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
|
||||
lockIntervalMinutes = lockIntervalMinutes.coerceAtLeast(Constants.MIN_INTERVAL_MINUTES),
|
||||
homeEffects = homeEffects.validate(),
|
||||
lockEffects = lockEffects.validate()
|
||||
)
|
||||
|
||||
companion object {
|
||||
fun default() = ScheduleSettings()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.net.Uri
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
|
||||
/**
|
||||
* Domain model for Wallpaper
|
||||
*
|
||||
* Pure Kotlin data class without Room annotations
|
||||
*/
|
||||
data class Wallpaper(
|
||||
val id: String,
|
||||
val albumId: String,
|
||||
val folderId: String? = null,
|
||||
val uri: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
|
||||
val addedAt: Long = System.currentTimeMillis()
|
||||
) {
|
||||
/**
|
||||
* Get URL-decoded file name for display (filename only, no path)
|
||||
*/
|
||||
val displayFileName: String
|
||||
get() = try {
|
||||
val decoded = Uri.decode(fileName)
|
||||
// Extract just the filename (last segment after / or :)
|
||||
decoded.substringAfterLast('/', decoded.substringAfterLast(':', decoded))
|
||||
} catch (e: Exception) {
|
||||
fileName
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if wallpaper is from a folder
|
||||
*/
|
||||
val isFromFolder: Boolean
|
||||
get() = folderId != null && sourceType == WallpaperSourceType.FOLDER
|
||||
|
||||
/**
|
||||
* Get file extension
|
||||
*/
|
||||
val extension: String
|
||||
get() = fileName.substringAfterLast('.', "").lowercase()
|
||||
|
||||
/**
|
||||
* Check if file is a valid image
|
||||
*/
|
||||
val isValidImage: Boolean
|
||||
get() = extension in setOf("jpg", "jpeg", "png", "webp", "avif")
|
||||
|
||||
companion object {
|
||||
fun empty(id: String = "", albumId: String = "") = Wallpaper(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
uri = "",
|
||||
fileName = "",
|
||||
dateModified = 0L
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
* Domain model for Wallpaper Effects
|
||||
*
|
||||
* Represents the visual effects applied to wallpapers
|
||||
*/
|
||||
data class WallpaperEffects(
|
||||
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
|
||||
) {
|
||||
/**
|
||||
* Check if any effects are applied
|
||||
*/
|
||||
val hasEffects: Boolean
|
||||
get() = (enableBlur && blurPercentage > 0) ||
|
||||
(enableDarken && darkenPercentage != 0) ||
|
||||
(enableVignette && vignettePercentage > 0) ||
|
||||
enableGrayscale
|
||||
|
||||
/**
|
||||
* Validate effect percentages
|
||||
*/
|
||||
fun validate(): WallpaperEffects = copy(
|
||||
darkenPercentage = darkenPercentage.coerceIn(-100, 100),
|
||||
blurPercentage = blurPercentage.coerceIn(0, 100),
|
||||
vignettePercentage = vignettePercentage.coerceIn(0, 100)
|
||||
)
|
||||
|
||||
companion object {
|
||||
fun default() = WallpaperEffects()
|
||||
fun none() = WallpaperEffects()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.anthonyla.paperize.domain.repository
|
||||
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Repository interface for Album operations
|
||||
*
|
||||
* Clean interface following repository pattern - implementation in data layer
|
||||
*/
|
||||
interface AlbumRepository {
|
||||
/**
|
||||
* Get all albums with their wallpapers and folders
|
||||
*/
|
||||
fun getAllAlbums(): Flow<List<Album>>
|
||||
|
||||
/**
|
||||
* Get a specific album by ID
|
||||
*/
|
||||
fun getAlbumById(albumId: String): Flow<Album?>
|
||||
|
||||
/**
|
||||
* Get a specific folder by ID
|
||||
*/
|
||||
fun getFolderById(folderId: String): Flow<Folder?>
|
||||
|
||||
/**
|
||||
* Create a new album
|
||||
*/
|
||||
suspend fun createAlbum(name: String, coverUri: String? = null): Result<Album>
|
||||
|
||||
/**
|
||||
* Update album
|
||||
*/
|
||||
suspend fun updateAlbum(album: Album): Result<Unit>
|
||||
|
||||
/**
|
||||
* Delete album
|
||||
*/
|
||||
suspend fun deleteAlbum(albumId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Update album name
|
||||
*/
|
||||
suspend fun updateAlbumName(albumId: String, name: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Update album cover
|
||||
*/
|
||||
suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result<Unit>
|
||||
|
||||
/**
|
||||
* Add wallpapers to album
|
||||
*/
|
||||
suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>
|
||||
): Result<Unit>
|
||||
|
||||
/**
|
||||
* Add folder to album
|
||||
*/
|
||||
suspend fun addFolderToAlbum(albumId: String, folder: Folder): Result<Unit>
|
||||
|
||||
/**
|
||||
* Update folder
|
||||
*/
|
||||
suspend fun updateFolder(folder: Folder): Result<Unit>
|
||||
|
||||
/**
|
||||
* Remove wallpaper from album
|
||||
*/
|
||||
suspend fun removeWallpaperFromAlbum(albumId: String, wallpaperId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Remove multiple wallpapers from album (batch operation)
|
||||
* Updates album modified time and refreshes cover art
|
||||
*/
|
||||
suspend fun removeWallpapersFromAlbum(albumId: String, wallpaperIds: List<String>): Result<Unit>
|
||||
|
||||
/**
|
||||
* Remove folder from album
|
||||
*/
|
||||
suspend fun removeFolderFromAlbum(albumId: String, folderId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Get album count
|
||||
*/
|
||||
suspend fun getAlbumCount(): Int
|
||||
|
||||
/**
|
||||
* Delete all albums
|
||||
*/
|
||||
suspend fun deleteAllAlbums(): Result<Unit>
|
||||
|
||||
/**
|
||||
* Validate folder URIs and remove invalid ones
|
||||
* Returns number of folders removed
|
||||
*/
|
||||
suspend fun validateAndRemoveInvalidFolders(albumId: String): Result<Int>
|
||||
|
||||
/**
|
||||
* Refresh album cover art based on current wallpapers
|
||||
*/
|
||||
suspend fun refreshAlbumCover(albumId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Refresh all folder covers in an album based on their current wallpapers
|
||||
*/
|
||||
suspend fun refreshFolderCovers(albumId: String): Result<Unit>
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.anthonyla.paperize.domain.repository
|
||||
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Repository interface for Settings operations
|
||||
*/
|
||||
interface SettingsRepository {
|
||||
/**
|
||||
* Get app settings
|
||||
*/
|
||||
suspend fun getAppSettings(): AppSettings
|
||||
|
||||
/**
|
||||
* Get app settings as Flow
|
||||
*/
|
||||
fun getAppSettingsFlow(): Flow<AppSettings>
|
||||
|
||||
/**
|
||||
* Update app settings
|
||||
*/
|
||||
suspend fun updateAppSettings(settings: AppSettings)
|
||||
|
||||
/**
|
||||
* Get schedule settings
|
||||
*/
|
||||
suspend fun getScheduleSettings(): ScheduleSettings
|
||||
|
||||
/**
|
||||
* Get schedule settings as Flow
|
||||
*/
|
||||
fun getScheduleSettingsFlow(): Flow<ScheduleSettings>
|
||||
|
||||
/**
|
||||
* Update schedule settings
|
||||
*/
|
||||
suspend fun updateScheduleSettings(settings: ScheduleSettings)
|
||||
|
||||
/**
|
||||
* Clear all settings
|
||||
*/
|
||||
suspend fun clearAllSettings()
|
||||
|
||||
/**
|
||||
* Atomically update home album ID to prevent race conditions
|
||||
* Use this instead of updateScheduleSettings when only changing home album
|
||||
*/
|
||||
suspend fun updateHomeAlbumId(albumId: String?)
|
||||
|
||||
/**
|
||||
* Atomically update lock album ID to prevent race conditions
|
||||
* Use this instead of updateScheduleSettings when only changing lock album
|
||||
*/
|
||||
suspend fun updateLockAlbumId(albumId: String?)
|
||||
|
||||
/**
|
||||
* Atomically clear album selections if they match the given album ID
|
||||
* Used when deleting an album to prevent race conditions
|
||||
* Returns true if any selections were cleared
|
||||
*/
|
||||
suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean
|
||||
|
||||
// ============ 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)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.anthonyla.paperize.domain.repository
|
||||
|
||||
import android.net.Uri
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Repository interface for Wallpaper operations
|
||||
*/
|
||||
interface WallpaperRepository {
|
||||
/**
|
||||
* Get wallpapers for an album
|
||||
*/
|
||||
fun getWallpapersByAlbum(albumId: String): Flow<List<Wallpaper>>
|
||||
|
||||
/**
|
||||
* Get direct wallpapers for an album (not from folders)
|
||||
*/
|
||||
fun getDirectWallpapersByAlbum(albumId: String): Flow<List<Wallpaper>>
|
||||
|
||||
/**
|
||||
* Get wallpapers for a folder
|
||||
*/
|
||||
fun getWallpapersByFolder(folderId: String): Flow<List<Wallpaper>>
|
||||
|
||||
/**
|
||||
* Get wallpaper by ID
|
||||
*/
|
||||
suspend fun getWallpaperById(wallpaperId: String): Wallpaper?
|
||||
|
||||
/**
|
||||
* Add wallpaper
|
||||
*/
|
||||
suspend fun addWallpaper(wallpaper: Wallpaper): Result<Unit>
|
||||
|
||||
/**
|
||||
* Update wallpaper
|
||||
*/
|
||||
suspend fun updateWallpaper(wallpaper: Wallpaper): Result<Unit>
|
||||
|
||||
/**
|
||||
* Delete wallpaper
|
||||
*/
|
||||
suspend fun deleteWallpaper(wallpaperId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Delete multiple wallpapers by IDs (batch operation)
|
||||
*/
|
||||
suspend fun deleteWallpapers(wallpaperIds: List<String>): Result<Unit>
|
||||
|
||||
/**
|
||||
* Delete all wallpapers in a folder
|
||||
*/
|
||||
suspend fun deleteWallpapersByFolderId(folderId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Update wallpaper order
|
||||
*/
|
||||
suspend fun updateWallpaperOrder(wallpaperId: String, order: Int): Result<Unit>
|
||||
|
||||
/**
|
||||
* Validate wallpaper URIs and remove invalid ones
|
||||
*/
|
||||
suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result<Int>
|
||||
|
||||
/**
|
||||
* Get next wallpaper in queue
|
||||
*/
|
||||
suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
/**
|
||||
* Atomically get and remove next wallpaper from queue
|
||||
* Prevents race conditions when multiple wallpaper changes happen simultaneously
|
||||
*/
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
/**
|
||||
* Build wallpaper queue for album
|
||||
*/
|
||||
suspend fun buildWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
shuffle: Boolean = false
|
||||
): Result<Unit>
|
||||
|
||||
/**
|
||||
* Dequeue wallpaper (remove first from queue)
|
||||
*/
|
||||
suspend fun dequeueWallpaper(albumId: String, screenType: ScreenType): Result<Unit>
|
||||
|
||||
/**
|
||||
* Clear all queues for all albums
|
||||
* Used when shuffle setting changes to force rebuild with new mode
|
||||
*/
|
||||
suspend fun clearAllQueues(): Result<Unit>
|
||||
|
||||
/**
|
||||
* Normalize queue positions for all queues (HOME and LOCK) of an album
|
||||
* Fixes gaps in queue positions caused by CASCADE deletes when wallpapers are removed
|
||||
* Ensures positions are sequential (0, 1, 2, ...) without gaps
|
||||
*/
|
||||
suspend fun normalizeAllQueuesForAlbum(albumId: String): Result<Unit>
|
||||
|
||||
/**
|
||||
* Scan folder for wallpapers
|
||||
*/
|
||||
suspend fun scanFolderForWallpapers(folderUri: Uri): Result<List<Wallpaper>>
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
|
||||
import com.anthonyla.paperize.core.util.getDeviceScreenSize
|
||||
import com.anthonyla.paperize.core.util.isValid
|
||||
import com.anthonyla.paperize.core.util.processBitmap
|
||||
import com.anthonyla.paperize.core.util.retrieveBitmap
|
||||
import com.anthonyla.paperize.core.util.scaleBitmap
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
// Constants
|
||||
private const val MAX_VALIDATION_RETRIES = 10
|
||||
|
||||
/**
|
||||
* Use case to change wallpaper
|
||||
*
|
||||
* Handles the complete wallpaper changing flow:
|
||||
* 1. Atomically get and dequeue next wallpaper from queue
|
||||
* 2. Validate URI
|
||||
* 3. Load and process bitmap
|
||||
* 4. Apply effects
|
||||
* 5. Refill queue if needed
|
||||
*/
|
||||
class ChangeWallpaperUseCase @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val settingsRepository: SettingsRepository
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String, screenType: ScreenType): Result<Bitmap> {
|
||||
return try {
|
||||
// Get settings first - needed for queue building
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
|
||||
// Check if queue exists, build it if empty
|
||||
val queueCheck = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
|
||||
if (queueCheck == null) {
|
||||
// Queue is empty, build it first
|
||||
val buildResult = wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
if (buildResult is Result.Error) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_failed_to_build_queue)))
|
||||
}
|
||||
}
|
||||
|
||||
// Atomically get and dequeue wallpaper, skipping invalid ones
|
||||
// This prevents race conditions when multiple wallpaper changes happen simultaneously
|
||||
var wallpaper: Wallpaper? = null
|
||||
var maxRetries = MAX_VALIDATION_RETRIES // Prevent infinite loop
|
||||
|
||||
while (wallpaper == null && maxRetries > 0) {
|
||||
// Atomically get and remove from queue in a single transaction
|
||||
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
|
||||
|
||||
// If still null after building queue, no wallpapers exist in album
|
||||
if (candidate == null) {
|
||||
return Result.Error(Exception(context.getString(R.string.no_wallpapers_in_album)))
|
||||
}
|
||||
|
||||
// Validate URI
|
||||
val uri = candidate.uri.toUri()
|
||||
if (uri.isValid(context.contentResolver)) {
|
||||
wallpaper = candidate
|
||||
} else {
|
||||
// Remove invalid wallpaper entity (already dequeued)
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
maxRetries--
|
||||
}
|
||||
}
|
||||
|
||||
if (wallpaper == null) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
}
|
||||
|
||||
val uri = wallpaper.uri.toUri()
|
||||
|
||||
// Get effects and scaling from settings
|
||||
val effects = if (screenType == ScreenType.HOME || screenType == ScreenType.BOTH) {
|
||||
settings.homeEffects
|
||||
} else {
|
||||
settings.lockEffects
|
||||
}
|
||||
val scaling = if (screenType == ScreenType.HOME || screenType == ScreenType.BOTH) {
|
||||
settings.homeScalingType
|
||||
} else {
|
||||
settings.lockScalingType
|
||||
}
|
||||
|
||||
// Get screen dimensions
|
||||
val screenSize = getDeviceScreenSize(context)
|
||||
|
||||
// Load bitmap
|
||||
val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling)
|
||||
?: return Result.Error(Exception(context.getString(R.string.error_failed_to_load_bitmap)))
|
||||
|
||||
// Apply scaling
|
||||
val scaledBitmap = scaleBitmap(bitmap, screenSize.width, screenSize.height, scaling)
|
||||
// Recycle original bitmap if scaling created a new one
|
||||
if (scaledBitmap !== bitmap) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
|
||||
// Apply effects with proper enable flags
|
||||
var processedBitmap = processBitmap(
|
||||
context = context,
|
||||
source = scaledBitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
enableBlur = effects.enableBlur,
|
||||
blurPercent = effects.blurPercentage,
|
||||
enableVignette = effects.enableVignette,
|
||||
vignettePercent = effects.vignettePercentage,
|
||||
enableGrayscale = effects.enableGrayscale,
|
||||
grayscalePercent = if (effects.enableGrayscale) 100 else 0
|
||||
)
|
||||
|
||||
// Recycle scaled bitmap if effects created a new one
|
||||
if (processedBitmap !== scaledBitmap) {
|
||||
scaledBitmap.recycle()
|
||||
}
|
||||
|
||||
// Apply adaptive brightness if enabled
|
||||
if (settings.adaptiveBrightness) {
|
||||
val previousBitmap = processedBitmap
|
||||
processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
|
||||
// Recycle previous if adaptive brightness created a new bitmap
|
||||
if (processedBitmap !== previousBitmap) {
|
||||
previousBitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
// Check if queue needs refilling (wallpaper was already dequeued atomically)
|
||||
val queueSize = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
|
||||
if (queueSize == null) {
|
||||
// Queue is now empty, rebuild it
|
||||
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
}
|
||||
|
||||
Result.Success(processedBitmap)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Use case to create a new album
|
||||
*/
|
||||
class CreateAlbumUseCase @Inject constructor(
|
||||
private val albumRepository: AlbumRepository
|
||||
) {
|
||||
suspend operator fun invoke(name: String, coverUri: String? = null): Result<Album> {
|
||||
if (name.isBlank()) {
|
||||
return Result.Error(IllegalArgumentException("Album name cannot be empty"))
|
||||
}
|
||||
return albumRepository.createAlbum(name, coverUri)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Use case to delete an album
|
||||
*/
|
||||
class DeleteAlbumUseCase @Inject constructor(
|
||||
private val albumRepository: AlbumRepository
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String): Result<Unit> {
|
||||
return albumRepository.deleteAlbum(albumId)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Use case to get all albums
|
||||
*/
|
||||
class GetAlbumsUseCase @Inject constructor(
|
||||
private val albumRepository: AlbumRepository
|
||||
) {
|
||||
operator fun invoke(): Flow<List<Album>> = albumRepository.getAllAlbums()
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Use case to refresh album wallpapers and folders
|
||||
*
|
||||
* Validates all wallpaper URIs and folder URIs, removes invalid ones
|
||||
* Normalizes wallpaper queues after deletions to maintain queue integrity
|
||||
* Returns total number of items removed (wallpapers + folders)
|
||||
*/
|
||||
class RefreshAlbumUseCase @Inject constructor(
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val albumRepository: AlbumRepository
|
||||
) {
|
||||
suspend operator fun invoke(albumId: String): Result<Int> {
|
||||
var totalRemoved = 0
|
||||
|
||||
// Validate and remove invalid folders
|
||||
val foldersResult = albumRepository.validateAndRemoveInvalidFolders(albumId)
|
||||
if (foldersResult is Result.Success) {
|
||||
totalRemoved += foldersResult.data
|
||||
}
|
||||
|
||||
// Validate and remove invalid wallpapers
|
||||
val wallpapersResult = wallpaperRepository.validateAndRemoveInvalidWallpapers(albumId)
|
||||
if (wallpapersResult is Result.Success) {
|
||||
totalRemoved += wallpapersResult.data
|
||||
}
|
||||
|
||||
// If wallpapers were removed, normalize queue positions to fix gaps from CASCADE deletes
|
||||
if (totalRemoved > 0) {
|
||||
// Refresh album cover after validation (in case cover wallpaper was removed)
|
||||
albumRepository.refreshAlbumCover(albumId)
|
||||
|
||||
// Normalize both HOME and LOCK queues to fix position gaps
|
||||
// CASCADE deletes may leave gaps in queue positions (e.g., 0, 2, 4 instead of 0, 1, 2)
|
||||
wallpaperRepository.normalizeAllQueuesForAlbum(albumId)
|
||||
}
|
||||
|
||||
// Return error if either operation failed
|
||||
return when {
|
||||
foldersResult is Result.Error -> foldersResult
|
||||
wallpapersResult is Result.Error -> wallpapersResult
|
||||
else -> Result.Success(totalRemoved)
|
||||
}
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.app_shortcut
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
|
||||
|
||||
class BroadcastActivity : Activity() {
|
||||
companion object {
|
||||
const val ACTION_CUSTOM_BROADCAST = "com.anthonyla.paperize.SHORTCUT"
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val intent = Intent(ACTION_CUSTOM_BROADCAST).apply {
|
||||
setClass(this@BroadcastActivity, WallpaperBootAndChangeReceiver::class.java)
|
||||
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
|
||||
}
|
||||
sendBroadcast(intent)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
-94
@@ -1,94 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data access object for AlbumWithWallpaperAndFolder which is used for application's list of user albums
|
||||
*/
|
||||
@Dao
|
||||
interface AlbumDao {
|
||||
@Transaction
|
||||
@Query("SELECT * FROM album")
|
||||
fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>>
|
||||
|
||||
@Transaction
|
||||
@Query("SELECT * FROM album WHERE selected = 1")
|
||||
fun getSelectedAlbums(): Flow<List<AlbumWithWallpaperAndFolder>>
|
||||
|
||||
@Query("UPDATE album SET selected = :selected WHERE initialAlbumName = :albumName")
|
||||
suspend fun updateAlbumSelection(albumName: String, selected: Boolean)
|
||||
|
||||
@Query("UPDATE album SET selected = 0")
|
||||
suspend fun deselectAllAlbums()
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertAlbum(album: Album)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertFolder(folder: Folder)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertFolderList(folders: List<Folder>)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteAlbum(album: Album)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteFolder(folder: Folder)
|
||||
@Delete
|
||||
suspend fun deleteWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
@Delete
|
||||
suspend fun deleteFolderList(folders: List<Folder>)
|
||||
|
||||
@Query("DELETE FROM wallpaper WHERE initialAlbumName=:initialAlbumName")
|
||||
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
|
||||
|
||||
@Query("DELETE FROM folder WHERE initialAlbumName=:initialAlbumName")
|
||||
suspend fun cascadeDeleteFolder(initialAlbumName: String)
|
||||
|
||||
@Update
|
||||
suspend fun updateAlbum(album: Album)
|
||||
|
||||
@Update
|
||||
suspend fun updateWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
@Update
|
||||
suspend fun updateFolder(folder: Folder)
|
||||
|
||||
@Query("DELETE FROM album")
|
||||
suspend fun deleteAllAlbums()
|
||||
|
||||
@Query("DELETE FROM wallpaper")
|
||||
suspend fun deleteAllWallpapers()
|
||||
|
||||
@Query("DELETE FROM folder")
|
||||
suspend fun deleteAllFolders()
|
||||
|
||||
@Transaction
|
||||
suspend fun deleteAllData() {
|
||||
deleteAllWallpapers()
|
||||
deleteAllFolders()
|
||||
deleteAllAlbums()
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Database for storing albums, wallpapers, and folders
|
||||
* Stores [Album], [Wallpaper], and [Folder] inside AlbumWithWallpaperAndFolder
|
||||
*/
|
||||
@Database(
|
||||
entities = [Album::class, Wallpaper::class, Folder::class],
|
||||
version = 12
|
||||
)
|
||||
@TypeConverters(Converters::class)
|
||||
abstract class AlbumDatabase: RoomDatabase() {
|
||||
abstract val albumDao: AlbumDao
|
||||
companion object {
|
||||
const val DATABASE_NAME = "paperize_album_db"
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.data_source
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
|
||||
/**
|
||||
* Converters for Room database to convert list of strings to json string and vice versa
|
||||
*/
|
||||
class Converters {
|
||||
private val gson = Gson()
|
||||
|
||||
/**
|
||||
* Convert list of strings to json string
|
||||
*/
|
||||
@TypeConverter
|
||||
fun listToJsonString(value: List<String>?): String = gson.toJson(value)
|
||||
|
||||
/**
|
||||
* Convert json string to list of strings
|
||||
*/
|
||||
@TypeConverter
|
||||
fun jsonStringToList(value: String?): List<String> {
|
||||
if (value == null) return emptyList()
|
||||
return gson.fromJson(value, Array<String>::class.java).toList()
|
||||
}
|
||||
|
||||
@TypeConverter
|
||||
fun fromWallpaperList(value: List<Wallpaper>): String? = gson.toJson(value)
|
||||
|
||||
@TypeConverter
|
||||
fun toWallpaperList(value: String?): List<Wallpaper> {
|
||||
if (value == null) return emptyList()
|
||||
val listType = object : TypeToken<List<Wallpaper>>() {}.type
|
||||
return gson.fromJson(value, listType)
|
||||
}
|
||||
}
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.data.repository
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.data.data_source.AlbumDao
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class AlbumRepositoryImpl(
|
||||
private val dao: AlbumDao,
|
||||
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
|
||||
): AlbumRepository {
|
||||
override fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>> {
|
||||
return dao.getAlbumsWithWallpaperAndFolder().map { albumWithWallpaperAndFolderList ->
|
||||
albumWithWallpaperAndFolderList.map {
|
||||
it.copy(
|
||||
wallpapers = it.sortedWallpapers,
|
||||
folders = it.sortedFolders,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun getSelectedAlbums(): Flow<List<AlbumWithWallpaperAndFolder>> {
|
||||
return dao.getSelectedAlbums().map { albumWithWallpaperAndFolderList ->
|
||||
albumWithWallpaperAndFolderList.map {
|
||||
it.copy(
|
||||
wallpapers = it.sortedWallpapers,
|
||||
folders = it.sortedFolders,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder) {
|
||||
withContext(dispatcher) {
|
||||
dao.upsertAlbum(albumWithWallpaperAndFolder.album)
|
||||
dao.upsertWallpaperList(albumWithWallpaperAndFolder.wallpapers)
|
||||
dao.upsertFolderList(albumWithWallpaperAndFolder.folders)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateAlbumSelection(albumName: String, selected: Boolean) {
|
||||
withContext(dispatcher) {
|
||||
dao.updateAlbumSelection(albumName, selected)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deselectAllAlbums() {
|
||||
withContext(dispatcher) {
|
||||
dao.deselectAllAlbums()
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun upsertAlbum(album: Album) {
|
||||
withContext(dispatcher) {
|
||||
dao.upsertAlbum(album)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun upsertWallpaper(wallpaper: Wallpaper) {
|
||||
withContext(dispatcher) {
|
||||
dao.upsertWallpaper(wallpaper)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun upsertFolder(folder: Folder) {
|
||||
withContext(dispatcher) {
|
||||
dao.upsertFolder(folder)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun upsertFolderList(folders: List<Folder>) {
|
||||
withContext(dispatcher) {
|
||||
dao.upsertFolderList(folders)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>) {
|
||||
withContext(dispatcher) {
|
||||
dao.upsertWallpaperList(wallpapers)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteAlbum(album: Album) {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteAlbum(album)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaper(wallpaper: Wallpaper) {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteWallpaper(wallpaper)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteFolder(folder: Folder) {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteFolder(folder)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateAlbum(album: Album) {
|
||||
withContext(dispatcher) {
|
||||
dao.updateAlbum(album)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateFolder(folder: Folder) {
|
||||
withContext(dispatcher) {
|
||||
dao.updateFolder(folder)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateWallpaper(wallpaper: Wallpaper) {
|
||||
withContext(dispatcher) {
|
||||
dao.updateWallpaper(wallpaper)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteAlbum(album: Album) {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteAlbum(album)
|
||||
dao.cascadeDeleteWallpaper(album.initialAlbumName)
|
||||
dao.cascadeDeleteFolder(album.initialAlbumName)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteFolder(initialAlbumName: String) {
|
||||
withContext(dispatcher) {
|
||||
dao.cascadeDeleteFolder(initialAlbumName)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun cascadeDeleteWallpaper(initialAlbumName: String) {
|
||||
withContext(dispatcher) {
|
||||
dao.cascadeDeleteWallpaper(initialAlbumName)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteFolderList(folders: List<Folder>) {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteFolderList(folders)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaperList(wallpapers: List<Wallpaper>) {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteWallpaperList(wallpapers)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteAllData() {
|
||||
withContext(dispatcher) {
|
||||
dao.deleteAllData()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Album model
|
||||
*
|
||||
* @param initialAlbumName The initial album name -- should not be changed as it is used as the key for database queries
|
||||
* @param displayedAlbumName The displayed album name
|
||||
* @param coverUri The cover uri of the album
|
||||
* @param homeWallpapersInQueue The list of home wallpapers in the queue
|
||||
* @param lockWallpapersInQueue The list of lock wallpapers in the queue
|
||||
* @param selected Whether the album is selected
|
||||
*/
|
||||
@Entity
|
||||
data class Album(
|
||||
@PrimaryKey(autoGenerate = false) val initialAlbumName: String,
|
||||
val displayedAlbumName: String,
|
||||
val coverUri: String?,
|
||||
val homeWallpapersInQueue: List<String> = emptyList(),
|
||||
val lockWallpapersInQueue: List<String> = emptyList(),
|
||||
val selected : Boolean = false
|
||||
)
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
|
||||
/**
|
||||
* Complete data class that represents an album with its wallpapers and folders.
|
||||
* @param album The album.
|
||||
* @param wallpapers The wallpapers.
|
||||
* @param folders The folders.
|
||||
* */
|
||||
data class AlbumWithWallpaperAndFolder(
|
||||
@Embedded val album: Album,
|
||||
@Relation(
|
||||
parentColumn = "initialAlbumName",
|
||||
entityColumn = "initialAlbumName",
|
||||
entity = Wallpaper::class,
|
||||
)
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
@Relation(
|
||||
parentColumn = "initialAlbumName",
|
||||
entityColumn = "initialAlbumName",
|
||||
entity = Folder::class
|
||||
)
|
||||
val folders: List<Folder> = emptyList(),
|
||||
) {
|
||||
val totalWallpapers: List<Wallpaper>
|
||||
get() = folders.flatMap { it.wallpapers } + wallpapers
|
||||
val sortedFolders: List<Folder>
|
||||
get() = folders.map { folder ->
|
||||
folder.copy(wallpapers = folder.wallpapers.sortedBy { it.order })
|
||||
}.sortedBy { it.order }
|
||||
val sortedWallpapers: List<Wallpaper>
|
||||
get() = wallpapers.sortedBy { it.order }
|
||||
val sortedTotalWallpapers: List<Wallpaper>
|
||||
get() = (folders.flatMap { it.wallpapers } + wallpapers).sortedBy { it.order }
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Represents a folder directory containing wallpapers
|
||||
*
|
||||
* @param initialAlbumName The initial album name
|
||||
* @param folderName The folder name
|
||||
* @param folderUri The folder directory URI
|
||||
* @param coverUri The cover URI
|
||||
* @param dateModified The date modified of the folder
|
||||
* @param wallpapers The list of wallpaper URI strings in the folder
|
||||
* @param order The order of the folder
|
||||
*/
|
||||
@Entity
|
||||
data class Folder(
|
||||
val initialAlbumName: String,
|
||||
val folderName: String?,
|
||||
val folderUri: String,
|
||||
val coverUri: String?,
|
||||
val dateModified: Long,
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
val order: Int,
|
||||
@PrimaryKey(autoGenerate = false) val key: Int
|
||||
)
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
data class Metadata(
|
||||
val filename: String,
|
||||
val lastModified: Long
|
||||
)
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.model
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Represents a wallpaper object
|
||||
*
|
||||
* @param initialAlbumName The name of the album the wallpaper belongs to
|
||||
* @param wallpaperUri The URI of the wallpaper
|
||||
* @param fileName The name of the file
|
||||
* @param dateModified The date the wallpaper was last modified
|
||||
*/
|
||||
@Entity
|
||||
data class Wallpaper(
|
||||
val initialAlbumName: String,
|
||||
val wallpaperUri: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val order: Int,
|
||||
@PrimaryKey(autoGenerate = false) val key: Int
|
||||
)
|
||||
-119
@@ -1,119 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.domain.repository
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
interface AlbumRepository {
|
||||
/**
|
||||
* Get all albums with wallpaper and folder
|
||||
*/
|
||||
fun getAlbumsWithWallpaperAndFolder(): Flow<List<AlbumWithWallpaperAndFolder>>
|
||||
|
||||
/**
|
||||
* Get all selected albums with wallpaper and folder
|
||||
*/
|
||||
fun getSelectedAlbums(): Flow<List<AlbumWithWallpaperAndFolder>>
|
||||
|
||||
/**
|
||||
* Update album selection
|
||||
*/
|
||||
suspend fun updateAlbumSelection(albumName: String, selected: Boolean)
|
||||
|
||||
/**
|
||||
* Deselect all albums
|
||||
*/
|
||||
suspend fun deselectAllAlbums()
|
||||
|
||||
/**
|
||||
* Insert or update album with wallpaper and folder
|
||||
*/
|
||||
suspend fun upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder: AlbumWithWallpaperAndFolder)
|
||||
|
||||
/**
|
||||
* Insert or update album and its wallpaper and folder
|
||||
*/
|
||||
suspend fun upsertAlbum(album: Album)
|
||||
|
||||
/**
|
||||
* Delete album and its wallpaper and folder
|
||||
*/
|
||||
suspend fun deleteAlbum(album: Album)
|
||||
|
||||
/**
|
||||
* Update album
|
||||
*/
|
||||
suspend fun updateAlbum(album: Album)
|
||||
|
||||
/**
|
||||
* Cascade delete album and its wallpaper and folder. Proper way to delete an AlbumWithWallpaperAndFolder
|
||||
*/
|
||||
suspend fun cascadeDeleteAlbum(album: Album)
|
||||
|
||||
/**
|
||||
* Insert or update wallpaper
|
||||
*/
|
||||
suspend fun upsertWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
/**
|
||||
* Insert or update wallpaper list in one transaction
|
||||
*/
|
||||
suspend fun upsertWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
/**
|
||||
* Delete wallpaper
|
||||
*/
|
||||
suspend fun deleteWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
/**
|
||||
* Delete wallpaper list in one transaction
|
||||
*/
|
||||
suspend fun deleteWallpaperList(wallpapers: List<Wallpaper>)
|
||||
|
||||
/**
|
||||
* Update wallpaper
|
||||
*/
|
||||
suspend fun updateWallpaper(wallpaper: Wallpaper)
|
||||
|
||||
/**
|
||||
* Cascade delete wallpaper. Proper way to delete a single wallpaper
|
||||
*/
|
||||
suspend fun cascadeDeleteWallpaper(initialAlbumName: String)
|
||||
|
||||
/**
|
||||
* Insert or update folder
|
||||
*/
|
||||
suspend fun upsertFolder(folder: Folder)
|
||||
|
||||
/**
|
||||
* Insert or update folder list in one transaction
|
||||
*/
|
||||
suspend fun upsertFolderList(folders: List<Folder>)
|
||||
|
||||
/**
|
||||
* Delete folder
|
||||
*/
|
||||
suspend fun deleteFolder(folder: Folder)
|
||||
|
||||
/**
|
||||
* Update folder
|
||||
*/
|
||||
suspend fun updateFolder(folder: Folder)
|
||||
|
||||
/**
|
||||
* Cascade delete folder. Proper way to delete a single folder
|
||||
*/
|
||||
suspend fun cascadeDeleteFolder(initialAlbumName: String)
|
||||
|
||||
/**
|
||||
* Delete folder list in one transaction
|
||||
*/
|
||||
suspend fun deleteFolderList(folders: List<Folder>)
|
||||
|
||||
/**
|
||||
* Delete all data in database
|
||||
*/
|
||||
suspend fun deleteAllData()
|
||||
}
|
||||
-54
@@ -1,54 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.glance_widget
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.glance.GlanceId
|
||||
import androidx.glance.GlanceModifier
|
||||
import androidx.glance.Image
|
||||
import androidx.glance.ImageProvider
|
||||
import androidx.glance.action.clickable
|
||||
import androidx.glance.appwidget.GlanceAppWidget
|
||||
import androidx.glance.appwidget.provideContent
|
||||
import androidx.glance.layout.Box
|
||||
import androidx.glance.layout.ContentScale
|
||||
import androidx.glance.layout.fillMaxSize
|
||||
import com.anthonyla.paperize.R
|
||||
import androidx.glance.ColorFilter
|
||||
import androidx.glance.GlanceTheme
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperBootAndChangeReceiver
|
||||
|
||||
class PaperizeWidget : GlanceAppWidget() {
|
||||
override suspend fun provideGlance(context: Context, id: GlanceId) {
|
||||
provideContent {
|
||||
WidgetContent(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WidgetContent(context: Context) {
|
||||
val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.SHORTCUT"
|
||||
Box(
|
||||
modifier = GlanceModifier
|
||||
.fillMaxSize()
|
||||
.clickable(
|
||||
{
|
||||
|
||||
val intent = Intent(ACTION_CHANGE_WALLPAPER).apply {
|
||||
setClass(context, WallpaperBootAndChangeReceiver::class.java)
|
||||
addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
|
||||
}
|
||||
context.sendBroadcast(intent)
|
||||
}
|
||||
)
|
||||
) {
|
||||
Image(
|
||||
provider = ImageProvider(R.drawable.next_wallpaper_icon),
|
||||
contentDescription = "Paperize Widget",
|
||||
modifier = GlanceModifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
colorFilter = ColorFilter.tint(GlanceTheme.colors.primaryContainer)
|
||||
)
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.glance_widget
|
||||
import androidx.glance.appwidget.GlanceAppWidget
|
||||
import androidx.glance.appwidget.GlanceAppWidgetReceiver
|
||||
|
||||
class PaperizeWidgetReceiver : GlanceAppWidgetReceiver() {
|
||||
override val glanceAppWidget: GlanceAppWidget = PaperizeWidget()
|
||||
}
|
||||
-249
@@ -1,249 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation
|
||||
|
||||
import android.Manifest
|
||||
import android.animation.ObjectAnimator
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Color
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.view.View
|
||||
import android.view.animation.AccelerateInterpolator
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.SystemBarStyle
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.activity.viewModels
|
||||
import androidx.annotation.RequiresPermission
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.animation.doOnEnd
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.anthonyla.paperize.core.SettingsConstants
|
||||
import com.anthonyla.paperize.core.Type
|
||||
import com.anthonyla.paperize.data.settings.SettingsDataStore
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.themes.PaperizeTheme
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmSchedulerImpl
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperReceiver
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_service.HomeWallpaperService
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import javax.inject.Inject
|
||||
|
||||
@AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
@Inject lateinit var settingsDataStoreImpl: SettingsDataStore
|
||||
private val settingsViewModel: SettingsViewModel by viewModels()
|
||||
|
||||
// Launcher for SET_WALLPAPER permission
|
||||
private val requestSetWallpaperPermission = registerForActivityResult(
|
||||
ActivityResultContracts.RequestPermission()
|
||||
) { isGranted: Boolean ->
|
||||
if (!isGranted) {
|
||||
// Handle the case where the user denies the permission.
|
||||
// For wallpaper apps, this permission is critical, so denying it
|
||||
// means the app won't function as intended.
|
||||
// Consider showing a dialog explaining why it's needed and
|
||||
// offering to open app settings.
|
||||
}
|
||||
}
|
||||
|
||||
// Launcher for SCHEDULE_EXACT_ALARM permission (Android 12+)
|
||||
private val requestExactAlarmPermission = registerForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) {
|
||||
// No specific action needed on result here, as we just want the permission granted.
|
||||
// The check `am.canScheduleExactAlarms()` will reflect the new state when needed.
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge(
|
||||
statusBarStyle = SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT),
|
||||
navigationBarStyle = SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT)
|
||||
)
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
// Request SET_WALLPAPER permission immediately if not granted
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SET_WALLPAPER) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestSetWallpaperPermission.launch(Manifest.permission.SET_WALLPAPER)
|
||||
}
|
||||
|
||||
// Trigger a refresh of wallpapers when the app is opened.
|
||||
val refreshIntent = Intent(this, HomeWallpaperService::class.java).apply {
|
||||
action = HomeWallpaperService.Actions.REFRESH.toString()
|
||||
}
|
||||
startForegroundService(refreshIntent)
|
||||
|
||||
val splashScreen = installSplashScreen()
|
||||
|
||||
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
|
||||
splashScreen.setOnExitAnimationListener { splashScreenViewProvider ->
|
||||
val fadeOut = ObjectAnimator.ofFloat(splashScreenViewProvider.view, View.ALPHA, 1f, 0f)
|
||||
fadeOut.interpolator = AccelerateInterpolator()
|
||||
fadeOut.duration = 300L
|
||||
fadeOut.doOnEnd { splashScreenViewProvider.remove() }
|
||||
fadeOut.start()
|
||||
}
|
||||
}
|
||||
splashScreen.setKeepOnScreenCondition { settingsViewModel.setKeepOnScreenCondition }
|
||||
|
||||
setContent {
|
||||
// Request SCHEDULE_EXACT_ALARM permission when the Composable is active.
|
||||
// This will prompt the user to grant the permission if not already granted.
|
||||
LaunchedEffect(Unit) {
|
||||
requestExactAlarmPermissionIfNeeded(this@MainActivity)
|
||||
}
|
||||
|
||||
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
|
||||
val isFirstLaunch = runBlocking { settingsDataStoreImpl.getBoolean(SettingsConstants.FIRST_LAUNCH) } ?: true
|
||||
val scheduler = WallpaperAlarmSchedulerImpl(this, settingsDataStoreImpl)
|
||||
|
||||
var hasScheduleRun by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(settingsState.value) {
|
||||
// Only attempt to schedule once settings are initialized and the scheduling logic hasn't run yet.
|
||||
if (!hasScheduleRun && settingsState.value.initialized) {
|
||||
handleWallpaperScheduling(settingsState.value, scheduler)
|
||||
hasScheduleRun = true
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeTheme(
|
||||
darkMode = settingsState.value.themeSettings.darkMode,
|
||||
amoledMode = settingsState.value.themeSettings.amoledTheme,
|
||||
dynamicTheming = settingsState.value.themeSettings.dynamicTheming
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
tonalElevation = 5.dp
|
||||
) {
|
||||
PaperizeApp(isFirstLaunch, scheduler)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the SCHEDULE_EXACT_ALARM permission if needed on Android 12 (S) and above.
|
||||
* This function should be called from a LaunchedEffect or similar lifecycle-aware scope
|
||||
* within Compose, or directly in onCreate if you prefer.
|
||||
*/
|
||||
private fun requestExactAlarmPermissionIfNeeded(context: Context) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val am = context.getSystemService(ALARM_SERVICE) as AlarmManager
|
||||
if (!am.canScheduleExactAlarms()) {
|
||||
val intent = Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {
|
||||
data = "package:${context.packageName}".toUri()
|
||||
flags = Intent.FLAG_ACTIVITY_NEW_TASK
|
||||
}
|
||||
requestExactAlarmPermission.launch(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private suspend fun handleWallpaperScheduling(
|
||||
settings: SettingsState,
|
||||
scheduler: WallpaperAlarmSchedulerImpl
|
||||
) {
|
||||
val wallpaperSettings = settings.wallpaperSettings
|
||||
val scheduleSettings = settings.scheduleSettings
|
||||
|
||||
// If changer is not enabled, or essential album names are missing, disable changer and return.
|
||||
if (!wallpaperSettings.enableChanger || wallpaperSettings.homeAlbumName.isNullOrEmpty() || wallpaperSettings.lockAlbumName.isNullOrEmpty()) {
|
||||
if (wallpaperSettings.enableChanger) { // Only dispatch event if it was enabled
|
||||
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Check if alarms are already set to avoid redundant scheduling
|
||||
val shouldScheduleAlarm = if (scheduleSettings.scheduleSeparately) {
|
||||
!(isPendingIntentSet(Type.HOME.ordinal) && isPendingIntentSet(Type.LOCK.ordinal))
|
||||
} else {
|
||||
!isPendingIntentSet(Type.SINGLE.ordinal)
|
||||
}
|
||||
|
||||
if (shouldScheduleAlarm) {
|
||||
val canScheduleExactAlarms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
|
||||
alarmManager.canScheduleExactAlarms()
|
||||
} else {
|
||||
true
|
||||
}
|
||||
|
||||
if (canScheduleExactAlarms) {
|
||||
scheduleWallpaperAlarm(settings, scheduler)
|
||||
} else {
|
||||
// Optionally prompt user to grant permission
|
||||
requestExactAlarmPermissionIfNeeded(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@RequiresPermission(Manifest.permission.SCHEDULE_EXACT_ALARM)
|
||||
private suspend fun scheduleWallpaperAlarm(
|
||||
settings: SettingsState,
|
||||
scheduler: WallpaperAlarmSchedulerImpl
|
||||
) {
|
||||
val scheduleSettings = settings.scheduleSettings
|
||||
val wallpaperSettings = settings.wallpaperSettings
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
val am = getSystemService(ALARM_SERVICE) as AlarmManager
|
||||
if (!am.canScheduleExactAlarms()) {
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
scheduler.scheduleWallpaperAlarm(
|
||||
WallpaperAlarmItem(
|
||||
homeInterval = scheduleSettings.homeInterval,
|
||||
lockInterval = scheduleSettings.lockInterval,
|
||||
setLock = wallpaperSettings.setLockWallpaper,
|
||||
setHome = wallpaperSettings.setHomeWallpaper,
|
||||
scheduleSeparately = scheduleSettings.scheduleSeparately,
|
||||
changeStartTime = scheduleSettings.changeStartTime,
|
||||
startTime = scheduleSettings.startTime,
|
||||
),
|
||||
origin = null,
|
||||
changeImmediate = true,
|
||||
cancelImmediate = true,
|
||||
firstLaunch = true,
|
||||
homeNextTime = settingsDataStoreImpl.getString(SettingsConstants.HOME_NEXT_SET_TIME),
|
||||
lockNextTime = settingsDataStoreImpl.getString(SettingsConstants.LOCK_NEXT_SET_TIME)
|
||||
)
|
||||
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
|
||||
}
|
||||
|
||||
private fun isPendingIntentSet(requestCode: Int): Boolean {
|
||||
val intent = Intent(applicationContext, WallpaperReceiver::class.java)
|
||||
val pendingIntent = PendingIntent.getBroadcast(
|
||||
applicationContext,
|
||||
requestCode,
|
||||
intent,
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_NO_CREATE
|
||||
)
|
||||
return pendingIntent != null
|
||||
}
|
||||
}
|
||||
-789
@@ -1,789 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.navigationBarsPadding
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import androidx.navigation.toRoute
|
||||
import com.anthonyla.paperize.data.SendContactIntent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.AlbumsViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.AlbumViewScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.AlbumScreenViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.AlbumViewEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen.FolderEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen.FolderViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen.FolderViewScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.HomeScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.notifications_screen.NotificationScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.privacy_screen.PrivacyScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortViewModel
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortViewScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.startup_screen.StartupScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_view_screen.WallpaperViewScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.AddAlbum
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.AlbumView
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.FolderView
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.Home
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.Notification
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.Privacy
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.Settings
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.SortView
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.Startup
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.WallpaperView
|
||||
import com.anthonyla.paperize.feature.wallpaper.util.navigation.animatedScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmItem
|
||||
import com.anthonyla.paperize.feature.wallpaper.wallpaper_alarmmanager.WallpaperAlarmSchedulerImpl
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PaperizeApp(
|
||||
firstLaunch: Boolean,
|
||||
scheduler : WallpaperAlarmSchedulerImpl,
|
||||
albumsViewModel: AlbumsViewModel = hiltViewModel(),
|
||||
settingsViewModel: SettingsViewModel = hiltViewModel(),
|
||||
albumScreenViewModel: AlbumScreenViewModel = hiltViewModel(),
|
||||
addAlbumViewModel: AddAlbumViewModel = hiltViewModel(),
|
||||
folderViewModel: FolderViewModel = hiltViewModel(),
|
||||
sortViewModel: SortViewModel = hiltViewModel()
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val navController = rememberNavController()
|
||||
val scope = rememberCoroutineScope()
|
||||
var job by remember { mutableStateOf<Job?>(null) }
|
||||
val settingsState = settingsViewModel.state.collectAsStateWithLifecycle()
|
||||
val albumState = albumsViewModel.state.collectAsStateWithLifecycle()
|
||||
val sortState = sortViewModel.state.collectAsStateWithLifecycle()
|
||||
val folderState = folderViewModel.state.collectAsStateWithLifecycle()
|
||||
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = if (firstLaunch) Startup else Home,
|
||||
modifier = Modifier.fillMaxSize().navigationBarsPadding(),
|
||||
) {
|
||||
// Navigate to the startup screen to show the privacy policy and notification screen
|
||||
animatedScreen<Startup>(animate = settingsState.value.themeSettings.animate) {
|
||||
StartupScreen(
|
||||
onAgree = {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetFirstLaunch)
|
||||
}
|
||||
else { navController.navigate(Notification) }
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Navigate to the notification screen to ask for notification permission
|
||||
animatedScreen<Notification>(animate = settingsState.value.themeSettings.animate) {
|
||||
NotificationScreen(
|
||||
onAgree = { settingsViewModel.onEvent(SettingsEvent.SetFirstLaunch) }
|
||||
)
|
||||
}
|
||||
|
||||
// Navigate to the home screen to view all albums and wallpapers
|
||||
animatedScreen<Home>(animate = settingsState.value.themeSettings.animate) {
|
||||
HomeScreen(
|
||||
albums = albumState.value.albumsWithWallpapers,
|
||||
homeSelectedAlbum = albumState.value.selectedAlbum.find { it.album.initialAlbumName == settingsState.value.wallpaperSettings.homeAlbumName },
|
||||
lockSelectedAlbum = albumState.value.selectedAlbum.find { it.album.initialAlbumName == settingsState.value.wallpaperSettings.lockAlbumName },
|
||||
themeSettings = settingsState.value.themeSettings,
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings,
|
||||
scheduleSettings = settingsState.value.scheduleSettings,
|
||||
effectSettings = settingsState.value.effectSettings,
|
||||
onSettingsClick = { navController.navigate(Settings) },
|
||||
onNavigateAddWallpaper = { navController.navigate(AddAlbum(it)) },
|
||||
onViewAlbum = { navController.navigate(AlbumView(it)) },
|
||||
onHomeTimeChange = { timeInMinutes ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetHomeWallpaperInterval(timeInMinutes))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaperAlarm(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
homeInterval = timeInMinutes
|
||||
)
|
||||
),
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onLockTimeChange = { timeInMinutes ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetLockWallpaperInterval(timeInMinutes))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaperAlarm(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
lockInterval = timeInMinutes
|
||||
)
|
||||
),
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onDeselect = { lock, home ->
|
||||
if (albumState.value.selectedAlbum.isNotEmpty()) {
|
||||
val notSameAlbum = settingsState.value.wallpaperSettings.homeAlbumName != settingsState.value.wallpaperSettings.lockAlbumName
|
||||
when {
|
||||
lock && home -> {
|
||||
settingsState.value.wallpaperSettings.lockAlbumName?.let {
|
||||
albumsViewModel.onEvent(AlbumsEvent.RemoveSelectedAlbum(it))
|
||||
}
|
||||
}
|
||||
lock -> {
|
||||
if (notSameAlbum) {
|
||||
settingsState.value.wallpaperSettings.lockAlbumName?.let {
|
||||
albumsViewModel.onEvent(AlbumsEvent.RemoveSelectedAlbum(it))
|
||||
}
|
||||
}
|
||||
}
|
||||
home -> {
|
||||
if (notSameAlbum) {
|
||||
settingsState.value.wallpaperSettings.homeAlbumName?.let {
|
||||
albumsViewModel.onEvent(AlbumsEvent.RemoveSelectedAlbum(it))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
settingsViewModel.onEvent(SettingsEvent.RemoveSelectedAlbumAsType(lock, home))
|
||||
scheduler.cancelWallpaperAlarm()
|
||||
}
|
||||
},
|
||||
onToggleChanger = { enableWallpaperChanger ->
|
||||
if (albumState.value.selectedAlbum.isNotEmpty() && !settingsState.value.wallpaperSettings.homeAlbumName.isNullOrEmpty() && !settingsState.value.wallpaperSettings.lockAlbumName.isNullOrEmpty()) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(enableWallpaperChanger))
|
||||
if (enableWallpaperChanger) {
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
|
||||
enableChanger = true
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context,
|
||||
refreshNextTime = true
|
||||
)
|
||||
}
|
||||
else { scheduler.cancelWallpaperAlarm() }
|
||||
}
|
||||
},
|
||||
onSelectAlbum = { album, lock, home ->
|
||||
val currentSettings = settingsState.value
|
||||
val notSameAlbum = currentSettings.wallpaperSettings.lockAlbumName != currentSettings.wallpaperSettings.homeAlbumName
|
||||
val newLockAlbum = if (lock) album.album.initialAlbumName else null
|
||||
val newHomeAlbum = if (home) album.album.initialAlbumName else null
|
||||
settingsViewModel.onEvent(SettingsEvent.SetAlbum(
|
||||
homeAlbumName = newHomeAlbum,
|
||||
lockAlbumName = newLockAlbum
|
||||
))
|
||||
albumsViewModel.onEvent(
|
||||
AlbumsEvent.AddSelectedAlbum(
|
||||
album = album,
|
||||
deselectAlbumName = when {
|
||||
notSameAlbum && lock -> currentSettings.wallpaperSettings.lockAlbumName
|
||||
notSameAlbum && home -> currentSettings.wallpaperSettings.homeAlbumName
|
||||
else -> null
|
||||
},
|
||||
shuffle = currentSettings.scheduleSettings.shuffle
|
||||
)
|
||||
)
|
||||
val shouldSchedule =
|
||||
(home && !currentSettings.wallpaperSettings.lockAlbumName.isNullOrEmpty()) ||
|
||||
(lock && !currentSettings.wallpaperSettings.homeAlbumName.isNullOrEmpty()) ||
|
||||
(lock && home)
|
||||
|
||||
if (shouldSchedule) {
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = currentSettings.wallpaperSettings.copy(
|
||||
homeAlbumName = newHomeAlbum ?: currentSettings.wallpaperSettings.homeAlbumName,
|
||||
lockAlbumName = newLockAlbum ?: currentSettings.wallpaperSettings.lockAlbumName
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context,
|
||||
refreshNextTime = true,
|
||||
changeImmediate = true,
|
||||
cancelImmediate = true,
|
||||
firstLaunch = true,
|
||||
delay = 500L
|
||||
)
|
||||
}
|
||||
},
|
||||
onDarkenPercentage = { home, lock ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetDarkenPercentage(home, lock))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.darken) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
lockDarkenPercentage = lock,
|
||||
homeDarkenPercentage = home
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onDarkCheck = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetDarken(it))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
darken = it
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onScalingChange = {
|
||||
if (settingsState.value.wallpaperSettings.wallpaperScaling != it) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetWallpaperScaling(it))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
|
||||
wallpaperScaling = it
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
onHomeCheckedChange = { setHome ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetHome(setHome))
|
||||
if (albumState.value.selectedAlbum.isNotEmpty() && !setHome && !settingsState.value.wallpaperSettings.setLockWallpaper) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
|
||||
albumState.value.selectedAlbum.let { albumsViewModel.onEvent(AlbumsEvent.DeselectSelected) }
|
||||
scheduler.cancelWallpaperAlarm()
|
||||
}
|
||||
else if (albumState.value.selectedAlbum.isNotEmpty() && ((setHome && !settingsState.value.wallpaperSettings.setLockWallpaper) || (!setHome && settingsState.value.wallpaperSettings.setLockWallpaper))) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
|
||||
setHomeWallpaper = setHome
|
||||
),
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
scheduleSeparately = false
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
else if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
|
||||
setHomeWallpaper = setHome
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onLockCheckedChange = { setLock ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetLock(setLock))
|
||||
if (!setLock && !settingsState.value.wallpaperSettings.setHomeWallpaper) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetChangerToggle(false))
|
||||
albumState.value.selectedAlbum.let {
|
||||
albumsViewModel.onEvent(AlbumsEvent.DeselectSelected)
|
||||
}
|
||||
scheduler.cancelWallpaperAlarm()
|
||||
}
|
||||
else if (albumState.value.selectedAlbum.isNotEmpty() && ((setLock && !settingsState.value.wallpaperSettings.setHomeWallpaper) || (!setLock && settingsState.value.wallpaperSettings.setHomeWallpaper))) {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(false))
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
|
||||
setLockWallpaper = setLock
|
||||
),
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
scheduleSeparately = false
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
else if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
wallpaperSettings = settingsState.value.wallpaperSettings.copy(
|
||||
setLockWallpaper = setLock
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onScheduleSeparatelyChange = { changeSeparately ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetScheduleSeparately(changeSeparately))
|
||||
if (albumState.value.selectedAlbum.isNotEmpty() && settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.scheduleWallpaperUpdate(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
scheduleSeparately = changeSeparately
|
||||
)
|
||||
),
|
||||
settingsViewModel = settingsViewModel,
|
||||
scheduler = scheduler,
|
||||
context = context,
|
||||
changeImmediate = true,
|
||||
cancelImmediate = true,
|
||||
firstLaunch = true
|
||||
)
|
||||
}
|
||||
},
|
||||
onBlurChange = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetBlur(it))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
blur = it
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onBlurPercentageChange = { home, lock ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetBlurPercentage(home, lock))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.blur) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
lockBlurPercentage = lock,
|
||||
homeBlurPercentage = home
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onVignetteChange = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetVignette(it))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
vignette = it
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onVignettePercentageChange = { home, lock ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetVignettePercentage(home, lock))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.vignette) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
lockVignettePercentage = lock,
|
||||
homeVignettePercentage = home
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onGrayscaleChange = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetGrayscale(it))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
grayscale = it
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onGrayscalePercentageChange = { home, lock ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetGrayscalePercentage(home, lock))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger && settingsState.value.effectSettings.grayscale) {
|
||||
job = scope.updateWallpaper(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
effectSettings = settingsState.value.effectSettings.copy(
|
||||
lockGrayscalePercentage = lock,
|
||||
homeGrayscalePercentage = home
|
||||
)
|
||||
),
|
||||
scheduler = scheduler
|
||||
)
|
||||
}
|
||||
},
|
||||
onStartTimeChange = { time ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetStartTime(time.hour, time.minute))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaperAlarm(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
startTime = Pair(time.hour, time.minute))
|
||||
),
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onChangeStartTimeToggle = { changeStartTime ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetChangeStartTime(changeStartTime))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaperAlarm(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
changeStartTime = changeStartTime
|
||||
)
|
||||
),
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onShuffleCheck = { shuffle ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetShuffle(shuffle))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
job = scope.updateWallpaperAlarm(
|
||||
job = job,
|
||||
settingsState = settingsState.value.copy(
|
||||
scheduleSettings = settingsState.value.scheduleSettings.copy(
|
||||
shuffle = shuffle
|
||||
)
|
||||
),
|
||||
scheduler = scheduler,
|
||||
context = context
|
||||
)
|
||||
}
|
||||
},
|
||||
onRefreshChange = { refresh ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetRefresh(refresh))
|
||||
if (settingsState.value.wallpaperSettings.enableChanger) {
|
||||
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, refresh)
|
||||
}
|
||||
},
|
||||
onSkipLandscapeChange = { skipLandscape ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetSkipLandscape(skipLandscape))
|
||||
},
|
||||
onSkipNonInteractiveChange = {
|
||||
skipNonInteractive ->
|
||||
settingsViewModel.onEvent(SettingsEvent.SetSkipNonInteractive(skipNonInteractive))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Navigate to the add album screen to create a new album and add wallpapers to it
|
||||
animatedScreen<AddAlbum>(animate = settingsState.value.themeSettings.animate) { backStackEntry ->
|
||||
val addAlbum: AddAlbum = backStackEntry.toRoute()
|
||||
AddAlbumScreen(
|
||||
addAlbumViewModel = addAlbumViewModel,
|
||||
initialAlbumName = addAlbum.initialAlbumName,
|
||||
onBackClick = {
|
||||
navController.navigateUp()
|
||||
},
|
||||
onConfirmation = {
|
||||
navController.navigateUp()
|
||||
},
|
||||
onShowWallpaperView = { uri, name ->
|
||||
navController.navigate(WallpaperView(uri, name))
|
||||
},
|
||||
onShowFolderView = { folder ->
|
||||
if (folder.wallpapers.isNotEmpty()) {
|
||||
folderViewModel.onEvent(FolderEvent.LoadFolderView(folder))
|
||||
navController.navigate(FolderView)
|
||||
}
|
||||
},
|
||||
onSortClick = { folders, wallpapers ->
|
||||
if (folders.isNotEmpty() || wallpapers.isNotEmpty()) {
|
||||
sortViewModel.onEvent(SortEvent.LoadSortView(folders, wallpapers))
|
||||
navController.navigate(SortView)
|
||||
}
|
||||
},
|
||||
animate = settingsState.value.themeSettings.animate
|
||||
)
|
||||
}
|
||||
|
||||
// Navigate to wallpaper view screen to view individual wallpapers in full screen
|
||||
animatedScreen<WallpaperView>(animate = settingsState.value.themeSettings.animate) { backStackEntry ->
|
||||
val wallpaperView: WallpaperView = backStackEntry.toRoute()
|
||||
WallpaperViewScreen(
|
||||
wallpaperUri = wallpaperView.wallpaperUri,
|
||||
wallpaperName = wallpaperView.wallpaperName,
|
||||
onBackClick = { navController.navigateUp() },
|
||||
animate = settingsState.value.themeSettings.animate
|
||||
)
|
||||
}
|
||||
|
||||
// Navigate to the folder view screen to view wallpapers in a folder
|
||||
animatedScreen<FolderView>(animate = settingsState.value.themeSettings.animate) {
|
||||
if (folderState.value.folder == null || folderState.value.folder!!.wallpapers.isEmpty()) {
|
||||
navController.navigateUp()
|
||||
}
|
||||
else {
|
||||
FolderViewScreen(
|
||||
folder = folderState.value.folder!!,
|
||||
onBackClick = { navController.navigateUp() },
|
||||
onShowWallpaperView = { uri, name ->
|
||||
navController.navigate(WallpaperView(uri, name))
|
||||
},
|
||||
animate = settingsState.value.themeSettings.animate
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Navigate to sort view screen to sort wallpapers and folders
|
||||
animatedScreen<SortView>(animate = settingsState.value.themeSettings.animate) {
|
||||
if (sortState.value.folders.isEmpty() && sortState.value.wallpapers.isEmpty()) {
|
||||
navController.navigateUp()
|
||||
}
|
||||
else {
|
||||
SortViewScreen(
|
||||
sortViewModel = sortViewModel,
|
||||
onSaveClick = {
|
||||
val previousScreen = navController.previousBackStackEntry?.destination?.route
|
||||
if (previousScreen?.contains(AddAlbum::class.simpleName.toString()) ?: false) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.LoadFoldersAndWallpapers(
|
||||
folders = sortState.value.folders,
|
||||
wallpapers = sortState.value.wallpapers
|
||||
))
|
||||
navController.navigateUp()
|
||||
}
|
||||
else if (previousScreen?.contains(AlbumView::class.simpleName.toString()) ?: false) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.LoadFoldersAndWallpapers(
|
||||
folders = sortState.value.folders,
|
||||
wallpapers = sortState.value.wallpapers
|
||||
))
|
||||
navController.navigateUp()
|
||||
}
|
||||
},
|
||||
onBackClick = { navController.navigateUp() },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Navigate to the album view screen to view folders and wallpapers in an album
|
||||
animatedScreen<AlbumView>(animate = settingsState.value.themeSettings.animate) { backStackEntry ->
|
||||
val albumView: AlbumView = backStackEntry.toRoute()
|
||||
if (albumView.initialAlbumName.isNotEmpty()) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.LoadAlbum(albumView.initialAlbumName))
|
||||
AlbumViewScreen(
|
||||
albumScreenViewModel = albumScreenViewModel ,
|
||||
animate = settingsState.value.themeSettings.animate,
|
||||
onBackClick = { navController.navigateUp() },
|
||||
onShowWallpaperView = { uri, name ->
|
||||
navController.navigate(WallpaperView(uri, name))
|
||||
},
|
||||
onShowFolderView = { folder ->
|
||||
if (folder.wallpapers.isNotEmpty()) {
|
||||
folderViewModel.onEvent(FolderEvent.LoadFolderView(folder))
|
||||
navController.navigate(FolderView)
|
||||
}
|
||||
},
|
||||
onDeleteAlbum = {
|
||||
navController.navigateUp()
|
||||
},
|
||||
onSortClick = { folders, wallpapers ->
|
||||
if (folders.isNotEmpty() || wallpapers.isNotEmpty()) {
|
||||
sortViewModel.onEvent(SortEvent.LoadSortView(folders, wallpapers))
|
||||
navController.navigate(SortView)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
else { navController.navigateUp() }
|
||||
}
|
||||
|
||||
// Navigate to the settings screen to change app settings
|
||||
animatedScreen<Settings>(animate = settingsState.value.themeSettings.animate) {
|
||||
SettingsScreen(
|
||||
themeSettings = settingsState.value.themeSettings,
|
||||
onBackClick = { navController.navigateUp() },
|
||||
onDarkModeClick = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetDarkMode(it))
|
||||
},
|
||||
onAmoledClick = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetAmoledTheme(it))
|
||||
},
|
||||
onDynamicThemingClick = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetDynamicTheming(it))
|
||||
},
|
||||
onAnimateClick = {
|
||||
settingsViewModel.onEvent(SettingsEvent.SetAnimate(it))
|
||||
},
|
||||
onPrivacyClick = {
|
||||
navController.navigate(Privacy)
|
||||
},
|
||||
onContactClick = {
|
||||
SendContactIntent(context)
|
||||
},
|
||||
onResetClick = {
|
||||
settingsViewModel.onEvent(SettingsEvent.Reset)
|
||||
albumsViewModel.onEvent(AlbumsEvent.Reset)
|
||||
albumsViewModel.onEvent(AlbumsEvent.Reset)
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
|
||||
scheduler.cancelWallpaperAlarm()
|
||||
val contentResolver = context.contentResolver
|
||||
val persistedUris = contentResolver.persistedUriPermissions
|
||||
for (permission in persistedUris) {
|
||||
contentResolver.releasePersistableUriPermission(permission.uri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Navigate to the privacy screen to view the privacy policy
|
||||
animatedScreen<Privacy>(animate = settingsState.value.themeSettings.animate) {
|
||||
PrivacyScreen(
|
||||
onBackClick = { navController.navigateUp() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
private fun CoroutineScope.scheduleWallpaperUpdate(
|
||||
job: Job?,
|
||||
settingsState: SettingsState,
|
||||
settingsViewModel: SettingsViewModel,
|
||||
scheduler: WallpaperAlarmSchedulerImpl,
|
||||
context: android.content.Context,
|
||||
refreshNextTime: Boolean = false,
|
||||
changeImmediate: Boolean = true,
|
||||
cancelImmediate: Boolean = true,
|
||||
firstLaunch: Boolean = true,
|
||||
origin: Int? = null,
|
||||
delay: Long = 0L
|
||||
): Job {
|
||||
job?.cancel()
|
||||
return launch {
|
||||
if (delay > 0) delay(delay)
|
||||
if (refreshNextTime) {
|
||||
settingsViewModel.onEvent(SettingsEvent.RefreshNextSetTime)
|
||||
}
|
||||
|
||||
val alarmItem = WallpaperAlarmItem(
|
||||
homeInterval = settingsState.scheduleSettings.homeInterval,
|
||||
lockInterval = settingsState.scheduleSettings.lockInterval,
|
||||
scheduleSeparately = settingsState.scheduleSettings.scheduleSeparately,
|
||||
setHome = settingsState.wallpaperSettings.setHomeWallpaper,
|
||||
setLock = settingsState.wallpaperSettings.setLockWallpaper,
|
||||
changeStartTime = settingsState.scheduleSettings.changeStartTime,
|
||||
startTime = settingsState.scheduleSettings.startTime,
|
||||
shuffle = settingsState.scheduleSettings.shuffle
|
||||
)
|
||||
|
||||
scheduler.scheduleWallpaperAlarm(
|
||||
wallpaperAlarmItem = alarmItem,
|
||||
origin = origin,
|
||||
changeImmediate = changeImmediate,
|
||||
cancelImmediate = cancelImmediate,
|
||||
firstLaunch = firstLaunch
|
||||
)
|
||||
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, settingsState.scheduleSettings.refresh)
|
||||
}
|
||||
}
|
||||
|
||||
private fun CoroutineScope.updateWallpaperAlarm(
|
||||
job: Job?,
|
||||
settingsState: SettingsState,
|
||||
scheduler: WallpaperAlarmSchedulerImpl,
|
||||
context: android.content.Context,
|
||||
firstLaunch: Boolean = true,
|
||||
): Job {
|
||||
job?.cancel()
|
||||
return launch {
|
||||
val alarmItem = WallpaperAlarmItem(
|
||||
homeInterval = settingsState.scheduleSettings.homeInterval,
|
||||
lockInterval = settingsState.scheduleSettings.lockInterval,
|
||||
scheduleSeparately = settingsState.scheduleSettings.scheduleSeparately,
|
||||
setHome = settingsState.wallpaperSettings.setHomeWallpaper,
|
||||
setLock = settingsState.wallpaperSettings.setLockWallpaper,
|
||||
changeStartTime = settingsState.scheduleSettings.changeStartTime,
|
||||
startTime = settingsState.scheduleSettings.startTime,
|
||||
shuffle = settingsState.scheduleSettings.shuffle
|
||||
)
|
||||
|
||||
scheduler.updateWallpaperAlarm(
|
||||
wallpaperAlarmItem = alarmItem,
|
||||
firstLaunch = firstLaunch
|
||||
)
|
||||
WallpaperAlarmSchedulerImpl.scheduleRefresh(context, settingsState.scheduleSettings.refresh)
|
||||
}
|
||||
}
|
||||
|
||||
private fun CoroutineScope.updateWallpaper(
|
||||
job: Job?,
|
||||
settingsState: SettingsState,
|
||||
scheduler: WallpaperAlarmSchedulerImpl,
|
||||
): Job {
|
||||
job?.cancel()
|
||||
return launch {
|
||||
delay(500L)
|
||||
scheduler.updateWallpaper(
|
||||
scheduleSeparately = settingsState.scheduleSettings.scheduleSeparately,
|
||||
setHome = settingsState.wallpaperSettings.setHomeWallpaper,
|
||||
setLock = settingsState.wallpaperSettings.setLockWallpaper,
|
||||
)
|
||||
}
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
|
||||
sealed class AddAlbumEvent {
|
||||
data object Reset: AddAlbumEvent()
|
||||
data object DeleteSelected: AddAlbumEvent()
|
||||
data object SelectAll: AddAlbumEvent()
|
||||
data object DeselectAll: AddAlbumEvent()
|
||||
data class SaveAlbum(
|
||||
val initialAlbumName: String
|
||||
): AddAlbumEvent()
|
||||
data class AddWallpapers(
|
||||
val wallpaperUris: List<String>
|
||||
): AddAlbumEvent()
|
||||
data class AddFolder(
|
||||
val directoryUri: String
|
||||
): AddAlbumEvent()
|
||||
data class SelectWallpaper(
|
||||
val wallpaperUri: String
|
||||
): AddAlbumEvent()
|
||||
data class SelectFolder(
|
||||
val directoryUri: String
|
||||
): AddAlbumEvent()
|
||||
data class DeselectFolder(
|
||||
val directoryUri: String
|
||||
): AddAlbumEvent()
|
||||
data class DeselectWallpaper(
|
||||
val wallpaperUri: String
|
||||
): AddAlbumEvent()
|
||||
data class SetLoading(
|
||||
val isLoading: Boolean
|
||||
): AddAlbumEvent()
|
||||
data class LoadFoldersAndWallpapers(
|
||||
val folders: List<Folder>,
|
||||
val wallpapers: List<Wallpaper>
|
||||
): AddAlbumEvent()
|
||||
}
|
||||
-351
@@ -1,351 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumAnimatedFab
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumSmallTopBar
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.FolderItem
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import my.nanihadesuka.compose.LazyVerticalGridScrollbar
|
||||
import my.nanihadesuka.compose.ScrollbarSettings
|
||||
|
||||
@Composable
|
||||
fun AddAlbumScreen(
|
||||
addAlbumViewModel: AddAlbumViewModel,
|
||||
initialAlbumName: String,
|
||||
onBackClick: () -> Unit,
|
||||
onConfirmation: () -> Unit,
|
||||
onShowWallpaperView: (String, String) -> Unit,
|
||||
onShowFolderView: (Folder) -> Unit,
|
||||
onSortClick: (List<Folder>, List<Wallpaper>) -> Unit,
|
||||
animate: Boolean // This likely controls item animation, similar to AlbumViewScreen
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val addAlbumState by addAlbumViewModel.state.collectAsStateWithLifecycle() // Use by for direct access
|
||||
val lazyListState = rememberLazyGridState()
|
||||
var showSpotlight by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
// Remember scrollbar settings for consistency and performance
|
||||
val colorScheme = MaterialTheme.colorScheme
|
||||
val scrollbarSettings = remember {
|
||||
ScrollbarSettings.Default.copy(
|
||||
thumbUnselectedColor = colorScheme.primary,
|
||||
thumbSelectedColor = colorScheme.primary,
|
||||
thumbShape = RoundedCornerShape(16.dp),
|
||||
scrollbarPadding = 1.dp,
|
||||
)
|
||||
}
|
||||
|
||||
// Remember common modifier for grid items for consistency and responsiveness
|
||||
val commonItemModifier = remember {
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(9f / 16f) // Common aspect ratio for wallpapers/photos
|
||||
}
|
||||
|
||||
BackHandler(
|
||||
enabled = addAlbumState.selectionState.selectedCount > 0,
|
||||
onBack = remember(addAlbumState.isLoading, addAlbumViewModel) { // Remember the lambda
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** Image picker **/
|
||||
val imagePickerLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenMultipleDocuments(),
|
||||
onResult = { uris: List<Uri> ->
|
||||
val selectionLimit = 500
|
||||
if (uris.size > selectionLimit) {
|
||||
// Inform the user that they selected too many files.
|
||||
Toast.makeText(
|
||||
context,
|
||||
"Please select fewer than $selectionLimit images at a time. For bulk imports, use the 'Add Folder' option.",
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
else if (uris.isNotEmpty()) {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
withContext(Dispatchers.Main) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.SetLoading(true))
|
||||
}
|
||||
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
val uriList = uris.mapNotNull { uri ->
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
|
||||
uri.toString()
|
||||
} catch (e: Exception) {
|
||||
Log.e("AddAlbumScreen", "Failed to take persistable URI permission for image: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
if (uriList.isNotEmpty()) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.AddWallpapers(uriList))
|
||||
}
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.SetLoading(false))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** Folder picker **/
|
||||
val folderPickerLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenDocumentTree(),
|
||||
onResult = { uri: Uri? ->
|
||||
scope.launch(Dispatchers.IO) {
|
||||
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
if (uri != null) {
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
|
||||
withContext(Dispatchers.Main) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.AddFolder(uri.toString()))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("AddAlbumScreen", "Failed to take persistable URI permission: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
val onBackClickTopBar = remember(addAlbumViewModel, onBackClick) {
|
||||
{
|
||||
showSpotlight = false
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.Reset)
|
||||
onBackClick()
|
||||
}
|
||||
}
|
||||
|
||||
val onConfirmationClickTopBar = remember(addAlbumState.isLoading, addAlbumViewModel, initialAlbumName, onConfirmation) {
|
||||
{ text: String ->
|
||||
if (!addAlbumState.isLoading) {
|
||||
showSpotlight = false
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.SaveAlbum(text))
|
||||
onConfirmation()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onSelectAllClickTopBar = remember(addAlbumState.isLoading, addAlbumState.selectionState.allSelected, addAlbumViewModel) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
if (!addAlbumState.selectionState.allSelected) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.SelectAll)
|
||||
} else {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onDeleteSelectedTopBar = remember(addAlbumState.isLoading, addAlbumViewModel) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeleteSelected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onSortClickTopBar = remember(addAlbumState.isLoading, addAlbumViewModel, addAlbumState.folders, addAlbumState.wallpapers, onSortClick) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
|
||||
onSortClick(addAlbumState.folders, addAlbumState.wallpapers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AddAlbumSmallTopBar(
|
||||
title = initialAlbumName,
|
||||
allSelected = addAlbumState.selectionState.allSelected,
|
||||
selectedCount = addAlbumState.selectionState.selectedCount,
|
||||
isEmpty = addAlbumState.isEmpty,
|
||||
selectionMode = addAlbumState.selectionState.selectedCount > 0,
|
||||
showSpotlight = showSpotlight,
|
||||
isLoad = addAlbumState.isLoading,
|
||||
onBackClick = onBackClickTopBar,
|
||||
onConfirmationClick = onConfirmationClickTopBar,
|
||||
onSelectAllClick = onSelectAllClickTopBar,
|
||||
onDeleteSelected = onDeleteSelectedTopBar,
|
||||
onSortClick = onSortClickTopBar
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
// Remember FAB callbacks
|
||||
val onImageClickFab = remember(addAlbumViewModel, imagePickerLauncher) {
|
||||
{
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
|
||||
imagePickerLauncher.launch(arrayOf("image/*"))
|
||||
}
|
||||
}
|
||||
val onFolderClickFab = remember(addAlbumViewModel, folderPickerLauncher) {
|
||||
{
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectAll)
|
||||
folderPickerLauncher.launch(null)
|
||||
}
|
||||
}
|
||||
|
||||
AddAlbumAnimatedFab(
|
||||
isLoading = addAlbumState.isLoading,
|
||||
animate = animate,
|
||||
onImageClick = onImageClickFab,
|
||||
onFolderClick = onFolderClickFab
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (addAlbumState.isLoading) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
},
|
||||
content = { paddingValues -> // Use paddingValues from Scaffold
|
||||
LazyVerticalGridScrollbar(
|
||||
state = lazyListState,
|
||||
settings = scrollbarSettings, // Use remembered settings
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues), // Apply Scaffold padding
|
||||
) {
|
||||
LazyVerticalGrid(
|
||||
state = lazyListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
columns = GridCells.Adaptive(150.dp),
|
||||
contentPadding = PaddingValues(4.dp), // Apply padding to grid content
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp), // Use spacedBy for consistent spacing
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp), // Use spacedBy for consistent spacing
|
||||
) {
|
||||
items(
|
||||
items = addAlbumState.folders,
|
||||
key = { folder -> folder.folderUri }
|
||||
) { folder -> // Renamed 'it' to 'folder' for clarity
|
||||
val isSelected = addAlbumState.selectionState.selectedFolders.contains(folder.folderUri)
|
||||
val onFolderItemSelection = remember(folder.folderUri, addAlbumState.isLoading, addAlbumViewModel, isSelected) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
if (!isSelected) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.SelectFolder(folder.folderUri))
|
||||
} else {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectFolder(folder.folderUri))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onFolderViewClickItem = remember(folder, addAlbumState.isLoading, onShowFolderView) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
onShowFolderView(folder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FolderItem(
|
||||
folder = folder,
|
||||
itemSelected = isSelected,
|
||||
selectionMode = addAlbumState.selectionState.selectedCount > 0,
|
||||
onItemSelection = onFolderItemSelection,
|
||||
onFolderViewClick = onFolderViewClickItem,
|
||||
modifier = commonItemModifier // Use common responsive modifier
|
||||
.then(
|
||||
if (animate) Modifier.animateItem( // Add item animation
|
||||
placementSpec = tween(
|
||||
durationMillis = 800,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
) else Modifier
|
||||
)
|
||||
)
|
||||
}
|
||||
items(
|
||||
items = addAlbumState.wallpapers,
|
||||
key = { wallpaper -> wallpaper.wallpaperUri }
|
||||
) { wallpaper -> // Renamed 'it' to 'wallpaper' for clarity
|
||||
val isSelected = addAlbumState.selectionState.selectedWallpapers.contains(wallpaper.wallpaperUri)
|
||||
val onWallpaperItemSelection = remember(wallpaper.wallpaperUri, addAlbumState.isLoading, addAlbumViewModel, isSelected) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
if (!isSelected) {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.SelectWallpaper(wallpaper.wallpaperUri))
|
||||
} else {
|
||||
addAlbumViewModel.onEvent(AddAlbumEvent.DeselectWallpaper(wallpaper.wallpaperUri))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onWallpaperViewClickItem = remember(wallpaper, addAlbumState.isLoading, onShowWallpaperView) {
|
||||
{
|
||||
if (!addAlbumState.isLoading) {
|
||||
onShowWallpaperView(wallpaper.wallpaperUri, wallpaper.fileName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WallpaperItem(
|
||||
wallpaperUri = wallpaper.wallpaperUri,
|
||||
itemSelected = isSelected,
|
||||
selectionMode = addAlbumState.selectionState.selectedCount > 0,
|
||||
onItemSelection = onWallpaperItemSelection,
|
||||
onWallpaperViewClick = onWallpaperViewClickItem,
|
||||
modifier = commonItemModifier // Use common responsive modifier
|
||||
.then(
|
||||
if (animate) Modifier.animateItem( // Add item animation
|
||||
placementSpec = tween(
|
||||
durationMillis = 800,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
) else Modifier
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
|
||||
data class AddAlbumState(
|
||||
val wallpapers: List<Wallpaper> = emptyList(),
|
||||
val folders: List<Folder> = emptyList(),
|
||||
val selectionState: SelectionState = SelectionState(),
|
||||
val isEmpty: Boolean = true,
|
||||
val isLoading: Boolean = false
|
||||
)
|
||||
|
||||
data class SelectionState(
|
||||
val selectedWallpapers: List<String> = emptyList(),
|
||||
val selectedFolders: List<String> = emptyList(),
|
||||
val allSelected: Boolean = false,
|
||||
val selectedCount: Int = 0
|
||||
)
|
||||
-280
@@ -1,280 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.core.compress
|
||||
import com.anthonyla.paperize.core.getFolderMetadata
|
||||
import com.anthonyla.paperize.core.getImageMetadata
|
||||
import com.anthonyla.paperize.core.getWallpaperFromFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class AddAlbumViewModel @Inject constructor(
|
||||
application: Application,
|
||||
private val repository: AlbumRepository,
|
||||
) : AndroidViewModel(application) {
|
||||
private val context: Context
|
||||
get() = getApplication<Application>().applicationContext
|
||||
private val _state = MutableStateFlow(AddAlbumState())
|
||||
val state = _state.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.WhileSubscribed(5000), AddAlbumState()
|
||||
)
|
||||
|
||||
fun onEvent(event: AddAlbumEvent) {
|
||||
when (event) {
|
||||
is AddAlbumEvent.SaveAlbum -> {
|
||||
viewModelScope.launch {
|
||||
if (_state.value.wallpapers.isEmpty() && _state.value.folders.isEmpty()) { return@launch }
|
||||
val wallpapers = _state.value.wallpapers.map {
|
||||
it.copy(
|
||||
initialAlbumName = event.initialAlbumName,
|
||||
key = event.initialAlbumName.hashCode() + it.wallpaperUri.hashCode()
|
||||
)
|
||||
}
|
||||
var totalWallpapers = _state.value.wallpapers.size
|
||||
val folders = _state.value.folders.map { folder ->
|
||||
val updatedWallpapers = folder.wallpapers.map {
|
||||
it.copy(
|
||||
initialAlbumName = event.initialAlbumName,
|
||||
key = event.initialAlbumName.hashCode() + folder.folderUri.hashCode() + it.wallpaperUri.hashCode(),
|
||||
order = it.order + totalWallpapers
|
||||
)
|
||||
}
|
||||
totalWallpapers += folder.wallpapers.size
|
||||
folder.copy(
|
||||
initialAlbumName = event.initialAlbumName,
|
||||
key = event.initialAlbumName.hashCode() + folder.hashCode(),
|
||||
coverUri = updatedWallpapers.firstOrNull()?.wallpaperUri ?: folder.coverUri,
|
||||
wallpapers = updatedWallpapers
|
||||
)
|
||||
}
|
||||
|
||||
val albumWithWallpaperAndFolder = AlbumWithWallpaperAndFolder(
|
||||
album = Album(
|
||||
initialAlbumName = event.initialAlbumName,
|
||||
displayedAlbumName = event.initialAlbumName,
|
||||
coverUri = folders.firstOrNull()?.coverUri ?: wallpapers.firstOrNull()?.wallpaperUri ?: "",
|
||||
homeWallpapersInQueue = emptyList(),
|
||||
lockWallpapersInQueue = emptyList(),
|
||||
selected = false
|
||||
),
|
||||
wallpapers = wallpapers,
|
||||
folders = folders
|
||||
)
|
||||
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
|
||||
_state.update { AddAlbumState() }
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.DeleteSelected -> {
|
||||
viewModelScope.launch {
|
||||
val selectedWallpaperUris = _state.value.selectionState.selectedWallpapers.toSet()
|
||||
val selectedFolderUris = _state.value.selectionState.selectedFolders.toSet()
|
||||
val wallpapersRemoved = _state.value.wallpapers.filter { wallpaper ->
|
||||
wallpaper.wallpaperUri !in selectedWallpaperUris
|
||||
}
|
||||
val foldersRemoved = _state.value.folders.filter { folder ->
|
||||
folder.folderUri !in selectedFolderUris
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
wallpapers = wallpapersRemoved,
|
||||
folders = foldersRemoved,
|
||||
isEmpty = wallpapersRemoved.isEmpty() && foldersRemoved.isEmpty(),
|
||||
selectionState = SelectionState()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.AddWallpapers -> {
|
||||
viewModelScope.launch {
|
||||
val existingWallpapers = _state.value.wallpapers.map { it.wallpaperUri }.toSet()
|
||||
val newWallpapers = event.wallpaperUris.filter { wallpaperUri ->
|
||||
wallpaperUri !in existingWallpapers
|
||||
}
|
||||
val wallpapers = _state.value.wallpapers.plus(
|
||||
newWallpapers.mapIndexed { index, wallpaperUri ->
|
||||
val metadata = getImageMetadata(context, wallpaperUri)
|
||||
Wallpaper(
|
||||
initialAlbumName = "",
|
||||
wallpaperUri = wallpaperUri.compress("content://com.android.externalstorage.documents/"),
|
||||
fileName = metadata.filename,
|
||||
dateModified = metadata.lastModified,
|
||||
order = index + _state.value.wallpapers.size,
|
||||
key = 0
|
||||
)
|
||||
}
|
||||
)
|
||||
_state.update {
|
||||
it.copy(
|
||||
wallpapers = wallpapers,
|
||||
isEmpty = false,
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.AddFolder -> {
|
||||
viewModelScope.launch {
|
||||
if (event.directoryUri in _state.value.folders.map { it.folderUri }) {
|
||||
return@launch
|
||||
}
|
||||
_state.update { it.copy(isLoading = true) }
|
||||
val wallpapers = getWallpaperFromFolder(event.directoryUri, context)
|
||||
val metadata = getFolderMetadata(event.directoryUri, context)
|
||||
val folder = Folder(
|
||||
initialAlbumName = "",
|
||||
folderName = metadata.filename,
|
||||
folderUri = event.directoryUri,
|
||||
wallpapers = wallpapers,
|
||||
coverUri = wallpapers.firstOrNull()?.wallpaperUri ?: "",
|
||||
dateModified = metadata.lastModified,
|
||||
order = if (_state.value.folders.isEmpty()) 0 else _state.value.folders.size,
|
||||
key = 0
|
||||
)
|
||||
_state.update {
|
||||
it.copy(
|
||||
folders = it.folders.plus(folder),
|
||||
isEmpty = false,
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.SelectAll -> {
|
||||
viewModelScope.launch {
|
||||
if (!_state.value.selectionState.allSelected) {
|
||||
_state.update { state ->
|
||||
state.copy(
|
||||
selectionState = SelectionState(
|
||||
selectedFolders = state.folders.map { it.folderUri },
|
||||
selectedWallpapers = state.wallpapers.map { it.wallpaperUri },
|
||||
allSelected = true,
|
||||
selectedCount = state.folders.size + state.wallpapers.size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
is AddAlbumEvent.DeselectAll-> {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(selectionState = SelectionState()) }
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.SelectFolder -> {
|
||||
viewModelScope.launch {
|
||||
val folderUri = (_state.value.folders.find { it.folderUri == event.directoryUri } ?: return@launch).folderUri
|
||||
_state.update {
|
||||
val newSelectedFolders = it.selectionState.selectedFolders.plus(folderUri)
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedFolders = newSelectedFolders,
|
||||
selectedCount = newSelectedFolders.size + it.selectionState.selectedWallpapers.size,
|
||||
allSelected = newSelectedFolders.size + it.selectionState.selectedWallpapers.size >=
|
||||
it.wallpapers.size + it.folders.size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.SelectWallpaper -> {
|
||||
viewModelScope.launch {
|
||||
if (!_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
|
||||
_state.update {
|
||||
val newSelectedWallpapers = it.selectionState.selectedWallpapers.plus(event.wallpaperUri)
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedWallpapers = newSelectedWallpapers,
|
||||
selectedCount = newSelectedWallpapers.size + it.selectionState.selectedFolders.size,
|
||||
allSelected = it.selectionState.selectedFolders.size + newSelectedWallpapers.size >=
|
||||
it.wallpapers.size + it.folders.size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.DeselectFolder -> {
|
||||
viewModelScope.launch {
|
||||
val folderUri = (_state.value.folders.find { it.folderUri == event.directoryUri } ?: return@launch).folderUri
|
||||
_state.update {
|
||||
val newSelectedFolders = it.selectionState.selectedFolders.minus(folderUri)
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedFolders = newSelectedFolders,
|
||||
selectedCount = it.selectionState.selectedCount - 1,
|
||||
allSelected = false
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.DeselectWallpaper -> {
|
||||
viewModelScope.launch {
|
||||
if (_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
|
||||
_state.update {
|
||||
val newSelectedWallpapers = it.selectionState.selectedWallpapers.minus(event.wallpaperUri)
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedWallpapers = newSelectedWallpapers,
|
||||
selectedCount = it.selectionState.selectedCount - 1,
|
||||
allSelected = false
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.LoadFoldersAndWallpapers -> {
|
||||
viewModelScope.launch {
|
||||
_state.update {
|
||||
it.copy(
|
||||
folders = event.folders,
|
||||
wallpapers = event.wallpapers,
|
||||
isEmpty = event.folders.isEmpty() && event.wallpapers.isEmpty(),
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.SetLoading -> {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(isLoading = event.isLoading) }
|
||||
}
|
||||
}
|
||||
|
||||
is AddAlbumEvent.Reset -> {
|
||||
viewModelScope.launch {
|
||||
_state.update { AddAlbumState() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-201
@@ -1,201 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.*
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.PhotoLibrary
|
||||
import androidx.compose.material.icons.filled.Remove
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
@Composable
|
||||
fun AddAlbumAnimatedFab(
|
||||
isLoading: Boolean,
|
||||
animate: Boolean,
|
||||
onImageClick: () -> Unit,
|
||||
onFolderClick: () -> Unit
|
||||
) {
|
||||
val expandedWidth = 165.dp
|
||||
val collapsedFabSize = 96.dp
|
||||
val expandedFabHeight = 60.dp
|
||||
val menuItemHeight = 56.dp
|
||||
val menuItemCount = 2
|
||||
|
||||
val menuColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
|
||||
val fabColor = MaterialTheme.colorScheme.primaryContainer
|
||||
|
||||
var isFabExpanded by remember { mutableStateOf(false) }
|
||||
BackHandler(isFabExpanded) { isFabExpanded = false }
|
||||
|
||||
val transition = updateTransition(targetState = isFabExpanded, label = "fabTransition")
|
||||
|
||||
val fabWidth by transition.animateDp(
|
||||
label = "fabWidth",
|
||||
transitionSpec = {
|
||||
if (animate) {
|
||||
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
|
||||
} else {
|
||||
snap()
|
||||
}
|
||||
}
|
||||
) { expanded ->
|
||||
if (expanded) expandedWidth else collapsedFabSize
|
||||
}
|
||||
|
||||
val fabHeight by transition.animateDp(
|
||||
label = "fabHeight",
|
||||
transitionSpec = {
|
||||
if (animate) {
|
||||
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
|
||||
} else {
|
||||
snap()
|
||||
}
|
||||
}
|
||||
) { expanded ->
|
||||
if (expanded) expandedFabHeight else collapsedFabSize
|
||||
}
|
||||
|
||||
val menuHeight by transition.animateDp(
|
||||
label = "menuHeight",
|
||||
transitionSpec = {
|
||||
if (animate) {
|
||||
spring(dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow)
|
||||
} else {
|
||||
snap()
|
||||
}
|
||||
}
|
||||
) { expanded ->
|
||||
if (expanded) menuItemHeight * menuItemCount else 0.dp
|
||||
}
|
||||
|
||||
val fabIconTransitionSpec: AnimatedContentTransitionScope<Boolean>.() -> ContentTransform = {
|
||||
if (animate) {
|
||||
(scaleIn(tween(100, 300, FastOutSlowInEasing)) + fadeIn(tween(250, 300, LinearEasing)))
|
||||
.togetherWith(fadeOut(tween(10, 0, LinearEasing)))
|
||||
} else {
|
||||
EnterTransition.None.togetherWith(ExitTransition.None)
|
||||
}
|
||||
}
|
||||
|
||||
ElevatedCard(
|
||||
modifier = Modifier.padding(4.dp),
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
elevation = CardDefaults.elevatedCardElevation(4.dp),
|
||||
colors = CardDefaults.elevatedCardColors(
|
||||
containerColor = menuColor
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.height(menuHeight)
|
||||
.width(fabWidth),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceEvenly
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = isFabExpanded,
|
||||
label = stringResource(R.string.add_images_btn),
|
||||
enter = if (animate) fadeIn(tween(300, 150, LinearEasing)) else EnterTransition.None,
|
||||
exit = if (animate) fadeOut(tween(200, 50, LinearEasing)) + scaleOut() else ExitTransition.None
|
||||
) {
|
||||
MenuItemRow(
|
||||
icon = Icons.Filled.PhotoLibrary,
|
||||
text = stringResource(R.string.add_images_btn),
|
||||
onClick = {
|
||||
onImageClick()
|
||||
isFabExpanded = false
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(menuItemHeight)
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = isFabExpanded,
|
||||
label = stringResource(R.string.add_folder_btn),
|
||||
enter = if (animate) fadeIn(tween(300, 150, LinearEasing)) else EnterTransition.None,
|
||||
exit = if (animate) fadeOut(tween(200, 50, LinearEasing)) + scaleOut() else ExitTransition.None
|
||||
) {
|
||||
MenuItemRow(
|
||||
icon = Icons.Filled.Folder,
|
||||
text = stringResource(R.string.add_folder_btn),
|
||||
onClick = {
|
||||
onFolderClick()
|
||||
isFabExpanded = false
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(menuItemHeight)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
LargeFloatingActionButton(
|
||||
onClick = { if (!isLoading) isFabExpanded = !isFabExpanded },
|
||||
modifier = Modifier
|
||||
.width(fabWidth)
|
||||
.height(fabHeight),
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
containerColor = fabColor,
|
||||
elevation = FloatingActionButtonDefaults.elevation(4.dp)
|
||||
) {
|
||||
AnimatedContent(
|
||||
targetState = isFabExpanded,
|
||||
transitionSpec = fabIconTransitionSpec,
|
||||
label = "FabContent"
|
||||
) { expanded ->
|
||||
Icon(
|
||||
imageVector = if (expanded) Icons.Filled.Remove else Icons.Filled.Add,
|
||||
contentDescription = stringResource(R.string.add_wallpaper)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reusable Composable for a single menu item row.
|
||||
*/
|
||||
@Composable
|
||||
private fun MenuItemRow(
|
||||
modifier: Modifier = Modifier,
|
||||
icon: ImageVector,
|
||||
text: String,
|
||||
onClick: () -> Unit
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier.clickable(onClick = onClick),
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = text,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(start = 16.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(16.dp))
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f)
|
||||
)
|
||||
}
|
||||
}
|
||||
-133
@@ -1,133 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.testTagsAsResourceId
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.anthonyla.paperize.R
|
||||
import kotlinx.coroutines.android.awaitFrame
|
||||
|
||||
/**
|
||||
* Dialog for adding a new album.
|
||||
*/
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun AddAlbumDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
onConfirmation: (String) -> Unit
|
||||
) {
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
var albumName by rememberSaveable { mutableStateOf("") }
|
||||
Dialog(
|
||||
onDismissRequest = onDismissRequest,
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp)
|
||||
.semantics {
|
||||
testTagsAsResourceId = true
|
||||
},
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.new_album),
|
||||
modifier = Modifier.padding(20.dp),
|
||||
fontSize = 25.sp
|
||||
)
|
||||
LaunchedEffect(focusRequester) {
|
||||
awaitFrame()
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = albumName,
|
||||
onValueChange = { albumName = it },
|
||||
label = { Text(stringResource(R.string.album_name)) },
|
||||
modifier = Modifier
|
||||
.padding(vertical = 12.dp, horizontal = 32.dp)
|
||||
.focusRequester(focusRequester),
|
||||
singleLine = true,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onDone = {
|
||||
if (albumName.isNotEmpty()) {
|
||||
onConfirmation(albumName)
|
||||
onDismissRequest()
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
TextButton(
|
||||
onClick = { onDismissRequest() },
|
||||
modifier = Modifier.padding(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.cancel),
|
||||
modifier = Modifier.testTag("paperize:cancel_album_button")
|
||||
)
|
||||
}
|
||||
TextButton(
|
||||
modifier = Modifier.padding(8.dp),
|
||||
onClick = {
|
||||
if (albumName.isNotEmpty()) {
|
||||
onConfirmation(albumName)
|
||||
onDismissRequest()
|
||||
}
|
||||
}
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.save),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-224
@@ -1,224 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components
|
||||
|
||||
import android.R.attr.contentDescription
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Sort
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.RadioButtonUnchecked
|
||||
import androidx.compose.material.icons.outlined.Add
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
/**
|
||||
* Top bar for the Add Album screen
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AddAlbumSmallTopBar(
|
||||
title: String,
|
||||
isEmpty: Boolean,
|
||||
allSelected: Boolean,
|
||||
selectedCount: Int,
|
||||
selectionMode: Boolean,
|
||||
showSpotlight: Boolean,
|
||||
isLoad: Boolean,
|
||||
onSelectAllClick: () -> Unit,
|
||||
onBackClick: () -> Unit,
|
||||
onDeleteSelected: () -> Unit,
|
||||
onConfirmationClick: (String) -> Unit,
|
||||
onSortClick: () -> Unit
|
||||
) {
|
||||
val focusManager = LocalFocusManager.current
|
||||
var editableTitle by rememberSaveable { mutableStateOf(title) }
|
||||
var showSelectionDeleteDialog by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
val infiniteTransition = rememberInfiniteTransition(label = stringResource(R.string.spotlight_animation))
|
||||
val radiusValues = listOf(50f, 60f, 75f).map { targetValue ->
|
||||
infiniteTransition.animateFloat(
|
||||
initialValue = 25f,
|
||||
targetValue = targetValue,
|
||||
animationSpec = infiniteRepeatable(
|
||||
animation = tween(2000, easing = LinearOutSlowInEasing),
|
||||
repeatMode = RepeatMode.Reverse
|
||||
),
|
||||
label = "circle_${targetValue}_animation"
|
||||
)
|
||||
}
|
||||
|
||||
if (showSelectionDeleteDialog) {
|
||||
DeleteImagesAlertDialog(
|
||||
onDismissRequest = { showSelectionDeleteDialog = false },
|
||||
onConfirmation = {
|
||||
showSelectionDeleteDialog = false
|
||||
onDeleteSelected()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
TopAppBar(
|
||||
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
|
||||
title = {
|
||||
if (!selectionMode) {
|
||||
TextField(
|
||||
value = editableTitle,
|
||||
onValueChange = { editableTitle = it },
|
||||
placeholder = { Text(stringResource(R.string.enter_the_name_of_the_album)) },
|
||||
singleLine = true,
|
||||
readOnly = isLoad,
|
||||
textStyle = MaterialTheme.typography.titleLarge,
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = Color.Transparent,
|
||||
unfocusedContainerColor = Color.Transparent,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent
|
||||
),
|
||||
isError = editableTitle.isEmpty(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Done
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() })
|
||||
)
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
if (!selectionMode) {
|
||||
IconButton(
|
||||
onClick = onBackClick,
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.requiredSize(24.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(id = R.string.home_screen)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
|
||||
IconButton(onClick = onSelectAllClick) {
|
||||
Icon(
|
||||
imageVector = if (allSelected) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked,
|
||||
contentDescription = stringResource(
|
||||
if (allSelected) R.string.all_images_selected_for_deletion
|
||||
else R.string.select_all_images_for_deletion
|
||||
),
|
||||
modifier = if (allSelected) {
|
||||
Modifier
|
||||
.padding(4.dp)
|
||||
.border(2.dp, bgColor, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(bgColor)
|
||||
} else {
|
||||
Modifier.padding(6.dp)
|
||||
}
|
||||
)
|
||||
}
|
||||
Text(stringResource(R.string.selected, selectedCount))
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (!selectionMode) {
|
||||
if (!isEmpty && editableTitle.isNotEmpty()) {
|
||||
Row {
|
||||
Box {
|
||||
IconButton(onClick = onSortClick) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Default.Sort,
|
||||
contentDescription = stringResource(R.string.sort_items),
|
||||
modifier = Modifier.padding(6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { onConfirmationClick(editableTitle) }) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Add,
|
||||
contentDescription = stringResource(R.string.add_album),
|
||||
modifier = Modifier.padding(6.dp)
|
||||
)
|
||||
}
|
||||
if (!showSpotlight) {
|
||||
val primaryColor = MaterialTheme.colorScheme.inversePrimary
|
||||
val secondaryColor = MaterialTheme.colorScheme.secondary
|
||||
val colors = listOf(primaryColor, secondaryColor, primaryColor)
|
||||
val animationValues = radiusValues.map { it.value }
|
||||
val pairs = animationValues.zip(colors)
|
||||
|
||||
Canvas(modifier = Modifier.matchParentSize()) {
|
||||
pairs.forEach { (radius, color) ->
|
||||
drawCircle(
|
||||
color = color,
|
||||
radius = radius,
|
||||
center = Offset(size.width / 2, size.height / 2),
|
||||
style = Stroke(width = 5f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
IconButton(onClick = { showSelectionDeleteDialog = true }) {
|
||||
Icon(
|
||||
imageVector = if (showSelectionDeleteDialog) Icons.Filled.Delete else Icons.Outlined.Delete,
|
||||
contentDescription = stringResource(R.string.select_all_images_for_deletion),
|
||||
modifier = Modifier.padding(6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
/**
|
||||
* AlertDialog to confirm deletion of images
|
||||
*/
|
||||
@Composable
|
||||
fun DeleteImagesAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
onConfirmation: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
icon = {
|
||||
Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.delete_confirmation))
|
||||
},
|
||||
title = { Text(text = stringResource(R.string.delete_these)) },
|
||||
text = { Text(text = stringResource(R.string.are_you_sure_you_want_to_delete_these_wallpapers)) },
|
||||
onDismissRequest = { onDismissRequest() },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onConfirmation() }) {
|
||||
Text(stringResource(R.string.confirm))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { onDismissRequest() }) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
|
||||
sealed class AlbumsEvent {
|
||||
data object DeselectSelected: AlbumsEvent()
|
||||
data object Reset: AlbumsEvent()
|
||||
data object Refresh: AlbumsEvent()
|
||||
|
||||
data class AddSelectedAlbum(
|
||||
val album: AlbumWithWallpaperAndFolder,
|
||||
val deselectAlbumName: String? = null,
|
||||
val shuffle: Boolean = true
|
||||
): AlbumsEvent()
|
||||
data class RemoveSelectedAlbum(val deselectAlbumName: String): AlbumsEvent()
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
|
||||
data class AlbumsState(
|
||||
val albumsWithWallpapers: List<AlbumWithWallpaperAndFolder> = emptyList(),
|
||||
val selectedAlbum: List<AlbumWithWallpaperAndFolder> = emptyList()
|
||||
)
|
||||
-185
@@ -1,185 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.core.findFirstValidUri
|
||||
import com.anthonyla.paperize.core.getFolderMetadata
|
||||
import com.anthonyla.paperize.core.getWallpaperFromFolder
|
||||
import com.anthonyla.paperize.core.isDirectory
|
||||
import com.anthonyla.paperize.core.isValidUri
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
|
||||
@HiltViewModel
|
||||
class AlbumsViewModel @Inject constructor (
|
||||
application: Application,
|
||||
private val repository: AlbumRepository
|
||||
) : AndroidViewModel(application) {
|
||||
private val context: Context
|
||||
get() = getApplication<Application>().applicationContext
|
||||
|
||||
private val _state = MutableStateFlow<AlbumsState>(AlbumsState())
|
||||
val state = combine(
|
||||
loadAlbumsFlow(),
|
||||
loadSelectedAlbumFlow(),
|
||||
_state
|
||||
) { albums: List<AlbumWithWallpaperAndFolder>, selectedAlbum: List<AlbumWithWallpaperAndFolder>, currentState: AlbumsState ->
|
||||
currentState.copy(
|
||||
albumsWithWallpapers = albums,
|
||||
selectedAlbum = selectedAlbum
|
||||
)
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = AlbumsState()
|
||||
)
|
||||
|
||||
private fun loadAlbumsFlow() = repository.getAlbumsWithWallpaperAndFolder()
|
||||
private fun loadSelectedAlbumFlow() = repository.getSelectedAlbums()
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
state.collect { newState -> _state.value = newState }
|
||||
}
|
||||
}
|
||||
|
||||
fun onEvent(event: AlbumsEvent) {
|
||||
when (event) {
|
||||
is AlbumsEvent.AddSelectedAlbum -> {
|
||||
viewModelScope.launch {
|
||||
event.deselectAlbumName?.let { repository.updateAlbumSelection(it, false) }
|
||||
val homeWallpapers = if (event.shuffle) event.album.totalWallpapers.shuffled().map { it.wallpaperUri }
|
||||
else event.album.sortedTotalWallpapers.map { it.wallpaperUri }
|
||||
val lockWallpapers = if (event.shuffle) event.album.totalWallpapers.shuffled().map { it.wallpaperUri }
|
||||
else event.album.sortedTotalWallpapers.map { it.wallpaperUri }
|
||||
repository.updateAlbum(
|
||||
event.album.album.copy(
|
||||
selected = true,
|
||||
lockWallpapersInQueue = lockWallpapers,
|
||||
homeWallpapersInQueue = homeWallpapers
|
||||
)
|
||||
)
|
||||
|
||||
_state.value.albumsWithWallpapers
|
||||
.filter { it.album.initialAlbumName != event.album.album.initialAlbumName }
|
||||
.forEach { album ->
|
||||
val otherHomeWallpapers = if (event.shuffle) album.totalWallpapers.shuffled().map { it.wallpaperUri }
|
||||
else album.sortedTotalWallpapers.map { it.wallpaperUri }
|
||||
val otherLockWallpapers = if (event.shuffle) album.totalWallpapers.shuffled().map { it.wallpaperUri }
|
||||
else album.sortedTotalWallpapers.map { it.wallpaperUri }
|
||||
repository.updateAlbum(
|
||||
album.album.copy(
|
||||
lockWallpapersInQueue = otherLockWallpapers,
|
||||
homeWallpapersInQueue = otherHomeWallpapers
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumsEvent.RemoveSelectedAlbum -> {
|
||||
viewModelScope.launch {
|
||||
repository.updateAlbumSelection(event.deselectAlbumName, false)
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumsEvent.DeselectSelected -> {
|
||||
viewModelScope.launch {
|
||||
repository.deselectAllAlbums()
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumsEvent.Refresh -> {
|
||||
viewModelScope.launch {
|
||||
updateAlbums()
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumsEvent.Reset -> {
|
||||
viewModelScope.launch {
|
||||
repository.deleteAllData()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateAlbums() {
|
||||
viewModelScope.launch {
|
||||
_state.value.albumsWithWallpapers.forEach { album ->
|
||||
// Remove invalid wallpapers
|
||||
val validWallpapers = async {
|
||||
album.wallpapers
|
||||
.asSequence()
|
||||
.filter { isValidUri(context, it.wallpaperUri) }
|
||||
.mapIndexed { index, wallpaper -> wallpaper.copy(order = index) }
|
||||
.toList()
|
||||
}
|
||||
|
||||
// Remove invalid folders and inner wallpapers
|
||||
val validFolders = async {
|
||||
album.folders
|
||||
.asSequence()
|
||||
.filterNot { isDirectory(context, it.folderUri) }
|
||||
.map { folder ->
|
||||
async {
|
||||
val metadata = getFolderMetadata(folder.folderUri, context)
|
||||
if (metadata.lastModified != folder.dateModified) {
|
||||
val existingWallpapers = folder.wallpapers
|
||||
.asSequence()
|
||||
.filter { isValidUri(context, it.wallpaperUri) }
|
||||
.mapIndexed { index, wallpaper -> wallpaper.copy(order = index) }
|
||||
.toList()
|
||||
val newWallpapers =
|
||||
getWallpaperFromFolder(folder.folderUri, context)
|
||||
.asSequence()
|
||||
.filterNot { new -> existingWallpapers.any { it.wallpaperUri == new.wallpaperUri } }
|
||||
.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(
|
||||
initialAlbumName = album.album.initialAlbumName,
|
||||
order = existingWallpapers.size + 1 + index,
|
||||
key = album.album.initialAlbumName.hashCode() +
|
||||
folder.folderUri.hashCode() +
|
||||
wallpaper.wallpaperUri.hashCode()
|
||||
)
|
||||
}.toList()
|
||||
val combinedWallpapers = existingWallpapers + newWallpapers
|
||||
folder.copy(
|
||||
coverUri = combinedWallpapers.firstOrNull()?.wallpaperUri ?: "",
|
||||
wallpapers = combinedWallpapers,
|
||||
dateModified = metadata.lastModified,
|
||||
folderName = metadata.filename
|
||||
)
|
||||
}
|
||||
else { folder }
|
||||
}
|
||||
}
|
||||
.toList()
|
||||
.awaitAll()
|
||||
}
|
||||
|
||||
val folders = validFolders.await()
|
||||
val wallpapers = validWallpapers.await()
|
||||
val coverUri = findFirstValidUri(context, folders, wallpapers)
|
||||
repository.upsertAlbumWithWallpaperAndFolder(
|
||||
album.copy(
|
||||
album = album.album.copy(coverUri = coverUri),
|
||||
wallpapers = wallpapers,
|
||||
folders = folders
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-99
@@ -1,99 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.core.decompress
|
||||
import com.anthonyla.paperize.core.isValidUri
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Album
|
||||
import com.skydoves.landscapist.ImageOptions
|
||||
import com.skydoves.landscapist.glide.GlideImage
|
||||
|
||||
/**
|
||||
* AlbumItem composable is a single item view for the Album list. Shows the thumbnail cover image.
|
||||
*/
|
||||
@Composable
|
||||
fun AlbumItem(
|
||||
album: Album,
|
||||
onAlbumViewClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val showCoverUri by remember(album.coverUri) {
|
||||
mutableStateOf(!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri))
|
||||
}
|
||||
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
modifier = modifier.fillMaxSize(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
onClick = onAlbumViewClick
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.Start
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(1f)
|
||||
.border(
|
||||
width = 1.dp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.clip(RoundedCornerShape(12.dp)),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
if (showCoverUri) {
|
||||
GlideImage(
|
||||
imageModel = {
|
||||
album.coverUri?.decompress("content://com.android.externalstorage.documents/")?.toUri()
|
||||
},
|
||||
imageOptions = ImageOptions(
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.Center,
|
||||
requestSize = IntSize(300, 300),
|
||||
),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
|
||||
Text(
|
||||
text = album.displayedAlbumName,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
-191
@@ -1,191 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
|
||||
|
||||
import androidx.compose.animation.core.animateDp
|
||||
import androidx.compose.animation.core.updateTransition
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.wrapContentHeight
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.RadioButtonUnchecked
|
||||
import androidx.compose.material.icons.rounded.Block
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.decompress
|
||||
import com.anthonyla.paperize.core.isValidUri
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.skydoves.landscapist.ImageOptions
|
||||
import com.skydoves.landscapist.glide.GlideImage
|
||||
|
||||
/**
|
||||
* FolderItem composable is a single item of the folder list. It shows the folder's cover image,
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun FolderItem(
|
||||
folder: Folder,
|
||||
itemSelected: Boolean,
|
||||
selectionMode: Boolean,
|
||||
onItemSelection: () -> Unit,
|
||||
onFolderViewClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val haptics = LocalHapticFeedback.current
|
||||
val transition = updateTransition(itemSelected, label = "FolderSelectionTransition")
|
||||
|
||||
val iconSelectionColor = MaterialTheme.colorScheme.surfaceColorAtElevation(10.dp)
|
||||
val paddingTransition by transition.animateDp(label = "FolderPaddingTransition") { selected ->
|
||||
if (selected) 4.dp else 0.dp
|
||||
}
|
||||
val roundedCornerShapeTransition by transition.animateDp(label = "FolderRoundedCornerTransition") { selected ->
|
||||
if (selected) 24.dp else 16.dp
|
||||
}
|
||||
|
||||
val showCoverUri by remember(folder.coverUri) { mutableStateOf(!folder.coverUri.isNullOrEmpty() && isValidUri(context, folder.coverUri)) }
|
||||
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
shape = RoundedCornerShape(roundedCornerShapeTransition),
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingTransition)
|
||||
.combinedClickable(
|
||||
onClick = {
|
||||
if (!selectionMode) {
|
||||
onFolderViewClick()
|
||||
} else {
|
||||
onItemSelection()
|
||||
}
|
||||
},
|
||||
onLongClick = {
|
||||
if (!selectionMode) {
|
||||
haptics.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
onItemSelection()
|
||||
}
|
||||
}
|
||||
),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxHeight(0.8f)
|
||||
.fillMaxWidth()
|
||||
.border(
|
||||
width = 1.dp,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.1f),
|
||||
shape = RoundedCornerShape(12.dp)
|
||||
)
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
) {
|
||||
if (showCoverUri) {
|
||||
GlideImage(
|
||||
imageModel = { folder.coverUri?.decompress("content://com.android.externalstorage.documents/")?.toUri() },
|
||||
imageOptions = ImageOptions(
|
||||
contentScale = ContentScale.Crop,
|
||||
alignment = Alignment.Center,
|
||||
requestSize = IntSize(300, 300),
|
||||
),
|
||||
modifier = Modifier.fillMaxSize()
|
||||
)
|
||||
} else {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Icon(
|
||||
imageVector = Icons.Rounded.Block,
|
||||
contentDescription = stringResource(R.string.image_is_not_selected),
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
|
||||
)
|
||||
}
|
||||
}
|
||||
if (selectionMode) {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
if (itemSelected) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = stringResource(R.string.image_is_selected),
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopStart)
|
||||
.padding(9.dp)
|
||||
.border(2.dp, iconSelectionColor, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(iconSelectionColor)
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.RadioButtonUnchecked,
|
||||
contentDescription = stringResource(R.string.image_is_not_selected),
|
||||
tint = Color.White.copy(alpha = 0.7f),
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopStart)
|
||||
.padding(6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
modifier = Modifier
|
||||
.align(Alignment.Start)
|
||||
.fillMaxHeight()
|
||||
.wrapContentHeight(Alignment.CenterVertically),
|
||||
) {
|
||||
folder.folderName?.let { name ->
|
||||
Text(
|
||||
text = name,
|
||||
modifier = Modifier,
|
||||
fontSize = 16.sp,
|
||||
style = MaterialTheme.typography.titleSmall
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = folder.wallpapers.size.toString().plus(" " + stringResource(R.string.wallpapers)),
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.tertiary,
|
||||
style = MaterialTheme.typography.titleSmall
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album.components
|
||||
|
||||
import androidx.compose.animation.core.animateDp
|
||||
import androidx.compose.animation.core.updateTransition
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.RadioButtonUnchecked
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember // Added
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalHapticFeedback
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.decompress
|
||||
import com.anthonyla.paperize.core.isValidUri
|
||||
import com.skydoves.landscapist.ImageOptions
|
||||
import com.skydoves.landscapist.glide.GlideImage
|
||||
|
||||
/**
|
||||
* A composable that displays a wallpaper item. It shows the wallpaper image and a selection icon when selected
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun WallpaperItem(
|
||||
wallpaperUri: String,
|
||||
itemSelected: Boolean,
|
||||
selectionMode: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
allowHapticFeedback: Boolean = true,
|
||||
onItemSelection: () -> Unit,
|
||||
onWallpaperViewClick: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val haptics = LocalHapticFeedback.current
|
||||
|
||||
val showUri by remember(wallpaperUri) { mutableStateOf(isValidUri(context, wallpaperUri)) }
|
||||
val decompressedUri by remember(wallpaperUri) {
|
||||
mutableStateOf(wallpaperUri.decompress("content://com.android.externalstorage.documents/").toUri())
|
||||
}
|
||||
|
||||
val imageOptions = remember {
|
||||
ImageOptions(
|
||||
requestSize = IntSize(200, 200),
|
||||
alignment = Alignment.Center,
|
||||
)
|
||||
}
|
||||
|
||||
val transition = updateTransition(itemSelected, label = "WallpaperItemSelection")
|
||||
|
||||
val paddingTransition by transition.animateDp(label = "padding") { selected ->
|
||||
if (selected) 5.dp else 0.dp
|
||||
}
|
||||
val roundedCornerShapeTransition by transition.animateDp(label = "roundedCornerShape") { selected ->
|
||||
if (selected) 24.dp else 16.dp
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.padding(paddingTransition)
|
||||
.clip(RoundedCornerShape(roundedCornerShapeTransition))
|
||||
.combinedClickable(
|
||||
onClick = {
|
||||
if (!selectionMode) {
|
||||
onWallpaperViewClick()
|
||||
} else {
|
||||
onItemSelection()
|
||||
}
|
||||
},
|
||||
onLongClick = {
|
||||
if (!selectionMode) {
|
||||
if (allowHapticFeedback) haptics.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
onItemSelection()
|
||||
}
|
||||
}
|
||||
)
|
||||
) {
|
||||
if (showUri) {
|
||||
GlideImage(
|
||||
imageModel = { decompressedUri },
|
||||
imageOptions = imageOptions,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.clip(RoundedCornerShape(roundedCornerShapeTransition))
|
||||
)
|
||||
}
|
||||
if (selectionMode) {
|
||||
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
|
||||
if (itemSelected) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = stringResource(R.string.image_is_selected),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier
|
||||
.padding(9.dp)
|
||||
.clip(CircleShape)
|
||||
.background(bgColor)
|
||||
.border(2.dp, bgColor, CircleShape)
|
||||
.align(Alignment.TopEnd)
|
||||
)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.RadioButtonUnchecked,
|
||||
contentDescription = stringResource(R.string.image_is_not_selected),
|
||||
tint = Color.White.copy(alpha = 0.7f),
|
||||
modifier = Modifier
|
||||
.padding(6.dp)
|
||||
.align(Alignment.TopEnd)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-354
@@ -1,354 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
|
||||
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.core.compress
|
||||
import com.anthonyla.paperize.core.getFolderMetadata
|
||||
import com.anthonyla.paperize.core.getImageMetadata
|
||||
import com.anthonyla.paperize.core.getWallpaperFromFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.SelectionState
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
import kotlin.collections.plus
|
||||
|
||||
@HiltViewModel
|
||||
class AlbumScreenViewModel @Inject constructor(
|
||||
application: Application,
|
||||
private val repository: AlbumRepository,
|
||||
) : AndroidViewModel(application) {
|
||||
private val context: Context
|
||||
get() = getApplication<Application>().applicationContext
|
||||
private val _state = MutableStateFlow<AlbumViewState>(AlbumViewState())
|
||||
val state = combine(
|
||||
loadAlbumsFlow(),
|
||||
_state
|
||||
) { albums: List<AlbumWithWallpaperAndFolder>, currentState: AlbumViewState ->
|
||||
currentState.copy(albums = albums)
|
||||
}.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = AlbumViewState()
|
||||
)
|
||||
|
||||
private fun loadAlbumsFlow() = repository.getAlbumsWithWallpaperAndFolder()
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
state.collect { newState -> _state.value = newState }
|
||||
}
|
||||
}
|
||||
|
||||
fun onEvent(event: AlbumViewEvent) {
|
||||
when (event) {
|
||||
is AlbumViewEvent.LoadAlbum -> {
|
||||
viewModelScope.launch {
|
||||
_state.update {
|
||||
it.copy(initialAlbumName = event.initialAlbumName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.AddWallpapers -> {
|
||||
viewModelScope.launch {
|
||||
if (event.wallpaperUris.isEmpty()) { return@launch }
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
val existingUris = album.wallpapers.map { it.wallpaperUri }
|
||||
val newUris = event.wallpaperUris.filter { it !in existingUris }
|
||||
if (newUris.isEmpty()) { return@launch }
|
||||
val wallpapers = newUris.mapIndexed { index, uri ->
|
||||
val metadata = getImageMetadata(context, uri)
|
||||
Wallpaper(
|
||||
initialAlbumName = _state.value.initialAlbumName,
|
||||
wallpaperUri = uri.compress("content://com.android.externalstorage.documents/"),
|
||||
fileName = metadata.filename,
|
||||
dateModified = metadata.lastModified,
|
||||
order = if (album.wallpapers.isEmpty()) 0 else album.wallpapers.size + index,
|
||||
key = _state.value.initialAlbumName.hashCode() + uri.hashCode()
|
||||
)
|
||||
}
|
||||
var totalWallpapers = album.wallpapers.size + wallpapers.size
|
||||
val folders = album.folders.map { folder ->
|
||||
val updatedWallpapers = folder.wallpapers.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(
|
||||
order = index + totalWallpapers
|
||||
)
|
||||
}
|
||||
totalWallpapers += folder.wallpapers.size
|
||||
folder.copy(
|
||||
wallpapers = updatedWallpapers
|
||||
)
|
||||
}
|
||||
val albumWithWallpaperAndFolder = album.copy(
|
||||
wallpapers = album.wallpapers + wallpapers,
|
||||
folders = folders
|
||||
)
|
||||
repository.upsertAlbumWithWallpaperAndFolder(albumWithWallpaperAndFolder)
|
||||
_state.update {
|
||||
it.copy(
|
||||
isEmpty = false,
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.AddFolder -> {
|
||||
viewModelScope.launch {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null || album.folders.any { it.folderUri == event.directoryUri }) { return@launch }
|
||||
_state.update { it.copy(isLoading = true) }
|
||||
val wallpapers = getWallpaperFromFolder(event.directoryUri, context).mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(
|
||||
initialAlbumName = _state.value.initialAlbumName,
|
||||
key = _state.value.initialAlbumName.hashCode() + event.directoryUri.hashCode() + wallpaper.wallpaperUri.hashCode(),
|
||||
order = index + album.wallpapers.size + album.folders.sumOf { it.wallpapers.size }
|
||||
)
|
||||
}
|
||||
val metadata = getFolderMetadata(event.directoryUri, context)
|
||||
val folder = Folder(
|
||||
initialAlbumName = _state.value.initialAlbumName,
|
||||
folderUri = event.directoryUri,
|
||||
folderName = metadata.filename,
|
||||
coverUri = wallpapers.map { it.wallpaperUri }.firstOrNull() ?: "",
|
||||
dateModified = metadata.lastModified,
|
||||
wallpapers = wallpapers,
|
||||
order = album.folders.size,
|
||||
key = _state.value.initialAlbumName.hashCode() + event.directoryUri.hashCode()
|
||||
)
|
||||
repository.upsertFolder(folder)
|
||||
_state.update {
|
||||
it.copy(
|
||||
isEmpty = false,
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.ChangeAlbumName -> {
|
||||
viewModelScope.launch {
|
||||
if (!_state.value.albums.any { it.album.displayedAlbumName == event.displayName }) {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
repository.updateAlbum(
|
||||
album.album.copy(displayedAlbumName = event.displayName)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.SelectWallpaper -> {
|
||||
viewModelScope.launch {
|
||||
if (!_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
_state.update {
|
||||
val newSelectedWallpapers = it.selectionState.selectedWallpapers.plus(event.wallpaperUri)
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedWallpapers = newSelectedWallpapers,
|
||||
selectedCount = newSelectedWallpapers.size + it.selectionState.selectedFolders.size,
|
||||
allSelected = it.selectionState.selectedFolders.size + newSelectedWallpapers.size >=
|
||||
album.folders.size + album.wallpapers.size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.SelectFolder -> {
|
||||
viewModelScope.launch {
|
||||
if (!_state.value.selectionState.selectedFolders.contains(event.directoryUri)) {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
_state.update {
|
||||
val newSelectedFolders = it.selectionState.selectedFolders.plus(event.directoryUri)
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedFolders = newSelectedFolders,
|
||||
selectedCount = newSelectedFolders.size + it.selectionState.selectedWallpapers.size,
|
||||
allSelected = newSelectedFolders.size + it.selectionState.selectedWallpapers.size >=
|
||||
album.folders.size + album.wallpapers.size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.DeselectFolder -> {
|
||||
viewModelScope.launch {
|
||||
if (_state.value.selectionState.selectedFolders.contains(event.directoryUri)) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedFolders = it.selectionState.selectedFolders.minus(event.directoryUri),
|
||||
selectedCount = it.selectionState.selectedCount - 1,
|
||||
allSelected = false
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.DeselectWallpaper -> {
|
||||
viewModelScope.launch {
|
||||
if (_state.value.selectionState.selectedWallpapers.contains(event.wallpaperUri)) {
|
||||
_state.update {
|
||||
it.copy(
|
||||
selectionState = it.selectionState.copy(
|
||||
selectedWallpapers = it.selectionState.selectedWallpapers.minus(event.wallpaperUri),
|
||||
selectedCount = it.selectionState.selectedCount - 1,
|
||||
allSelected = false
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.DeleteSelected -> {
|
||||
viewModelScope.launch {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
val selectedFolders = _state.value.selectionState.selectedFolders
|
||||
val selectedWallpapers = _state.value.selectionState.selectedWallpapers
|
||||
val foldersToDelete = album.folders.filter { selectedFolders.contains(it.folderUri) }
|
||||
val wallpapersToDelete = album.wallpapers.filter { selectedWallpapers.contains(it.wallpaperUri) }
|
||||
if (foldersToDelete.size + wallpapersToDelete.size == album.folders.size + album.wallpapers.size) {
|
||||
repository.cascadeDeleteAlbum(album.album)
|
||||
}
|
||||
else {
|
||||
repository.deleteFolderList(foldersToDelete)
|
||||
repository.deleteWallpaperList(wallpapersToDelete)
|
||||
if (album.album.coverUri in (foldersToDelete.map { it.folderUri } + wallpapersToDelete.map { it.wallpaperUri })) {
|
||||
val newCover = album.folders.minus(foldersToDelete.toSet()).firstOrNull()?.coverUri ?: album.wallpapers.minus(wallpapersToDelete.toSet()
|
||||
).firstOrNull()?.wallpaperUri ?: ""
|
||||
repository.updateAlbum(album.album.copy(coverUri = newCover))
|
||||
}
|
||||
|
||||
val remainingWallpapers = album.wallpapers.minus(wallpapersToDelete.toSet())
|
||||
val newWallpapers = remainingWallpapers.sortedBy { it.order }.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(order = index)
|
||||
}
|
||||
|
||||
val remainingFolders = album.folders.minus(foldersToDelete.toSet())
|
||||
var totalWallpaper = newWallpapers.size
|
||||
val newFolders = remainingFolders.sortedBy { it.order }.mapIndexed { folderIndex, folder ->
|
||||
val updatedWallpapers = folder.wallpapers.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(order = index + totalWallpaper)
|
||||
}
|
||||
totalWallpaper += folder.wallpapers.size
|
||||
folder.copy(
|
||||
wallpapers = updatedWallpapers,
|
||||
order = folderIndex
|
||||
)
|
||||
}
|
||||
|
||||
repository.upsertAlbumWithWallpaperAndFolder(
|
||||
album.copy(
|
||||
folders = newFolders,
|
||||
wallpapers = newWallpapers
|
||||
)
|
||||
)
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.Reset -> {
|
||||
viewModelScope.launch {
|
||||
_state.update { AlbumViewState() }
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.SelectAll -> {
|
||||
viewModelScope.launch {
|
||||
if (!_state.value.selectionState.allSelected) {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
_state.update {
|
||||
it.copy(
|
||||
selectionState = SelectionState(
|
||||
selectedFolders = album.folders.map { it.folderUri },
|
||||
selectedWallpapers = album.wallpapers.map { it.wallpaperUri },
|
||||
allSelected = true,
|
||||
selectedCount = album.folders.size + album.wallpapers.size
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.DeselectAll -> {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(selectionState = SelectionState()) }
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.SetLoading -> {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(isLoading = event.isLoading) }
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.LoadFoldersAndWallpapers -> {
|
||||
viewModelScope.launch {
|
||||
_state.update { state ->
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
repository.upsertAlbumWithWallpaperAndFolder(
|
||||
AlbumWithWallpaperAndFolder(
|
||||
album = album.album.copy(
|
||||
coverUri = event.folders.firstOrNull()?.coverUri ?: event.wallpapers.firstOrNull()?.wallpaperUri ?: ""
|
||||
),
|
||||
folders = event.folders.map {
|
||||
it.copy(coverUri = it.wallpapers.firstOrNull()?.wallpaperUri ?: "")
|
||||
},
|
||||
wallpapers = event.wallpapers
|
||||
)
|
||||
)
|
||||
state.copy(
|
||||
selectionState = SelectionState(),
|
||||
isLoading = false
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is AlbumViewEvent.DeleteAlbum -> {
|
||||
viewModelScope.launch {
|
||||
val album = _state.value.albums.find { it.album.initialAlbumName == _state.value.initialAlbumName }
|
||||
if (album == null) { return@launch }
|
||||
repository.cascadeDeleteAlbum(album.album)
|
||||
_state.update { AlbumViewState() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.AddAlbumEvent
|
||||
|
||||
sealed class AlbumViewEvent {
|
||||
data object Reset: AlbumViewEvent()
|
||||
data object SelectAll: AlbumViewEvent()
|
||||
data object DeselectAll: AlbumViewEvent()
|
||||
data object DeleteSelected: AlbumViewEvent()
|
||||
data object DeleteAlbum: AlbumViewEvent()
|
||||
|
||||
data class LoadAlbum(
|
||||
val initialAlbumName: String
|
||||
): AlbumViewEvent()
|
||||
data class AddWallpapers(
|
||||
val wallpaperUris: List<String>
|
||||
): AlbumViewEvent()
|
||||
data class AddFolder(
|
||||
val directoryUri: String
|
||||
): AlbumViewEvent()
|
||||
data class SelectWallpaper(
|
||||
val wallpaperUri: String
|
||||
): AlbumViewEvent()
|
||||
data class SelectFolder(
|
||||
val directoryUri: String
|
||||
): AlbumViewEvent()
|
||||
data class DeselectFolder(
|
||||
val directoryUri: String
|
||||
): AlbumViewEvent()
|
||||
data class DeselectWallpaper(
|
||||
val wallpaperUri: String
|
||||
): AlbumViewEvent()
|
||||
data class ChangeAlbumName(
|
||||
val displayName: String
|
||||
): AlbumViewEvent()
|
||||
data class SetLoading(
|
||||
val isLoading: Boolean
|
||||
): AlbumViewEvent()
|
||||
data class LoadFoldersAndWallpapers(
|
||||
val folders: List<Folder>,
|
||||
val wallpapers: List<Wallpaper>
|
||||
): AlbumViewEvent()
|
||||
}
|
||||
-394
@@ -1,394 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumAnimatedFab
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.FolderItem
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.components.AlbumViewTopBar
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import my.nanihadesuka.compose.LazyVerticalGridScrollbar
|
||||
import my.nanihadesuka.compose.ScrollbarSettings
|
||||
|
||||
@Composable
|
||||
fun AlbumViewScreen(
|
||||
albumScreenViewModel: AlbumScreenViewModel,
|
||||
animate: Boolean,
|
||||
onBackClick: () -> Unit,
|
||||
onShowWallpaperView: (String, String) -> Unit,
|
||||
onShowFolderView: (Folder) -> Unit,
|
||||
onDeleteAlbum: () -> Unit,
|
||||
onSortClick: (List<Folder>, List<Wallpaper>) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val lazyListState = rememberLazyGridState()
|
||||
|
||||
val albumViewState by albumScreenViewModel.state.collectAsStateWithLifecycle()
|
||||
|
||||
val album = remember(albumViewState.albums, albumViewState.initialAlbumName) {
|
||||
albumViewState.albums.find { it.album.initialAlbumName == albumViewState.initialAlbumName }
|
||||
}
|
||||
|
||||
val colorScheme = MaterialTheme.colorScheme
|
||||
val scrollbarSettings = remember {
|
||||
ScrollbarSettings.Default.copy(
|
||||
thumbUnselectedColor = colorScheme.primary,
|
||||
thumbSelectedColor = colorScheme.primary,
|
||||
thumbShape = RoundedCornerShape(16.dp),
|
||||
scrollbarPadding = 1.dp,
|
||||
)
|
||||
}
|
||||
|
||||
val commonItemModifier = remember {
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(9f / 16f)
|
||||
}
|
||||
|
||||
BackHandler(
|
||||
enabled = albumViewState.selectionState.selectedCount > 0,
|
||||
onBack = remember(albumViewState.isLoading, albumScreenViewModel) {
|
||||
{
|
||||
if (!albumViewState.isLoading) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** Image picker **/
|
||||
val imagePickerLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenMultipleDocuments(),
|
||||
onResult = remember(albumScreenViewModel, scope, context) {
|
||||
{ uris: List<Uri> ->
|
||||
val selectionLimit = 500
|
||||
if (uris.size > selectionLimit) {
|
||||
Toast.makeText(
|
||||
context,
|
||||
"Please select fewer than $selectionLimit images at a time. For bulk imports, use the 'Add Folder' option.",
|
||||
Toast.LENGTH_LONG
|
||||
).show()
|
||||
}
|
||||
|
||||
else if (uris.isNotEmpty()) {
|
||||
scope.launch(Dispatchers.IO) {
|
||||
withContext(Dispatchers.Main) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.SetLoading(true))
|
||||
}
|
||||
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
val uriList = uris.mapNotNull { uri ->
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
|
||||
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
|
||||
if (persistedUriPermissions.any { it.uri == uri }) uri.toString() else null
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("AlbumViewScreen", "Failed to take persistable URI permission for image: ${e.message}")
|
||||
null
|
||||
}
|
||||
}
|
||||
withContext(Dispatchers.Main) {
|
||||
if (uriList.isNotEmpty()) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.AddWallpapers(uriList))
|
||||
}
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.SetLoading(false))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
/** Folder picker **/
|
||||
val folderPickerLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.OpenDocumentTree(),
|
||||
onResult = remember(albumScreenViewModel, scope, context) {
|
||||
{ uri: Uri? ->
|
||||
scope.launch(Dispatchers.IO) {
|
||||
val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
if (uri != null) {
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
|
||||
val persistedUriPermissions = context.contentResolver.persistedUriPermissions
|
||||
if (persistedUriPermissions.any { it.uri == uri }) {
|
||||
withContext(Dispatchers.Main) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.AddFolder(uri.toString()))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("AlbumViewScreen", "Failed to take persistable URI permission for folder: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
val onSelectAllClick = remember(
|
||||
albumViewState.isLoading,
|
||||
albumViewState.selectionState.allSelected,
|
||||
albumScreenViewModel
|
||||
) {
|
||||
{
|
||||
if (!albumViewState.isLoading) {
|
||||
if (!albumViewState.selectionState.allSelected) albumScreenViewModel.onEvent(
|
||||
AlbumViewEvent.SelectAll
|
||||
)
|
||||
else albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onBackClickTopBar = remember(albumScreenViewModel, onBackClick) {
|
||||
{
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.Reset)
|
||||
onBackClick()
|
||||
}
|
||||
}
|
||||
|
||||
val onDeleteSelected = remember(
|
||||
albumViewState.isLoading,
|
||||
album,
|
||||
albumViewState.selectionState.selectedCount,
|
||||
albumScreenViewModel,
|
||||
onBackClick
|
||||
) {
|
||||
{
|
||||
if (!albumViewState.isLoading) {
|
||||
if (album != null) {
|
||||
if (album.folders.size + album.wallpapers.size == albumViewState.selectionState.selectedCount) {
|
||||
onBackClick()
|
||||
}
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.DeleteSelected)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onDeleteAlbumTopBar = remember(
|
||||
albumViewState.isLoading,
|
||||
album,
|
||||
albumScreenViewModel,
|
||||
onDeleteAlbum
|
||||
) {
|
||||
{
|
||||
if (!albumViewState.isLoading && album != null) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.DeleteAlbum)
|
||||
onDeleteAlbum()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onTitleChangeTopBar: (String) -> Unit = remember(
|
||||
albumViewState.isLoading,
|
||||
album,
|
||||
albumScreenViewModel
|
||||
) {
|
||||
{ newTitle ->
|
||||
if (!albumViewState.isLoading && album != null) {
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.ChangeAlbumName(newTitle))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onSortClickTopBar = remember(
|
||||
albumViewState.isLoading,
|
||||
album,
|
||||
onSortClick
|
||||
) {
|
||||
{
|
||||
if (!albumViewState.isLoading && album != null) {
|
||||
onSortClick(album.folders, album.wallpapers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AlbumViewTopBar(
|
||||
title = album?.album?.displayedAlbumName ?: "",
|
||||
allSelected = albumViewState.selectionState.allSelected,
|
||||
selectedCount = albumViewState.selectionState.selectedCount,
|
||||
selectionMode = albumViewState.selectionState.selectedCount > 0,
|
||||
isLoad = albumViewState.isLoading,
|
||||
onSelectAllClick = onSelectAllClick,
|
||||
onBackClick = onBackClickTopBar,
|
||||
onDeleteSelected = onDeleteSelected,
|
||||
onDeleteAlbum = onDeleteAlbumTopBar,
|
||||
onTitleChange = onTitleChangeTopBar,
|
||||
onSortClick = onSortClickTopBar
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
val onImageClickFab = remember(albumScreenViewModel, imagePickerLauncher) {
|
||||
{
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
|
||||
imagePickerLauncher.launch(arrayOf("image/*"))
|
||||
}
|
||||
}
|
||||
val onFolderClickFab = remember(albumScreenViewModel, folderPickerLauncher) {
|
||||
{
|
||||
albumScreenViewModel.onEvent(AlbumViewEvent.DeselectAll)
|
||||
folderPickerLauncher.launch(null)
|
||||
}
|
||||
}
|
||||
|
||||
AddAlbumAnimatedFab(
|
||||
isLoading = albumViewState.isLoading,
|
||||
animate = animate,
|
||||
onImageClick = onImageClickFab,
|
||||
onFolderClick = onFolderClickFab
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (albumViewState.isLoading) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
},
|
||||
content = { paddingValues ->
|
||||
if (album != null) {
|
||||
LazyVerticalGridScrollbar(
|
||||
state = lazyListState,
|
||||
settings = scrollbarSettings,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues),
|
||||
) {
|
||||
LazyVerticalGrid(
|
||||
state = lazyListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
columns = GridCells.Adaptive(150.dp),
|
||||
contentPadding = PaddingValues(4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
items(
|
||||
items = album.folders,
|
||||
key = { folder -> folder.folderUri }
|
||||
) { folder ->
|
||||
val isSelected = albumViewState.selectionState.selectedFolders.contains(folder.folderUri)
|
||||
val onFolderItemSelection = remember(
|
||||
folder.folderUri,
|
||||
albumViewState.isLoading,
|
||||
albumViewState.selectionState.selectedFolders
|
||||
) {
|
||||
{
|
||||
if (!albumViewState.isLoading) {
|
||||
albumScreenViewModel.onEvent(
|
||||
if (!isSelected) AlbumViewEvent.SelectFolder(folder.folderUri)
|
||||
else AlbumViewEvent.DeselectFolder(folder.folderUri)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onFolderViewClickItem = remember(folder, albumViewState.isLoading, onShowFolderView) {
|
||||
{
|
||||
if (!albumViewState.isLoading) {
|
||||
onShowFolderView(folder)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
FolderItem(
|
||||
folder = folder,
|
||||
itemSelected = isSelected,
|
||||
selectionMode = albumViewState.selectionState.selectedCount > 0,
|
||||
onItemSelection = onFolderItemSelection,
|
||||
onFolderViewClick = onFolderViewClickItem,
|
||||
modifier = commonItemModifier
|
||||
.then(
|
||||
if (animate) Modifier.animateItem(
|
||||
placementSpec = tween(
|
||||
durationMillis = 800,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
) else Modifier
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
items(
|
||||
items = album.wallpapers,
|
||||
key = { wallpaper -> wallpaper.wallpaperUri }
|
||||
) { wallpaper ->
|
||||
val isSelected = albumViewState.selectionState.selectedWallpapers.contains(wallpaper.wallpaperUri)
|
||||
val onWallpaperItemSelection = remember(
|
||||
wallpaper.wallpaperUri,
|
||||
albumViewState.isLoading,
|
||||
albumViewState.selectionState.selectedWallpapers
|
||||
) {
|
||||
{
|
||||
if (!albumViewState.isLoading) {
|
||||
albumScreenViewModel.onEvent(
|
||||
if (!isSelected) AlbumViewEvent.SelectWallpaper(wallpaper.wallpaperUri)
|
||||
else AlbumViewEvent.DeselectWallpaper(wallpaper.wallpaperUri)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val onWallpaperViewClickItem = remember(wallpaper, albumViewState.isLoading, onShowWallpaperView) {
|
||||
{
|
||||
if (!albumViewState.isLoading)
|
||||
onShowWallpaperView(wallpaper.wallpaperUri, wallpaper.fileName)
|
||||
}
|
||||
}
|
||||
|
||||
WallpaperItem(
|
||||
wallpaperUri = wallpaper.wallpaperUri,
|
||||
itemSelected = isSelected,
|
||||
selectionMode = albumViewState.selectionState.selectedCount > 0,
|
||||
onItemSelection = onWallpaperItemSelection,
|
||||
onWallpaperViewClick = onWallpaperViewClickItem,
|
||||
modifier = commonItemModifier
|
||||
.then(
|
||||
if (animate) Modifier.animateItem(
|
||||
placementSpec = tween(
|
||||
durationMillis = 800,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
) else Modifier
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.SelectionState
|
||||
|
||||
data class AlbumViewState (
|
||||
val albums: List<AlbumWithWallpaperAndFolder> = emptyList(),
|
||||
val initialAlbumName: String = "",
|
||||
val selectionState: SelectionState = SelectionState(),
|
||||
val isEmpty: Boolean = true,
|
||||
val isLoading: Boolean = false
|
||||
)
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.anthonyla.paperize.R
|
||||
import kotlinx.coroutines.android.awaitFrame
|
||||
|
||||
/**
|
||||
* Dialog for creating a new album. Input of album name is required.
|
||||
*/
|
||||
@Composable
|
||||
fun AlbumNameDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
onConfirmation: (String) -> Unit
|
||||
) {
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
var albumName by rememberSaveable { mutableStateOf("") }
|
||||
Dialog(onDismissRequest = onDismissRequest) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.Top,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
LaunchedEffect(focusRequester) {
|
||||
awaitFrame()
|
||||
focusRequester.requestFocus()
|
||||
}
|
||||
Spacer(modifier = Modifier.padding(10.dp))
|
||||
OutlinedTextField(
|
||||
value = albumName,
|
||||
onValueChange = { albumName = it },
|
||||
label = { Text(stringResource(R.string.album_name)) },
|
||||
modifier = Modifier
|
||||
.padding(vertical = 12.dp, horizontal = 32.dp)
|
||||
.focusRequester(focusRequester),
|
||||
singleLine = true,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onDone = {
|
||||
if (albumName.isNotEmpty()) {
|
||||
onConfirmation(albumName)
|
||||
onDismissRequest()
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
) {
|
||||
TextButton(
|
||||
onClick = { onDismissRequest() },
|
||||
modifier = Modifier.padding(8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
TextButton(
|
||||
modifier = Modifier.padding(8.dp),
|
||||
onClick = {
|
||||
if (albumName.isNotEmpty()) {
|
||||
onConfirmation(albumName)
|
||||
onDismissRequest()
|
||||
}
|
||||
}
|
||||
) {
|
||||
Text(stringResource(R.string.save))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-204
@@ -1,204 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Sort
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.RadioButtonUnchecked
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.DpOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.DeleteImagesAlertDialog
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.AlbumViewState
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
|
||||
/**
|
||||
* Top bar for the album view screen
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AlbumViewTopBar(
|
||||
title: String,
|
||||
allSelected: Boolean,
|
||||
selectedCount: Int,
|
||||
selectionMode: Boolean,
|
||||
isLoad: Boolean,
|
||||
onBackClick: () -> Unit,
|
||||
onSortClick: () -> Unit,
|
||||
onSelectAllClick: () -> Unit,
|
||||
onDeleteAlbum: () -> Unit,
|
||||
onDeleteSelected: () -> Unit,
|
||||
onTitleChange: (String) -> Unit,
|
||||
) {
|
||||
var showDeleteAlertDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var showNameChangeDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var menuExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var showSelectionDeleteDialog by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
TopAppBar(
|
||||
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
|
||||
title = { if (!selectionMode) Text(title) },
|
||||
navigationIcon = {
|
||||
if (!selectionMode) {
|
||||
IconButton(
|
||||
onClick = onBackClick,
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.requiredSize(24.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(id = R.string.home_screen)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
|
||||
IconButton(onClick = onSelectAllClick) {
|
||||
Icon(
|
||||
imageVector = if (allSelected) Icons.Default.CheckCircle else Icons.Default.RadioButtonUnchecked,
|
||||
contentDescription = stringResource(
|
||||
if (allSelected) R.string.all_images_selected_for_deletion
|
||||
else R.string.select_all_images_for_deletion
|
||||
),
|
||||
modifier = if (allSelected) {
|
||||
Modifier
|
||||
.padding(4.dp)
|
||||
.border(2.dp, bgColor, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(bgColor)
|
||||
} else {
|
||||
Modifier.padding(6.dp)
|
||||
}
|
||||
)
|
||||
}
|
||||
Text(stringResource(R.string.selected, selectedCount))
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (!selectionMode) {
|
||||
if (showDeleteAlertDialog) DeleteAlbumAlertDialog (
|
||||
onDismissRequest = { showDeleteAlertDialog = false },
|
||||
onConfirmation = {
|
||||
showDeleteAlertDialog = false
|
||||
if (!isLoad) { onDeleteAlbum() }
|
||||
}
|
||||
)
|
||||
if (showNameChangeDialog) AlbumNameDialog (
|
||||
onDismissRequest = { showNameChangeDialog = false },
|
||||
onConfirmation = {
|
||||
showNameChangeDialog = false
|
||||
if (!isLoad) { onTitleChange(it) }
|
||||
}
|
||||
)
|
||||
Row {
|
||||
Box {
|
||||
IconButton(
|
||||
onClick = { if (!isLoad) { onSortClick() } }
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Default.Sort,
|
||||
contentDescription = stringResource(R.string.sort_items),
|
||||
modifier = Modifier.padding(6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
if (!isLoad) { menuExpanded = true }
|
||||
}) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.MoreVert,
|
||||
contentDescription = stringResource(R.string.more_options),
|
||||
)
|
||||
MaterialTheme(
|
||||
shapes = MaterialTheme.shapes.copy(extraSmall = RoundedCornerShape(16.dp))
|
||||
) {
|
||||
DropdownMenu(
|
||||
expanded = menuExpanded,
|
||||
onDismissRequest = { menuExpanded = false },
|
||||
offset = DpOffset(0.dp, 5.dp),
|
||||
modifier = Modifier.padding(8.dp),
|
||||
containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.delete_album)) },
|
||||
onClick = {
|
||||
if (!isLoad) {
|
||||
showDeleteAlertDialog = true
|
||||
}
|
||||
menuExpanded = false
|
||||
}
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.change_name)) },
|
||||
onClick = {
|
||||
if (!isLoad) {
|
||||
showNameChangeDialog = true
|
||||
}
|
||||
menuExpanded = false
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (showSelectionDeleteDialog) DeleteImagesAlertDialog (
|
||||
onDismissRequest = { showSelectionDeleteDialog = false },
|
||||
onConfirmation = {
|
||||
showSelectionDeleteDialog = false
|
||||
if (!isLoad) {
|
||||
onDeleteSelected()
|
||||
}
|
||||
}
|
||||
)
|
||||
IconButton(
|
||||
onClick = { showSelectionDeleteDialog = true }
|
||||
) {
|
||||
Icon(
|
||||
imageVector = if (showSelectionDeleteDialog) Icons.Filled.Delete else Icons.Outlined.Delete,
|
||||
contentDescription = stringResource(R.string.select_all_images_for_deletion),
|
||||
modifier = Modifier.padding(6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.album_view_screen.components
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
/**
|
||||
* AlertDialog for confirmation of deleting an album
|
||||
*/
|
||||
@Composable
|
||||
fun DeleteAlbumAlertDialog(
|
||||
onDismissRequest: () -> Unit,
|
||||
onConfirmation: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
icon = {
|
||||
Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.delete_confirmation))
|
||||
},
|
||||
title = { Text(text = stringResource(R.string.delete_album_question)) },
|
||||
text = { Text(text = stringResource(R.string.are_you_sure_you_want_to_delete_this)) },
|
||||
onDismissRequest = { onDismissRequest() },
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onConfirmation() }) {
|
||||
Text(stringResource(R.string.confirm))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { onDismissRequest() }) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
|
||||
sealed class FolderEvent {
|
||||
data object Reset: FolderEvent()
|
||||
|
||||
data class LoadFolderView(
|
||||
val folder: Folder? = null
|
||||
): FolderEvent()
|
||||
}
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
|
||||
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Wallpaper
|
||||
|
||||
data class FolderState(
|
||||
val folder: Folder? = null,
|
||||
)
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
|
||||
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortEvent
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.sort_view_screen.SortState
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* ViewModel for the folder view screen to hold the folder name and the list of wallpapers
|
||||
*/
|
||||
class FolderViewModel @Inject constructor (): ViewModel() {
|
||||
private val _state = MutableStateFlow<FolderState>(FolderState())
|
||||
val state = _state.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = FolderState()
|
||||
)
|
||||
|
||||
fun onEvent(event: FolderEvent) {
|
||||
when (event) {
|
||||
is FolderEvent.LoadFolderView -> {
|
||||
_state.value = state.value.copy(
|
||||
folder = event.folder
|
||||
)
|
||||
}
|
||||
is FolderEvent.Reset -> {
|
||||
_state.value = FolderState()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember // Added remember import
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.Folder
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.WallpaperItem
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen.components.FolderViewTopBar
|
||||
import my.nanihadesuka.compose.LazyVerticalGridScrollbar
|
||||
import my.nanihadesuka.compose.ScrollbarSettings
|
||||
|
||||
@Composable
|
||||
fun FolderViewScreen(
|
||||
folder: Folder,
|
||||
onBackClick: () -> Unit,
|
||||
onShowWallpaperView: (String, String) -> Unit,
|
||||
animate: Boolean
|
||||
) {
|
||||
val lazyListState = rememberLazyGridState()
|
||||
val colorScheme = MaterialTheme.colorScheme
|
||||
|
||||
val scrollbarSettings = remember {
|
||||
ScrollbarSettings.Default.copy(
|
||||
thumbUnselectedColor = colorScheme.primary,
|
||||
thumbSelectedColor = colorScheme.primary,
|
||||
thumbShape = RoundedCornerShape(16.dp),
|
||||
scrollbarPadding = 1.dp,
|
||||
)
|
||||
}
|
||||
|
||||
val noOpItemSelection: () -> Unit = remember { { /* Do nothing */ } }
|
||||
|
||||
BackHandler { onBackClick() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
FolderViewTopBar(
|
||||
title = folder.folderName ?: "",
|
||||
onBackClick = onBackClick
|
||||
)
|
||||
},
|
||||
content = { paddingValues ->
|
||||
LazyVerticalGridScrollbar(
|
||||
state = lazyListState,
|
||||
settings = scrollbarSettings,
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues)
|
||||
) {
|
||||
LazyVerticalGrid(
|
||||
state = lazyListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
columns = GridCells.Adaptive(150.dp),
|
||||
contentPadding = PaddingValues(4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||
) {
|
||||
items(items = folder.wallpapers, key = { wallpaper -> wallpaper.wallpaperUri }) { wallpaper ->
|
||||
val itemModifier = remember(animate) {
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(9f / 16f)
|
||||
.then(
|
||||
if (animate) Modifier.animateItem(
|
||||
placementSpec = tween(
|
||||
durationMillis = 800,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
) else Modifier
|
||||
)
|
||||
}
|
||||
|
||||
WallpaperItem(
|
||||
wallpaperUri = wallpaper.wallpaperUri,
|
||||
itemSelected = false,
|
||||
selectionMode = false,
|
||||
allowHapticFeedback = false,
|
||||
onItemSelection = noOpItemSelection,
|
||||
onWallpaperViewClick = {
|
||||
onShowWallpaperView(wallpaper.wallpaperUri, wallpaper.fileName)
|
||||
},
|
||||
modifier = itemModifier
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.folder_view_screen.components
|
||||
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
/**
|
||||
* Top bar for the folder view screen.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun FolderViewTopBar(
|
||||
title: String,
|
||||
onBackClick: () -> Unit
|
||||
) {
|
||||
TopAppBar(
|
||||
colors = topAppBarColors(containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)),
|
||||
title = { Text(title) },
|
||||
navigationIcon = {
|
||||
IconButton(
|
||||
onClick = onBackClick,
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.requiredSize(24.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(id = R.string.home_screen),
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-160
@@ -1,160 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.home_screen
|
||||
|
||||
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.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.PrimaryTabRow
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TimePickerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.anthonyla.paperize.core.ScalingConstants
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.AddAlbumDialog
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.components.HomeTopBar
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.components.getTabItems
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.library_screen.LibraryScreen
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.EffectSettings
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ScheduleSettings
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.ThemeSettings
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.settings_screen.SettingsState.WallpaperSettings
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.wallpaper_screen.WallpaperScreen
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HomeScreen(
|
||||
albums: List<AlbumWithWallpaperAndFolder>,
|
||||
homeSelectedAlbum: AlbumWithWallpaperAndFolder?,
|
||||
lockSelectedAlbum: AlbumWithWallpaperAndFolder?,
|
||||
themeSettings: ThemeSettings,
|
||||
wallpaperSettings: WallpaperSettings,
|
||||
scheduleSettings: ScheduleSettings,
|
||||
effectSettings: EffectSettings,
|
||||
onNavigateAddWallpaper: (String) -> Unit,
|
||||
onViewAlbum: (String) -> Unit,
|
||||
onDarkCheck: (Boolean) -> Unit,
|
||||
onDarkenPercentage: (Int, Int) -> Unit,
|
||||
onHomeCheckedChange: (Boolean) -> Unit,
|
||||
onLockCheckedChange: (Boolean) -> Unit,
|
||||
onScalingChange: (ScalingConstants) -> Unit,
|
||||
onSelectAlbum: (AlbumWithWallpaperAndFolder, Boolean, Boolean) -> Unit,
|
||||
onScheduleSeparatelyChange: (Boolean) -> Unit,
|
||||
onHomeTimeChange: (Int) -> Unit,
|
||||
onLockTimeChange: (Int) -> Unit,
|
||||
onSettingsClick: () -> Unit,
|
||||
onDeselect: (Boolean, Boolean) -> Unit,
|
||||
onToggleChanger: (Boolean) -> Unit,
|
||||
onBlurPercentageChange: (Int, Int) -> Unit,
|
||||
onBlurChange: (Boolean) -> Unit,
|
||||
onVignettePercentageChange: (Int, Int) -> Unit,
|
||||
onVignetteChange: (Boolean) -> Unit,
|
||||
onGrayscalePercentageChange: (Int, Int) -> Unit,
|
||||
onGrayscaleChange: (Boolean) -> Unit,
|
||||
onChangeStartTimeToggle: (Boolean) -> Unit,
|
||||
onStartTimeChange: (TimePickerState) -> Unit,
|
||||
onShuffleCheck: (Boolean) -> Unit,
|
||||
onRefreshChange: (Boolean) -> Unit,
|
||||
onSkipLandscapeChange: (Boolean) -> Unit,
|
||||
onSkipNonInteractiveChange: (Boolean) -> Unit,
|
||||
) {
|
||||
val tabItems = getTabItems()
|
||||
val pagerState = rememberPagerState(0) { tabItems.size }
|
||||
var tabIndex by rememberSaveable { mutableIntStateOf(pagerState.currentPage) }
|
||||
var addAlbumDialog by rememberSaveable { mutableStateOf(false) }
|
||||
if (addAlbumDialog) AddAlbumDialog(
|
||||
onDismissRequest = { addAlbumDialog = false },
|
||||
onConfirmation = { onNavigateAddWallpaper(it) }
|
||||
)
|
||||
|
||||
LaunchedEffect(tabIndex) {
|
||||
pagerState.animateScrollToPage(tabIndex)
|
||||
}
|
||||
LaunchedEffect(pagerState.currentPage) {
|
||||
tabIndex = pagerState.currentPage
|
||||
}
|
||||
|
||||
Scaffold (
|
||||
topBar = {
|
||||
HomeTopBar(
|
||||
showSelectionModeAppBar = false,
|
||||
selectionCount = 0,
|
||||
onSettingsClick = onSettingsClick,
|
||||
)
|
||||
}
|
||||
) {
|
||||
Column(modifier = Modifier.padding(it)) {
|
||||
PrimaryTabRow(
|
||||
selectedTabIndex = tabIndex,
|
||||
) {
|
||||
tabItems.forEachIndexed { index, item ->
|
||||
Tab(
|
||||
selected = (index == tabIndex),
|
||||
onClick = { tabIndex = index },
|
||||
text = { Text(text = item.title) },
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = if (index == tabIndex) item.filledIcon else item.unfilledIcon,
|
||||
contentDescription = item.title
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalPager(
|
||||
state = pagerState,
|
||||
beyondViewportPageCount = 1
|
||||
) { index ->
|
||||
when (index.coerceIn(tabItems.indices)) {
|
||||
0 -> WallpaperScreen(
|
||||
albums = albums,
|
||||
homeSelectedAlbum = homeSelectedAlbum,
|
||||
lockSelectedAlbum = lockSelectedAlbum,
|
||||
themeSettings = themeSettings,
|
||||
wallpaperSettings = wallpaperSettings,
|
||||
scheduleSettings = scheduleSettings,
|
||||
effectSettings = effectSettings,
|
||||
onDarkCheck = onDarkCheck,
|
||||
onDarkenPercentage = onDarkenPercentage,
|
||||
onHomeCheckedChange = onHomeCheckedChange,
|
||||
onLockCheckedChange = onLockCheckedChange,
|
||||
onScalingChange = onScalingChange,
|
||||
onScheduleSeparatelyChange = onScheduleSeparatelyChange,
|
||||
onSelectAlbum = onSelectAlbum,
|
||||
onHomeTimeChange = onHomeTimeChange,
|
||||
onLockTimeChange = onLockTimeChange,
|
||||
onDeselect = onDeselect,
|
||||
onToggleChanger = onToggleChanger,
|
||||
onBlurPercentageChange = onBlurPercentageChange,
|
||||
onBlurChange = onBlurChange,
|
||||
onVignettePercentageChange = onVignettePercentageChange,
|
||||
onVignetteChange = onVignetteChange,
|
||||
onGrayscalePercentageChange = onGrayscalePercentageChange,
|
||||
onGrayscaleChange = onGrayscaleChange,
|
||||
onChangeStartTimeToggle = onChangeStartTimeToggle,
|
||||
onStartTimeChange = onStartTimeChange,
|
||||
onShuffleCheck = onShuffleCheck,
|
||||
onRefreshChange = onRefreshChange,
|
||||
onSkipLandscapeChange = onSkipLandscapeChange,
|
||||
onSkipNonInteractiveChange = onSkipNonInteractiveChange
|
||||
)
|
||||
else -> LibraryScreen(
|
||||
albums = albums,
|
||||
onAddNewAlbumClick = { addAlbumDialog = true },
|
||||
onViewAlbum = onViewAlbum,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Settings
|
||||
import androidx.compose.material3.CenterAlignedTopAppBar
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.add_album_screen.components.DeleteImagesAlertDialog
|
||||
|
||||
/**
|
||||
* Top bar for the home screen
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HomeTopBar (
|
||||
showSelectionModeAppBar: Boolean,
|
||||
selectionCount: Int,
|
||||
onSettingsClick: () -> Unit,
|
||||
) {
|
||||
CenterAlignedTopAppBar(
|
||||
colors = TopAppBarDefaults.centerAlignedTopAppBarColors(containerColor = Color.Transparent),
|
||||
title = { if (!showSelectionModeAppBar) Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
if (showSelectionModeAppBar) {
|
||||
var showAlertDialog by rememberSaveable { mutableStateOf(false) }
|
||||
if (showAlertDialog) DeleteImagesAlertDialog (
|
||||
onDismissRequest = { showAlertDialog = false },
|
||||
onConfirmation = {
|
||||
showAlertDialog = false
|
||||
}
|
||||
)
|
||||
IconButton(
|
||||
onClick = { showAlertDialog = true }
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Delete,
|
||||
contentDescription = stringResource(R.string.select_all_images_for_deletion),
|
||||
tint = Color.White.copy(alpha = 0.7f),
|
||||
modifier = Modifier.padding(6.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
if (showSelectionModeAppBar) {
|
||||
Row (
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
IconButton(
|
||||
onClick = { }
|
||||
) {
|
||||
val bgColor = MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp)
|
||||
Icon(
|
||||
imageVector = Icons.Default.CheckCircle,
|
||||
contentDescription = stringResource(R.string.all_images_selected_for_deletion),
|
||||
modifier = Modifier
|
||||
.padding(4.dp)
|
||||
.border(2.dp, bgColor, CircleShape)
|
||||
.clip(CircleShape)
|
||||
.background(bgColor)
|
||||
)
|
||||
}
|
||||
Text(stringResource(R.string.selected_count, selectionCount))
|
||||
}
|
||||
} else {
|
||||
IconButton(
|
||||
onClick = { onSettingsClick() }
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Settings,
|
||||
contentDescription = stringResource(R.string.SettingsIcon),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.home_screen.components
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.AddToPhotos
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.outlined.AddToPhotos
|
||||
import androidx.compose.material.icons.outlined.Image
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
/**
|
||||
* Data class representing a tab item
|
||||
*/
|
||||
data class TabItem(
|
||||
val title: String,
|
||||
val filledIcon: ImageVector,
|
||||
val unfilledIcon: ImageVector,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun getTabItems(): List<TabItem> {
|
||||
val context = LocalContext.current
|
||||
return listOf(
|
||||
TabItem(
|
||||
title = context.getString(R.string.wallpaper_screen),
|
||||
filledIcon = Icons.Filled.Image,
|
||||
unfilledIcon = Icons.Outlined.Image
|
||||
),
|
||||
TabItem(
|
||||
title = context.getString(R.string.library_screen),
|
||||
filledIcon = Icons.Filled.AddToPhotos,
|
||||
unfilledIcon = Icons.Outlined.AddToPhotos
|
||||
)
|
||||
)
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.library_screen
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LargeFloatingActionButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.feature.wallpaper.domain.model.AlbumWithWallpaperAndFolder
|
||||
import com.anthonyla.paperize.feature.wallpaper.presentation.album.components.AlbumItem
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun LibraryScreen(
|
||||
albums: List<AlbumWithWallpaperAndFolder>,
|
||||
onAddNewAlbumClick: () -> Unit,
|
||||
onViewAlbum: (String) -> Unit
|
||||
) {
|
||||
val lazyListState = rememberLazyGridState()
|
||||
Scaffold(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
floatingActionButton = {
|
||||
LargeFloatingActionButton(
|
||||
containerColor = MaterialTheme.colorScheme.primaryContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
onClick = onAddNewAlbumClick,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Add,
|
||||
contentDescription = stringResource(R.string.add_album),
|
||||
modifier = Modifier.padding(16.dp),
|
||||
)
|
||||
}
|
||||
},
|
||||
content = { it
|
||||
LazyVerticalGrid(
|
||||
state = lazyListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
columns = GridCells.Adaptive(150.dp),
|
||||
contentPadding = PaddingValues(4.dp, 4.dp),
|
||||
horizontalArrangement = Arrangement.Start,
|
||||
content = {
|
||||
items (albums, key = { album -> album.album.initialAlbumName}
|
||||
) { album ->
|
||||
AlbumItem(
|
||||
album = album.album,
|
||||
onAlbumViewClick = { onViewAlbum(album.album.initialAlbumName) },
|
||||
modifier = Modifier.padding(4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.notifications_screen
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.ArrowCircleRight
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.airbnb.lottie.compose.LottieAnimation
|
||||
import com.airbnb.lottie.compose.LottieCompositionSpec
|
||||
import com.airbnb.lottie.compose.LottieConstants
|
||||
import com.airbnb.lottie.compose.animateLottieCompositionAsState
|
||||
import com.airbnb.lottie.compose.rememberLottieComposition
|
||||
import com.anthonyla.paperize.R
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
fun NotificationScreen(
|
||||
onAgree: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.notification_animation))
|
||||
val progress by animateLottieCompositionAsState(
|
||||
composition = composition,
|
||||
iterations = LottieConstants.IterateForever,
|
||||
)
|
||||
val askPermission = rememberSaveable { mutableStateOf(false) }
|
||||
val requestPermissionLauncher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.RequestPermission()
|
||||
) { onAgree() }
|
||||
|
||||
fun handleFabClick() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
when {
|
||||
(ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) -> {
|
||||
onAgree()
|
||||
}
|
||||
else -> {
|
||||
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
} else { onAgree() }
|
||||
}
|
||||
|
||||
LaunchedEffect (askPermission.value) {
|
||||
if (askPermission.value) {
|
||||
handleFabClick()
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
content = { it
|
||||
Column (modifier = Modifier.padding(32.dp)) {
|
||||
Spacer(modifier = Modifier.height(120.dp))
|
||||
Text(text = stringResource(id = R.string.notifications), style = MaterialTheme.typography.headlineLarge)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
LottieAnimation(
|
||||
composition = composition,
|
||||
progress = { progress },
|
||||
modifier = Modifier
|
||||
.fillMaxHeight(0.5f)
|
||||
.align(Alignment.CenterHorizontally)
|
||||
.semantics { contentDescription = context.getString(R.string.notification_bell_animation) },
|
||||
safeMode = true,
|
||||
enableMergePaths = true
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Info,
|
||||
contentDescription = stringResource(R.string.agree),
|
||||
modifier = Modifier.padding(PaddingValues(vertical = 16.dp))
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.notification_info_message),
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
},
|
||||
floatingActionButton = {
|
||||
ExtendedFloatingActionButton(
|
||||
modifier = Modifier.padding(8.dp),
|
||||
onClick = { askPermission.value = true },
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.ArrowCircleRight,
|
||||
contentDescription = stringResource(R.string.continue_button),
|
||||
)
|
||||
},
|
||||
text = { Text(text = stringResource(R.string.continue_button)) },
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
-131
@@ -1,131 +0,0 @@
|
||||
package com.anthonyla.paperize.feature.wallpaper.presentation.privacy_screen
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.surfaceColorAtElevation
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.lerp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.anthonyla.paperize.R
|
||||
import me.onebone.toolbar.CollapsingToolbarScaffold
|
||||
import me.onebone.toolbar.ScrollStrategy
|
||||
import me.onebone.toolbar.rememberCollapsingToolbarScaffoldState
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PrivacyScreen(
|
||||
onBackClick: () -> Unit,
|
||||
) {
|
||||
val topBarState = rememberCollapsingToolbarScaffoldState()
|
||||
|
||||
// Collapsing top bar
|
||||
val largeTopAppBarHeight = TopAppBarDefaults.LargeAppBarExpandedHeight
|
||||
val startPadding = 64.dp
|
||||
val endPadding = 16.dp
|
||||
val titleFontScaleStart = 30
|
||||
val titleFontScaleEnd = 21
|
||||
val titleExtraStartPadding = 32.dp
|
||||
val collapseFraction = topBarState.toolbarState.progress
|
||||
val firstPaddingInterpolation = lerp((endPadding * 5 / 4), endPadding, collapseFraction) + titleExtraStartPadding
|
||||
val secondPaddingInterpolation = lerp(startPadding, (endPadding * 5 / 4), collapseFraction)
|
||||
val dynamicPaddingStart = lerp(firstPaddingInterpolation, secondPaddingInterpolation, collapseFraction)
|
||||
val textSize = (titleFontScaleEnd + (titleFontScaleStart - titleFontScaleEnd) * collapseFraction).sp
|
||||
|
||||
Scaffold {
|
||||
CollapsingToolbarScaffold(
|
||||
state = topBarState,
|
||||
modifier = Modifier.fillMaxSize().padding(it),
|
||||
scrollStrategy = ScrollStrategy.ExitUntilCollapsed,
|
||||
toolbar = {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(largeTopAppBarHeight)
|
||||
.background(MaterialTheme.colorScheme.surfaceColorAtElevation(5.dp))
|
||||
.pin()
|
||||
)
|
||||
IconButton(
|
||||
onClick = onBackClick,
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.size(24.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(id = R.string.home_screen)
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = stringResource(id = R.string.privacy_policy),
|
||||
style = MaterialTheme.typography.headlineMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontSize = textSize,
|
||||
modifier = Modifier
|
||||
.road(Alignment.CenterStart, Alignment.BottomStart)
|
||||
.padding(dynamicPaddingStart, 16.dp, 16.dp, 16.dp),
|
||||
)
|
||||
}
|
||||
) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.Start,
|
||||
verticalArrangement = Arrangement.Top,
|
||||
modifier = Modifier
|
||||
.verticalScroll(rememberScrollState())
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 24.dp),
|
||||
) {
|
||||
PrivacyNoticeText()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PrivacyNoticeText() {
|
||||
SectionText(stringResource(R.string.privacy_intro_title), stringResource(R.string.privacy_intro_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_data_collection_title), stringResource(R.string.privacy_data_collection_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_information_usage_title), stringResource(R.string.privacy_information_usage_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_data_security_title), stringResource(R.string.privacy_data_security_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_third_party_services_title), stringResource(R.string.privacy_third_party_services_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_children_privacy_title), stringResource(R.string.privacy_children_privacy_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_changes_notice_title), stringResource(R.string.privacy_changes_notice_content, stringResource(R.string.app_name)))
|
||||
SectionText(stringResource(R.string.privacy_contact_us_title), stringResource(R.string.privacy_contact_us_content, "anthonyyla.dev@gmail.com"))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionText(title: String, content: String) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
|
||||
)
|
||||
Text(
|
||||
text = content,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(bottom = 16.dp)
|
||||
)
|
||||
}
|
||||
Loaded 100 of 281 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user