Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15c9b47131 | ||
|
|
87a69e748f | ||
|
|
3b746ad354 | ||
|
|
797a407f3c | ||
|
|
145899d9a6 | ||
|
|
af72b78a7b | ||
|
|
13367165e6 | ||
|
|
b5f4b52f60 | ||
|
|
434830cfdd | ||
|
|
7c426d5d63 | ||
|
|
d940d9e112 | ||
|
|
153cdbe798 | ||
|
|
063f05bdba | ||
|
|
bc513d666e | ||
|
|
3793aaae65 | ||
|
|
ade1fd4673 | ||
|
|
e2e9d6f4f9 | ||
|
|
9c8fbaf1cc | ||
|
|
8e8be164bd | ||
|
|
e7d5022d02 | ||
|
|
83d1bafcf8 | ||
|
|
2abf5a1804 | ||
|
|
6884559b6b | ||
|
|
8d805ad17d | ||
|
|
5efb272dcb | ||
|
|
456fea3c17 | ||
|
|
8f357f8767 | ||
|
|
73ca207301 | ||
|
|
34031fe89d | ||
|
|
4e14adfc01 | ||
|
|
8e4b0771c8 | ||
|
|
4565893787 | ||
|
|
4ff25cad78 | ||
|
|
6d8a9a9302 | ||
|
|
8d945a63a4 | ||
|
|
c72cdc39a8 | ||
|
|
c93e2f71f1 | ||
|
|
bc26d3c75f | ||
|
|
eadd1952fe | ||
|
|
fd7e69f43a | ||
|
|
26a13bdeb2 | ||
|
|
89dc845f1b | ||
|
|
d0cda6cc36 | ||
|
|
bedfbe7afd | ||
|
|
6f2cb0b995 | ||
|
|
a6aaf55c3c | ||
|
|
f2aa714b17 | ||
|
|
2464907a9c | ||
|
|
304a384cd0 | ||
|
|
5dfb1c6a6c | ||
|
|
9e84837a68 | ||
|
|
600db80998 | ||
|
|
e6a0a607d2 | ||
|
|
0cff2f3a0a | ||
|
|
2e9768c3b5 | ||
|
|
1df9368330 | ||
|
|
7014fc06fe | ||
|
|
464ea59a4c | ||
|
|
dba8d9199d | ||
|
|
9358348549 | ||
|
|
1764f092ae | ||
|
|
8c25786a1c | ||
|
|
f358478355 | ||
|
|
e6ec42c015 | ||
|
|
9e7aabe7a7 | ||
|
|
6396857b66 | ||
|
|
51e498e8e7 | ||
|
|
85a39183f0 | ||
|
|
09ce9e83b4 | ||
|
|
63b0e15a9f | ||
|
|
4013e5e2ac | ||
|
|
69988fa0cc | ||
|
|
fcf92878a3 | ||
|
|
9fa1536c78 | ||
|
|
8a4f6b429d | ||
|
|
53c5e87dca | ||
|
|
9737dd70b6 | ||
|
|
57794f6588 | ||
|
|
dd79170859 | ||
|
|
6f972ef2d5 | ||
|
|
8ec4baac6d | ||
|
|
9bf160f379 | ||
|
|
aaf533535b | ||
|
|
508c5bfd23 | ||
|
|
63e224aa5b | ||
|
|
46d051ab8a | ||
|
|
53659c73f0 | ||
|
|
226260def4 | ||
|
|
cb24374230 | ||
|
|
2db01c9906 | ||
|
|
55f07becd0 | ||
|
|
3740431e96 | ||
|
|
26ef5b63ff | ||
|
|
33360a3e1e | ||
|
|
859d42a7fa | ||
|
|
eac9ba5f7e | ||
|
|
0b7da6f2a9 | ||
|
|
1c725a611f | ||
|
|
763291c5ba | ||
|
|
d0de92a019 | ||
|
|
4acd6fd56f | ||
|
|
3c23179842 | ||
|
|
c6be577be3 | ||
|
|
db3a7972a4 | ||
|
|
dc44eebbac | ||
|
|
88b0ffa95c | ||
|
|
55150e58db | ||
|
|
a02cb73e75 | ||
|
|
7801f06252 | ||
|
|
ce3234f0c2 | ||
|
|
42422b4a48 | ||
|
|
54ffe54d73 | ||
|
|
14651c1cc4 | ||
|
|
f428647995 | ||
|
|
be482fefbc | ||
|
|
0f1db0fb22 | ||
|
|
a292bddbe8 | ||
|
|
2aa4e6960d | ||
|
|
c947b6fc6f | ||
|
|
0385acd539 |
No files matched your search
@@ -27,6 +27,9 @@ on:
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# ===================================================================
|
||||
# JOB: test
|
||||
@@ -38,10 +41,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
@@ -53,14 +56,6 @@ jobs:
|
||||
- name: Run unit tests
|
||||
run: ./gradlew clean test
|
||||
|
||||
- name: Upload test reports
|
||||
uses: actions/upload-artifact@v6
|
||||
if: always()
|
||||
with:
|
||||
name: test-reports
|
||||
path: app/build/reports/tests/
|
||||
retention-days: 7
|
||||
|
||||
# ===================================================================
|
||||
# JOB: build
|
||||
#
|
||||
@@ -75,10 +70,10 @@ jobs:
|
||||
if: github.event_name == 'push'
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
@@ -118,13 +113,19 @@ jobs:
|
||||
fi
|
||||
echo "VERSION_NAME=$VERSION_NAME" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Name APK for distribution
|
||||
shell: bash
|
||||
run: |
|
||||
mv app/build/outputs/apk/release/app-release.apk \
|
||||
"app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk"
|
||||
|
||||
- name: Upload APK as a build artifact
|
||||
# Archives the generated APK with a dynamic, versioned name. This artifact is essential
|
||||
# for passing the APK file to the subsequent `release` job.
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: paperize-${{ steps.get_version.outputs.VERSION_NAME }}
|
||||
path: app/build/outputs/apk/release/paperize-v*.apk
|
||||
path: app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk
|
||||
if-no-files-found: error
|
||||
|
||||
# ===================================================================
|
||||
@@ -144,7 +145,7 @@ jobs:
|
||||
- name: Download signed APK artifact
|
||||
# Downloads the versioned artifact produced by the `build` job. The pattern ensures
|
||||
# it finds the correct artifact regardless of the specific version number.
|
||||
uses: actions/download-artifact@v7
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
pattern: paperize-v*
|
||||
path: ./apk-artifact
|
||||
@@ -153,7 +154,7 @@ jobs:
|
||||
- name: Create Draft Release
|
||||
# Publishes a new release to GitHub. `draft: true` ensures the release is not made
|
||||
# public until it has been manually reviewed and published.
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
|
||||
with:
|
||||
files: ./apk-artifact/paperize-v*.apk
|
||||
draft: true
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
schedule:
|
||||
- cron: "24 6 * * 3"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
jobs:
|
||||
analyze-actions:
|
||||
name: Analyze GitHub Actions
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4
|
||||
with:
|
||||
languages: actions
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4
|
||||
|
||||
analyze-java-kotlin:
|
||||
name: Analyze Java and Kotlin
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@03ad4de0992f5dab5e18fcb136590ce7c4a0ac95 # v5
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
cache: gradle
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4
|
||||
with:
|
||||
languages: java-kotlin
|
||||
build-mode: manual
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Build application for analysis
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4
|
||||
@@ -0,0 +1,65 @@
|
||||
## v4.0.2
|
||||
|
||||
- Reloaded the current live wallpaper at native resolution after fold, unfold,
|
||||
surface-size, and scaling changes without advancing the wallpaper queue.
|
||||
- Made adaptive brightness update the wallpaper already on screen and removed
|
||||
the brightness dip that could occur halfway through live crossfades.
|
||||
- Kept live vignette shading continuous across large images split into multiple
|
||||
GPU texture tiles.
|
||||
- Prevented a delayed effect-slider save from overwriting a switch or other
|
||||
setting changed immediately afterward.
|
||||
- Restored the launcher app shortcut for gesture apps and other launchers, with
|
||||
automatic routing to the configured static or live wallpaper engine.
|
||||
- Added the missing daily album refresh to live schedules and hardened boot
|
||||
recovery so valid jobs are restored without duplicates and stale jobs are removed.
|
||||
- Removed two unused legacy serialization and document-file dependencies from
|
||||
the release package.
|
||||
- Expanded device coverage for every static effect and verified synchronized,
|
||||
independent, manual, live, and reboot scheduling paths.
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.0.1...v4.0.2
|
||||
|
||||
## v4.0.1
|
||||
|
||||
- Restored native static FILL scrolling so wide wallpapers move between their real
|
||||
left and right edges without synthetic launcher-sized overflow.
|
||||
- Added independent brightness, blur, vignette, and grayscale controls for home
|
||||
and lock screens, including when both screens share one album and schedule.
|
||||
- Refreshed folder-backed albums whenever Paperize returns to the foreground so
|
||||
added and removed files appear without restarting the app.
|
||||
- Improved foldable sizing on Android 17 by including inactive built-in panels
|
||||
while excluding external displays.
|
||||
- Made wallpaper changes commit queue and current-wallpaper state only after
|
||||
Android accepts the bitmap, with rejected changes restored for retry.
|
||||
- Corrected live wallpaper parallax enablement, intensity, edge traversal, and
|
||||
launcher-offset clamping, and clarified that it responds to home-page swipes.
|
||||
- Added device regressions for EXIF rotation, static FILL overflow, and folded
|
||||
display sizing, plus focused queue and live-renderer unit coverage.
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v4.0.0...v4.0.1
|
||||
|
||||
## v4.0.0
|
||||
|
||||
- Completely rewrote Paperize for Android 12 and newer with a modern Compose interface.
|
||||
- Added static and live wallpaper modes with independent home and lock screen settings.
|
||||
- Added scaling, blur, darken, vignette, grayscale, adaptive brightness, parallax,
|
||||
double-tap, shuffle, interval, and manual wallpaper controls.
|
||||
- Added current-wallpaper previews, Quick Settings support, and progress indicators
|
||||
for large wallpaper and folder imports.
|
||||
- Improved folder scanning, queue refreshes, bitmap memory usage, scheduling, and
|
||||
wallpaper rendering reliability.
|
||||
- Fixed home and lock screen synchronization, foldable display sizing, EXIF rotation,
|
||||
and FIT, FILL, STRETCH, and NONE scaling behavior.
|
||||
- Removed the obsolete all-files storage permission in favor of Android's scoped
|
||||
document access.
|
||||
- Updated dependencies and repaired the release workflow for signed, versioned APKs.
|
||||
|
||||
**Upgrade note:** Updating from Paperize 3 resets local albums and settings once
|
||||
because Paperize 4 uses a new storage model. Users of the 4.0.0 alpha are not reset
|
||||
again.
|
||||
|
||||
## New Contributors
|
||||
|
||||
* @gpunto made their first contribution in https://github.com/Anthonyy232/Paperize/pull/415
|
||||
|
||||
**Full Changelog**: https://github.com/Anthonyy232/Paperize/compare/v3.2.1...v4.0.0
|
||||
@@ -72,8 +72,8 @@ Help translate Paperize into your language! Currently, most translations are pro
|
||||
| Requirement | Version |
|
||||
|-------------|---------|
|
||||
| Java | 17 |
|
||||
| Android Gradle Plugin | 8.7.0+ |
|
||||
| Gradle | 9.2.1 |
|
||||
| Android Gradle Plugin | 9.1.0 |
|
||||
| Gradle | 9.4.1 |
|
||||
| Minimum SDK | 31 (Android 12) |
|
||||
| Target SDK | 36 |
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.androidApplication)
|
||||
alias(libs.plugins.kotlinAndroid)
|
||||
alias(libs.plugins.kotlinCompose)
|
||||
alias(libs.plugins.hiltAndroid)
|
||||
alias(libs.plugins.ksp)
|
||||
@@ -31,8 +32,8 @@ android {
|
||||
applicationId = "com.anthonyla.paperize"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 50
|
||||
versionName = "4.0.0"
|
||||
versionCode = 53
|
||||
versionName = "4.0.2"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
@@ -57,12 +58,6 @@ android {
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
viewBinding = true
|
||||
@@ -74,25 +69,22 @@ android {
|
||||
generateLocaleConfig = true
|
||||
}
|
||||
|
||||
buildToolsVersion = "35.0.1"
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
}
|
||||
}
|
||||
|
||||
applicationVariants.all {
|
||||
this.outputs
|
||||
.map { it as com.android.build.gradle.internal.api.ApkVariantOutputImpl }
|
||||
.forEach { output ->
|
||||
val apkName = "paperize-v${this.versionName}.apk"
|
||||
output.outputFileName = apkName
|
||||
}
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.process)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.ui)
|
||||
@@ -113,7 +105,6 @@ dependencies {
|
||||
implementation(libs.androidx.animation)
|
||||
implementation(libs.androidx.core.splashscreen)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
implementation(libs.gson)
|
||||
implementation(libs.androidx.documentfile)
|
||||
implementation(libs.androidx.exifinterface)
|
||||
implementation(libs.zoomable)
|
||||
@@ -128,9 +119,11 @@ dependencies {
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.mockk)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
androidTestImplementation(platform(libs.androidx.compose.bom))
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(libs.androidx.ui.test.junit4)
|
||||
debugImplementation(platform(libs.androidx.compose.bom))
|
||||
debugImplementation(libs.androidx.ui.tooling)
|
||||
debugImplementation(libs.androidx.ui.test.manifest)
|
||||
implementation(libs.hilt.android)
|
||||
@@ -139,7 +132,6 @@ dependencies {
|
||||
implementation(libs.androidx.room.runtime)
|
||||
ksp(libs.androidx.room.compiler)
|
||||
implementation(libs.androidx.room.ktx)
|
||||
implementation(libs.dfc)
|
||||
implementation (libs.kotlinx.serialization.json)
|
||||
implementation(libs.toolbar.compose)
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,6 @@
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
-keepattributes Signature
|
||||
-keep class com.google.gson.reflect.TypeToken { *; }
|
||||
-keep class * extends com.google.gson.reflect.TypeToken
|
||||
-keep class kotlin.coroutines.Continuation
|
||||
-keep class androidx.datastore.*.** {*;}
|
||||
|
||||
@@ -61,4 +59,4 @@
|
||||
# Keep Room database
|
||||
-keep class * extends androidx.room.RoomDatabase
|
||||
-keep @androidx.room.Entity class *
|
||||
-dontwarn androidx.room.paging.**
|
||||
-dontwarn androidx.room.paging.**
|
||||
@@ -0,0 +1,209 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import java.io.File
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class WallpaperUtilInstrumentedTest {
|
||||
|
||||
private val context = ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
private val files = mutableListOf<File>()
|
||||
|
||||
@After
|
||||
fun cleanUp() {
|
||||
files.forEach(File::delete)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun imageDecoderAppliesExifRotation() {
|
||||
val image = createJpeg(width = 40, height = 20)
|
||||
ExifInterface(image).apply {
|
||||
setAttribute(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_ROTATE_90.toString()
|
||||
)
|
||||
saveAttributes()
|
||||
}
|
||||
|
||||
val result = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 20,
|
||||
height = 40,
|
||||
scaling = ScalingType.STRETCH
|
||||
)
|
||||
|
||||
assertNotNull(result)
|
||||
assertEquals(20, result?.width)
|
||||
assertEquals(40, result?.height)
|
||||
result?.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticFillRetainsWideSourceOverflow() {
|
||||
val image = createJpeg(width = 400, height = 200)
|
||||
|
||||
val scrolling = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 100,
|
||||
height = 200,
|
||||
scaling = ScalingType.FILL,
|
||||
preserveSourceOverflow = true
|
||||
)
|
||||
val exactCanvas = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 100,
|
||||
height = 200,
|
||||
scaling = ScalingType.FILL,
|
||||
preserveSourceOverflow = false
|
||||
)
|
||||
|
||||
assertEquals(400, scrolling?.width)
|
||||
assertEquals(200, scrolling?.height)
|
||||
assertEquals(100, exactCanvas?.width)
|
||||
assertEquals(200, exactCanvas?.height)
|
||||
scrolling?.recycle()
|
||||
exactCanvas?.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun android17FoldableSizingIncludesInactiveBuiltInPanel() {
|
||||
assumeTrue(Build.VERSION.SDK_INT >= 37)
|
||||
val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
val builtInDisplays = displayManager.getDisplays(
|
||||
"android.hardware.display.category.BUILT_IN_DISPLAYS"
|
||||
)
|
||||
assertTrue("Expected both foldable panels", builtInDisplays.size >= 2)
|
||||
|
||||
val expected = selectLargestDisplayDimensions(
|
||||
builtInDisplays.flatMap { display ->
|
||||
display.supportedModes.map { mode ->
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
}
|
||||
)
|
||||
val actual = ScreenMetricsCompat.getScreenSize(context)
|
||||
|
||||
assertNotNull(expected)
|
||||
assertEquals(expected?.first, actual.width)
|
||||
assertEquals(expected?.second, actual.height)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun disabledStaticEffectsLeaveBitmapUntouched() {
|
||||
val source = mutableBitmap(32, 32, Color.rgb(240, 80, 20))
|
||||
|
||||
val result = processBitmap(
|
||||
source = source,
|
||||
enableDarken = false,
|
||||
darkenPercent = 100,
|
||||
enableBlur = false,
|
||||
blurPercent = 100,
|
||||
enableVignette = false,
|
||||
vignettePercent = 100,
|
||||
enableGrayscale = false,
|
||||
grayscalePercent = 100
|
||||
)
|
||||
|
||||
assertSame(source, result)
|
||||
assertEquals(Color.rgb(240, 80, 20), result.getPixel(16, 16))
|
||||
result.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticDarkenAndGrayscaleEffectsChangePixels() {
|
||||
val white = mutableBitmap(32, 32, Color.WHITE)
|
||||
val darkened = processBitmap(
|
||||
source = white,
|
||||
enableDarken = true,
|
||||
darkenPercent = 100
|
||||
)
|
||||
assertTrue(Color.red(darkened.getPixel(16, 16)) <= 2)
|
||||
if (darkened !== white) white.recycle()
|
||||
darkened.recycle()
|
||||
|
||||
val red = mutableBitmap(32, 32, Color.RED)
|
||||
val grayscale = processBitmap(
|
||||
source = red,
|
||||
enableGrayscale = true,
|
||||
grayscalePercent = 100
|
||||
)
|
||||
val grayPixel = grayscale.getPixel(16, 16)
|
||||
assertTrue(kotlin.math.abs(Color.red(grayPixel) - Color.green(grayPixel)) <= 2)
|
||||
assertTrue(kotlin.math.abs(Color.green(grayPixel) - Color.blue(grayPixel)) <= 2)
|
||||
if (grayscale !== red) red.recycle()
|
||||
grayscale.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticVignetteDarkensEdgesMoreThanCenter() {
|
||||
val source = mutableBitmap(96, 96, Color.WHITE)
|
||||
val result = processBitmap(
|
||||
source = source,
|
||||
enableVignette = true,
|
||||
vignettePercent = 75
|
||||
)
|
||||
|
||||
val center = Color.red(result.getPixel(48, 48))
|
||||
val corner = Color.red(result.getPixel(0, 0))
|
||||
assertTrue("Expected vignette corner ($corner) below center ($center)", corner < center)
|
||||
if (result !== source) source.recycle()
|
||||
result.recycle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun staticBlurSoftensSharpBoundary() {
|
||||
val source = Bitmap.createBitmap(96, 96, Bitmap.Config.ARGB_8888)
|
||||
for (y in 0 until source.height) {
|
||||
for (x in 0 until source.width) {
|
||||
source.setPixel(x, y, if (x < 48) Color.BLACK else Color.WHITE)
|
||||
}
|
||||
}
|
||||
|
||||
val result = processBitmap(
|
||||
source = source,
|
||||
enableBlur = true,
|
||||
blurPercent = 60
|
||||
)
|
||||
|
||||
val boundary = Color.red(result.getPixel(48, 48))
|
||||
assertTrue("Expected blurred boundary, got $boundary", boundary in 2..253)
|
||||
if (result !== source) source.recycle()
|
||||
result.recycle()
|
||||
}
|
||||
|
||||
private fun mutableBitmap(width: Int, height: Int, color: Int): Bitmap =
|
||||
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
|
||||
eraseColor(color)
|
||||
}
|
||||
|
||||
private fun createJpeg(width: Int, height: Int): File {
|
||||
val file = File.createTempFile("paperize-test-", ".jpg", context.cacheDir)
|
||||
files += file
|
||||
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
bitmap.eraseColor(Color.MAGENTA)
|
||||
file.outputStream().use { output ->
|
||||
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 95, output))
|
||||
}
|
||||
bitmap.recycle()
|
||||
return file
|
||||
}
|
||||
}
|
||||
@@ -11,10 +11,6 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
|
||||
<!-- Features -->
|
||||
<uses-feature
|
||||
android:name="android.software.wallpaper"
|
||||
@@ -25,9 +21,9 @@
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="false"
|
||||
android:icon="@mipmap/app_icon"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/app_icon_round"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Paperize">
|
||||
|
||||
@@ -48,13 +44,24 @@
|
||||
android:name=".presentation.MainActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="uiMode|density|orientation|screenSize|screenLayout|keyboardHidden|keyboard"
|
||||
android:theme="@style/Theme.Paperize">
|
||||
android:theme="@style/Theme.App.Starting">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.app.shortcuts"
|
||||
android:resource="@xml/shortcuts" />
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".service.shortcut.WallpaperShortcutActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="false"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity=""
|
||||
android:theme="@android:style/Theme.NoDisplay" />
|
||||
|
||||
<service
|
||||
android:name=".service.wallpaper.WallpaperChangeService"
|
||||
android:enabled="true"
|
||||
@@ -76,7 +83,7 @@
|
||||
<service
|
||||
android:name=".service.tile.WallpaperTileService"
|
||||
android:exported="true"
|
||||
android:icon="@drawable/ic_launcher_foreground"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter>
|
||||
|
||||
|
After Width: | Height: | Size: 44 KiB |
@@ -4,15 +4,13 @@ import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import androidx.hilt.work.HiltWorkerFactory
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
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 com.anthonyla.paperize.core.util.DataResetManager
|
||||
import com.anthonyla.paperize.service.worker.AlbumRefreshScheduler
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import javax.inject.Inject
|
||||
|
||||
@@ -23,13 +21,13 @@ import javax.inject.Inject
|
||||
* Implements Configuration.Provider for WorkManager with Hilt support
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class PaperizeApplication : Application(), Configuration.Provider {
|
||||
class PaperizeApplication : Application(), Configuration.Provider, DefaultLifecycleObserver {
|
||||
|
||||
@Inject
|
||||
lateinit var workerFactory: HiltWorkerFactory
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
super<Application>.onCreate()
|
||||
|
||||
// Perform one-time data reset for major version upgrades (e.g., v3 -> v4)
|
||||
// Must run before any other initialization that accesses DB/preferences
|
||||
@@ -38,8 +36,9 @@ class PaperizeApplication : Application(), Configuration.Provider {
|
||||
// Create notification channel (minSdk is 31, so always supported)
|
||||
createNotificationChannel()
|
||||
|
||||
// Trigger album refresh on app cold start to validate and update all albums
|
||||
refreshAlbumsOnStartup()
|
||||
// Process lifecycle distinguishes real background/foreground transitions from activity
|
||||
// recreation, so folder-backed albums are refreshed whenever the user returns to the app.
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
|
||||
}
|
||||
|
||||
override val workManagerConfiguration: Configuration
|
||||
@@ -61,31 +60,7 @@ class PaperizeApplication : Application(), Configuration.Provider {
|
||||
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
|
||||
)
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
AlbumRefreshScheduler.enqueue(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Exception thrown when an album has no wallpapers available
|
||||
*/
|
||||
class EmptyAlbumException(message: String) : Exception(message)
|
||||
|
||||
/**
|
||||
* Exception thrown when no valid wallpaper can be found after retries
|
||||
*/
|
||||
class NoValidWallpaperException(message: String) : Exception(message)
|
||||
@@ -6,7 +6,7 @@ package com.anthonyla.paperize.core.constants
|
||||
object Constants {
|
||||
// Database
|
||||
const val DATABASE_NAME = "paperize_database"
|
||||
const val DATABASE_VERSION = 2 // v2: Added mediaType and crop fields to WallpaperEntity
|
||||
const val DATABASE_VERSION = 4 // v4: Removed unused cropOffsetX/Y/Scale columns from wallpapers table
|
||||
|
||||
// DataStore
|
||||
const val PREFERENCES_NAME = "paperize_preferences"
|
||||
@@ -17,6 +17,7 @@ object Constants {
|
||||
|
||||
// Services
|
||||
const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER"
|
||||
const val ACTION_REAPPLY_EFFECTS = "com.anthonyla.paperize.ACTION_REAPPLY_EFFECTS"
|
||||
const val ACTION_RELOAD_WALLPAPER = "com.anthonyla.paperize.ACTION_RELOAD_WALLPAPER"
|
||||
|
||||
// WorkManager
|
||||
@@ -87,7 +88,7 @@ object Constants {
|
||||
|
||||
// Vignette effect
|
||||
const val VIGNETTE_DIVISOR = 150f // Radius calculation divisor
|
||||
const val VIGNETTE_MIN_RADIUS = 0.1f // Minimum vignette radius
|
||||
const val VIGNETTE_MIN_RADIUS = 1f // Minimum vignette radius (guards against zero-radius RadialGradient crash)
|
||||
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
|
||||
@@ -117,6 +118,7 @@ object Constants {
|
||||
const val PERCENTAGE_DIVISOR = 100f
|
||||
const val GL_ES_VERSION = 2
|
||||
const val SURFACE_POLL_INTERVAL_MS = 50L
|
||||
const val SURFACE_WAIT_TIMEOUT_MS = 1000L // Max wait for GL surface dimensions before falling back to display metrics
|
||||
|
||||
// Wallpaper loading
|
||||
const val MAX_WALLPAPER_LOAD_RETRIES = 10
|
||||
@@ -185,7 +187,7 @@ object PreferenceKeys {
|
||||
const val LIVE_ENABLE_GRAYSCALE = "live_enable_grayscale"
|
||||
const val LIVE_GRAYSCALE = "live_grayscale"
|
||||
const val LIVE_ENABLE_DOUBLE_TAP = "live_enable_double_tap"
|
||||
const val LIVE_ENABLE_CHANGE_ON_SCREEN_ON = "live_enable_change_on_screen_on"
|
||||
const val LIVE_ENABLE_CHANGE_ON_SCREEN_OFF = "live_enable_change_on_screen_off"
|
||||
const val LIVE_ENABLE_PARALLAX = "live_enable_parallax"
|
||||
const val LIVE_PARALLAX_INTENSITY = "live_parallax_intensity"
|
||||
|
||||
@@ -194,10 +196,6 @@ object PreferenceKeys {
|
||||
const val LOCK_SCALING_TYPE = "lock_scaling_type"
|
||||
const val LIVE_SCALING_TYPE = "live_scaling_type"
|
||||
|
||||
// Current wallpapers
|
||||
const val CURRENT_HOME_WALLPAPER_ID = "current_home_wallpaper_id"
|
||||
const val CURRENT_LOCK_WALLPAPER_ID = "current_lock_wallpaper_id"
|
||||
|
||||
// Behavior
|
||||
const val ADAPTIVE_BRIGHTNESS = "adaptive_brightness"
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.datastore.PreferencesManager
|
||||
@@ -70,6 +71,11 @@ object AppModule {
|
||||
fun provideWallpaperQueueDao(database: PaperizeDatabase): WallpaperQueueDao =
|
||||
database.wallpaperQueueDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperCurrentDao(database: PaperizeDatabase): WallpaperCurrentDao =
|
||||
database.wallpaperCurrentDao()
|
||||
|
||||
/**
|
||||
* Provide PreferencesManager
|
||||
*/
|
||||
@@ -97,8 +103,9 @@ object AppModule {
|
||||
fun provideWallpaperRepository(
|
||||
@ApplicationContext context: Context,
|
||||
wallpaperDao: WallpaperDao,
|
||||
wallpaperQueueDao: WallpaperQueueDao
|
||||
): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao)
|
||||
wallpaperQueueDao: WallpaperQueueDao,
|
||||
wallpaperCurrentDao: WallpaperCurrentDao
|
||||
): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao, wallpaperCurrentDao)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import androidx.core.graphics.get
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
@@ -23,18 +22,27 @@ object BrightnessCalculator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate brightness estimate of bitmap (0.0 - 1.0)
|
||||
* Uses luminance calculation based on RGB values.
|
||||
* Calculate brightness estimate of bitmap (0.0 - 1.0).
|
||||
*
|
||||
* Reads one sampled row at a time using [Bitmap.getPixels] so the entire
|
||||
* sample set is fetched with (height / sampleSize) JNI calls instead of
|
||||
* (width / sampleSize) × (height / sampleSize) individual pixel lookups.
|
||||
* A reusable row buffer keeps allocations to one IntArray(width).
|
||||
*/
|
||||
fun calculateBitmapBrightness(bitmap: Bitmap): Float {
|
||||
val sampleSize = Constants.BRIGHTNESS_SAMPLE_SIZE
|
||||
val w = bitmap.width
|
||||
val h = bitmap.height
|
||||
if (w <= 0 || h <= 0) return Constants.DEFAULT_BRIGHTNESS
|
||||
|
||||
val rowBuffer = IntArray(w)
|
||||
var totalLuminance = 0.0
|
||||
var pixelCount = 0
|
||||
|
||||
for (x in 0 until bitmap.width step sampleSize) {
|
||||
for (y in 0 until bitmap.height step sampleSize) {
|
||||
val pixel = bitmap[x, y]
|
||||
totalLuminance += calculateLuminance(pixel)
|
||||
for (y in 0 until h step sampleSize) {
|
||||
bitmap.getPixels(rowBuffer, 0, w, 0, y, w, 1)
|
||||
for (x in 0 until w step sampleSize) {
|
||||
totalLuminance += calculateLuminance(rowBuffer[x])
|
||||
pixelCount++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,9 @@ package com.anthonyla.paperize.core.util
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
@@ -34,36 +36,95 @@ fun Uri.getFileName(context: Context): String? {
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan a folder URI and return all image file URIs
|
||||
* One image file discovered while scanning a folder tree.
|
||||
*
|
||||
* [name] and [lastModified] are read from the same cursor row as [uri], so callers
|
||||
* do not need a follow-up per-file query to obtain them.
|
||||
*/
|
||||
fun Uri.scanFolderForImages(context: Context): List<Uri> {
|
||||
val documentFile = DocumentFile.fromTreeUri(context, this) ?: return emptyList()
|
||||
if (!documentFile.isDirectory) return emptyList()
|
||||
data class ScannedImage(
|
||||
val uri: Uri,
|
||||
val name: String,
|
||||
val lastModified: Long
|
||||
)
|
||||
|
||||
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 -> {
|
||||
imageUris.add(file.uri)
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Recursively scan a tree [Uri] for image files.
|
||||
*
|
||||
* Uses a single [DocumentsContract] cursor query per directory instead of
|
||||
* [DocumentFile.listFiles], which issues a separate IPC round-trip for every file and
|
||||
* for every attribute access (name, isDirectory, lastModified). For folders with tens of
|
||||
* thousands of files that difference is the dominant cost. Directories are traversed
|
||||
* iteratively to avoid deep-recursion stack overflow on heavily nested trees.
|
||||
*
|
||||
* Returned URIs are built from the same tree document id used by [DocumentFile], so they
|
||||
* are byte-for-byte identical to the previous implementation and remain stable across the app.
|
||||
*
|
||||
* [onProgress] is invoked with the running number of images found, throttled to roughly once
|
||||
* per [PROGRESS_REPORT_INTERVAL] discoveries so callers can show a live count without flooding.
|
||||
*/
|
||||
fun Uri.scanFolderImages(context: Context, onProgress: ((found: Int) -> Unit)? = null): List<ScannedImage> {
|
||||
val rootDocumentId = try {
|
||||
DocumentsContract.getTreeDocumentId(this)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
return emptyList() // Not a tree URI
|
||||
}
|
||||
|
||||
scanDirectory(documentFile)
|
||||
return imageUris.sortedBy { it.toString() } // Sort for consistency
|
||||
val projection = arrayOf(
|
||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED
|
||||
)
|
||||
|
||||
val results = mutableListOf<ScannedImage>()
|
||||
var lastReported = 0
|
||||
val pendingDirs = ArrayDeque<String>()
|
||||
pendingDirs.addLast(rootDocumentId)
|
||||
|
||||
while (pendingDirs.isNotEmpty()) {
|
||||
val parentDocumentId = pendingDirs.removeLast()
|
||||
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(this, parentDocumentId)
|
||||
try {
|
||||
context.contentResolver.query(childrenUri, projection, null, null, null)?.use { cursor ->
|
||||
val idColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
|
||||
val nameColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
||||
val mimeColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
|
||||
val modifiedColumn = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
||||
|
||||
while (cursor.moveToNext()) {
|
||||
val documentId = cursor.getString(idColumn) ?: continue
|
||||
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
|
||||
pendingDirs.addLast(documentId)
|
||||
} else {
|
||||
val name = cursor.getString(nameColumn) ?: continue
|
||||
val extension = name.substringAfterLast('.', "").lowercase()
|
||||
if (extension in Constants.SUPPORTED_IMAGE_EXTENSIONS) {
|
||||
results.add(
|
||||
ScannedImage(
|
||||
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId),
|
||||
name = name,
|
||||
lastModified = if (cursor.isNull(modifiedColumn)) 0L else cursor.getLong(modifiedColumn)
|
||||
)
|
||||
)
|
||||
if (onProgress != null && results.size - lastReported >= PROGRESS_REPORT_INTERVAL) {
|
||||
lastReported = results.size
|
||||
onProgress(results.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Skip directories that can't be read and continue with the rest of the tree.
|
||||
}
|
||||
}
|
||||
onProgress?.invoke(results.size)
|
||||
return results
|
||||
}
|
||||
|
||||
/** Report scan progress at most once per this many discovered images. */
|
||||
private const val PROGRESS_REPORT_INTERVAL = 512
|
||||
|
||||
/**
|
||||
* UUID generation
|
||||
*/
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import androidx.core.content.ContextCompat
|
||||
|
||||
object PermissionUtil {
|
||||
@@ -20,14 +19,4 @@ object PermissionUtil {
|
||||
}
|
||||
}
|
||||
|
||||
fun hasStoragePermission(): Boolean {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
Environment.isExternalStorageManager()
|
||||
} else {
|
||||
// For older versions, we might check READ_EXTERNAL_STORAGE, but the app flow seems to rely on MANAGE for All Files Access
|
||||
// Stick to the existing logic which uses Environment.isExternalStorageManager()
|
||||
Environment.isExternalStorageManager()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -27,27 +27,6 @@ object QueueBuilder {
|
||||
return wallpaperIds.shuffled()
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if queue positions need normalization
|
||||
* Positions need normalization if they have gaps (e.g., 0, 2, 4 instead of 0, 1, 2)
|
||||
* @param positions Current queue positions
|
||||
* @return True if normalization is needed, false otherwise
|
||||
*/
|
||||
fun needsNormalization(positions: List<Int>): Boolean {
|
||||
if (positions.isEmpty()) return false
|
||||
val sorted = positions.sorted()
|
||||
return sorted.indices.any { sorted[it] != it }
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize queue positions to be sequential starting from 0
|
||||
* @param positions Current queue positions (may have gaps)
|
||||
* @return Normalized positions (0, 1, 2, ...)
|
||||
*/
|
||||
fun normalizePositions(positions: List<Int>): List<Int> {
|
||||
return positions.indices.toList()
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge existing queue with new wallpapers while preserving existing order
|
||||
* Used when new wallpapers are added to an album during shuffle mode
|
||||
@@ -59,13 +38,10 @@ object QueueBuilder {
|
||||
existingQueueIds: List<String>,
|
||||
allWallpaperIds: List<String>
|
||||
): List<String> {
|
||||
// Filter existing queue to only include IDs that still exist
|
||||
val existingValid = existingQueueIds.filter { it in allWallpaperIds }
|
||||
|
||||
// Find new wallpapers not in existing queue
|
||||
val newWallpaperIds = allWallpaperIds.filter { it !in existingQueueIds }
|
||||
|
||||
// Return existing order with new wallpapers shuffled at the end
|
||||
val allSet = allWallpaperIds.toHashSet()
|
||||
val existingSet = existingQueueIds.toHashSet()
|
||||
val existingValid = existingQueueIds.filter { it in allSet }
|
||||
val newWallpaperIds = allWallpaperIds.filter { it !in existingSet }
|
||||
return existingValid + newWallpaperIds.shuffled()
|
||||
}
|
||||
|
||||
@@ -77,8 +53,10 @@ object QueueBuilder {
|
||||
existingQueueIds: List<String>,
|
||||
allWallpaperIds: List<String>
|
||||
): List<String> {
|
||||
val existingValid = existingQueueIds.filter { it in allWallpaperIds }
|
||||
val newWallpaperIds = allWallpaperIds.filter { it !in existingQueueIds }
|
||||
val allSet = allWallpaperIds.toHashSet()
|
||||
val existingSet = existingQueueIds.toHashSet()
|
||||
val existingValid = existingQueueIds.filter { it in allSet }
|
||||
val newWallpaperIds = allWallpaperIds.filter { it !in existingSet }
|
||||
return existingValid + newWallpaperIds
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.graphics.Bitmap
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Apply a bitmap and treat WallpaperManager's documented zero return value as a failure.
|
||||
*/
|
||||
fun WallpaperManager.setBitmapChecked(bitmap: Bitmap, which: Int): Int {
|
||||
check(bitmap.width > 0 && bitmap.height > 0) {
|
||||
"Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}"
|
||||
}
|
||||
check(!bitmap.isRecycled) { "Bitmap has been recycled" }
|
||||
|
||||
val wallpaperId = setBitmap(bitmap, null, true, which)
|
||||
requireWallpaperSetSucceeded(wallpaperId)
|
||||
return wallpaperId
|
||||
}
|
||||
|
||||
internal fun requireWallpaperSetSucceeded(wallpaperId: Int) {
|
||||
if (wallpaperId == 0) {
|
||||
throw IOException("WallpaperManager rejected the wallpaper")
|
||||
}
|
||||
}
|
||||
@@ -173,7 +173,11 @@ object WallpaperSorter {
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByName(folder.wallpapers, ascending)
|
||||
folder.copy(wallpapers = applyDisplayOrder(sortedWallpapers))
|
||||
val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
|
||||
folder.copy(
|
||||
wallpapers = orderedWallpapers,
|
||||
coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
@@ -200,7 +204,11 @@ object WallpaperSorter {
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByDateModified(folder.wallpapers, ascending)
|
||||
folder.copy(wallpapers = applyDisplayOrder(sortedWallpapers))
|
||||
val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
|
||||
folder.copy(
|
||||
wallpapers = orderedWallpapers,
|
||||
coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
|
||||
@@ -15,18 +15,23 @@ import android.graphics.ImageDecoder
|
||||
import android.graphics.Matrix
|
||||
import android.graphics.Paint
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.PorterDuff
|
||||
import android.graphics.PorterDuffXfermode
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.RenderEffect
|
||||
import android.graphics.RenderNode
|
||||
import android.graphics.Shader
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.HardwareBuffer
|
||||
import android.media.ImageReader
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import android.util.Size
|
||||
import android.view.Display
|
||||
import android.view.WindowManager
|
||||
import android.view.WindowMetrics
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import androidx.core.graphics.scale
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
@@ -43,44 +48,8 @@ import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
*/
|
||||
|
||||
private const val TAG = "WallpaperUtil"
|
||||
|
||||
/**
|
||||
* Get the dimensions of the image from the URI
|
||||
*/
|
||||
fun Uri.getImageDimensions(context: Context): Size? {
|
||||
// Try EXIF first
|
||||
try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val exif = ExifInterface(inputStream)
|
||||
val width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, 0)
|
||||
val height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, 0)
|
||||
if (width > 0 && height > 0) {
|
||||
return Size(width, height)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Error reading EXIF dimensions for $this, falling back: $e")
|
||||
}
|
||||
|
||||
// Fallback to BitmapFactory
|
||||
try {
|
||||
context.contentResolver.openInputStream(this)?.use { inputStream ->
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
if (options.outWidth > 0 && options.outHeight > 0) {
|
||||
return Size(options.outWidth, options.outHeight)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error getting image dimensions with BitmapFactory for $this: $e")
|
||||
return null
|
||||
}
|
||||
|
||||
Log.w(TAG, "Could not get image dimensions for $this")
|
||||
return null
|
||||
}
|
||||
private const val BUILT_IN_DISPLAY_CATEGORY =
|
||||
"android.hardware.display.category.BUILT_IN_DISPLAYS"
|
||||
|
||||
/**
|
||||
* Get EXIF orientation from URI
|
||||
@@ -145,9 +114,12 @@ fun calculateInSampleSize(imageSize: Size, width: Int, height: Int): Int {
|
||||
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)
|
||||
// Integer division (floor) ensures inSampleSize is never larger than needed,
|
||||
// guaranteeing the decoded bitmap is at least as wide/tall as the target.
|
||||
// fastRoundToInt() can round UP, producing a bitmap smaller than the target.
|
||||
val heightRatio = imageSize.height / height
|
||||
val widthRatio = imageSize.width / width
|
||||
return minOf(heightRatio, widthRatio).coerceAtLeast(1)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
@@ -159,10 +131,62 @@ 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())
|
||||
val candidates = buildList {
|
||||
add(metrics.bounds.width() to metrics.bounds.height())
|
||||
|
||||
// Foldables may expose the cover and inner panels as separate internal displays.
|
||||
// Include every supported internal-display mode so a wallpaper changed while folded
|
||||
// is still rendered sharply enough for the larger unfolded panel. External displays
|
||||
// are deliberately excluded so a connected monitor cannot inflate wallpaper memory.
|
||||
val displayManager = context.getSystemService(DisplayManager::class.java)
|
||||
val builtInDisplays = displayManager
|
||||
?.getDisplays(BUILT_IN_DISPLAY_CATEGORY)
|
||||
.orEmpty()
|
||||
val candidateDisplays = if (builtInDisplays.isNotEmpty()) {
|
||||
// Android 17+ returns all built-in panels, including currently inactive panels.
|
||||
builtInDisplays.asSequence()
|
||||
} else {
|
||||
// Compatibility fallback for releases where the built-in category is unknown.
|
||||
// Exclude presentation and app-owned virtual displays.
|
||||
displayManager?.displays
|
||||
?.asSequence()
|
||||
?.filter { display ->
|
||||
display.flags and Display.FLAG_PRESENTATION == 0 &&
|
||||
display.flags and Display.FLAG_PRIVATE == 0
|
||||
}
|
||||
.orEmpty()
|
||||
}
|
||||
candidateDisplays
|
||||
.flatMap { display ->
|
||||
display.supportedModes.asSequence().map { mode ->
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
}
|
||||
.forEach(::add)
|
||||
}
|
||||
val largest = selectLargestDisplayDimensions(candidates)
|
||||
return largest?.let { Size(it.first, it.second) }
|
||||
?: Size(metrics.bounds.width(), metrics.bounds.height())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the highest-resolution display dimensions.
|
||||
*
|
||||
* Kept platform-independent so foldable sizing behavior is covered by local unit tests.
|
||||
*/
|
||||
internal fun selectLargestDisplayDimensions(
|
||||
candidates: Iterable<Pair<Int, Int>>
|
||||
): Pair<Int, Int>? = candidates
|
||||
.filter { (width, height) -> width > 0 && height > 0 }
|
||||
.maxWithOrNull(
|
||||
compareBy<Pair<Int, Int>>(
|
||||
{ (width, height) -> width.toLong() * height.toLong() },
|
||||
{ (width, height) -> maxOf(width, height) },
|
||||
{ (width, height) -> minOf(width, height) }
|
||||
)
|
||||
)
|
||||
|
||||
/**
|
||||
* Get device screen size with orientation
|
||||
*/
|
||||
@@ -177,72 +201,260 @@ fun getDeviceScreenSize(context: Context): Size {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a bitmap from a URI that is scaled down to the device's screen size
|
||||
* Now with EXIF orientation support
|
||||
* Get the target render size for a wallpaper bitmap.
|
||||
*
|
||||
* For FIT/STRETCH/NONE on HOME (and BOTH), the launcher may request a wider canvas than the
|
||||
* physical screen to support horizontal scrolling across multiple pages. Rendering those modes
|
||||
* to the exact desired canvas prevents WallpaperManager from rescaling them into FILL.
|
||||
*
|
||||
* FILL deliberately uses one physical screen as its minimum viewport and keeps source overflow.
|
||||
* That restores Android's native static-wallpaper behavior: the launcher can traverse a wide
|
||||
* image, but cannot manufacture scroll area beyond the image's real edge.
|
||||
*
|
||||
* LOCK screen wallpapers are not parallax-scrolled, so the physical screen size is correct.
|
||||
* LIVE wallpapers are rendered by GLRenderer directly; they do not go through this path.
|
||||
*/
|
||||
fun getWallpaperRenderSize(
|
||||
context: Context,
|
||||
screenType: com.anthonyla.paperize.core.ScreenType,
|
||||
scaling: ScalingType = ScalingType.FIT
|
||||
): Size {
|
||||
val screen = getDeviceScreenSize(context)
|
||||
return when (screenType) {
|
||||
com.anthonyla.paperize.core.ScreenType.HOME,
|
||||
com.anthonyla.paperize.core.ScreenType.BOTH -> {
|
||||
if (usesLauncherManagedScrolling(screenType, scaling)) {
|
||||
return screen
|
||||
}
|
||||
val wm = WallpaperManager.getInstance(context)
|
||||
val desiredW = wm.desiredMinimumWidth
|
||||
val desiredH = wm.desiredMinimumHeight
|
||||
// desiredMinimumWidth/Height return 0 when the launcher hasn't set a preference yet.
|
||||
// Never render below the largest internal panel's resolution on a foldable.
|
||||
if (desiredW > 0 && desiredH > 0) {
|
||||
Size(maxOf(desiredW, screen.width), maxOf(desiredH, screen.height))
|
||||
} else {
|
||||
screen
|
||||
}
|
||||
}
|
||||
else -> screen
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a static wallpaper should retain source overflow for launcher-managed scrolling.
|
||||
*
|
||||
* FIT/STRETCH/NONE use an exact launcher canvas so Android cannot rescale them into FILL.
|
||||
*/
|
||||
internal fun usesLauncherManagedScrolling(
|
||||
screenType: com.anthonyla.paperize.core.ScreenType,
|
||||
scaling: ScalingType
|
||||
): Boolean =
|
||||
(screenType == com.anthonyla.paperize.core.ScreenType.HOME ||
|
||||
screenType == com.anthonyla.paperize.core.ScreenType.BOTH) &&
|
||||
scaling == ScalingType.FILL
|
||||
|
||||
/**
|
||||
* Retrieve a bitmap from a URI that is scaled down to the device's screen size.
|
||||
*
|
||||
* ImageDecoder is the primary path: it auto-applies EXIF orientation and exposes
|
||||
* post-EXIF dimensions in the callback via info.size, so we no longer need a
|
||||
* separate getImageDimensions() pre-read. The BitmapFactory fallback computes its
|
||||
* own inSampleSize inline to avoid an extra stream open on the happy path.
|
||||
*/
|
||||
fun retrieveBitmap(
|
||||
context: Context,
|
||||
wallpaperUri: Uri,
|
||||
width: Int,
|
||||
height: Int,
|
||||
scaling: ScalingType = ScalingType.FIT
|
||||
scaling: ScalingType = ScalingType.FIT,
|
||||
preserveSourceOverflow: Boolean = false
|
||||
): Bitmap? {
|
||||
val imageSize = wallpaperUri.getImageDimensions(context) ?: return null
|
||||
if (imageSize.width <= 0 || imageSize.height <= 0) {
|
||||
Log.e(TAG, "Invalid image dimensions from URI: $imageSize")
|
||||
return null
|
||||
}
|
||||
|
||||
val sampleSize = if (scaling == ScalingType.NONE) {
|
||||
1
|
||||
} else {
|
||||
calculateInSampleSize(imageSize, width, height)
|
||||
}
|
||||
|
||||
// ImageDecoder auto-applies EXIF orientation; info.size is the post-EXIF display size.
|
||||
// No separate getImageDimensions() call needed — saves 1-2 stream opens per wallpaper.
|
||||
var decodedWithImageDecoder = false
|
||||
val bitmap = try {
|
||||
val source = ImageDecoder.createSource(context.contentResolver, wallpaperUri)
|
||||
ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
val (targetWidth, targetHeight) = when (scaling) {
|
||||
val result = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||
val srcWidth = info.size.width
|
||||
val srcHeight = info.size.height
|
||||
|
||||
when (scaling) {
|
||||
ScalingType.FILL -> {
|
||||
// Calculate scale to cover target dimensions
|
||||
val widthRatio = width.toFloat() / imageSize.width
|
||||
val heightRatio = height.toFloat() / imageSize.height
|
||||
val scale = maxOf(widthRatio, heightRatio)
|
||||
Pair((imageSize.width * scale).fastRoundToInt(), (imageSize.height * scale).fastRoundToInt())
|
||||
// Scale to fill, then crop to canvas during decode.
|
||||
// setCrop avoids allocating the full fill-scale bitmap (which can be
|
||||
// much taller/wider than the canvas) — major OOM prevention.
|
||||
val scale = maxOf(width.toFloat() / srcWidth, height.toFloat() / srcHeight)
|
||||
val targetW = (srcWidth * scale).fastRoundToInt()
|
||||
val targetH = (srcHeight * scale).fastRoundToInt()
|
||||
decoder.setTargetSize(targetW, targetH)
|
||||
if (!preserveSourceOverflow && (targetW > width || targetH > height)) {
|
||||
val cropX = ((targetW - width) / 2).coerceAtLeast(0)
|
||||
val cropY = ((targetH - height) / 2).coerceAtLeast(0)
|
||||
decoder.setCrop(android.graphics.Rect(
|
||||
cropX, cropY, cropX + width, cropY + height
|
||||
))
|
||||
}
|
||||
}
|
||||
ScalingType.FIT -> {
|
||||
// Calculate scale to fit inside target dimensions
|
||||
val widthRatio = width.toFloat() / imageSize.width
|
||||
val heightRatio = height.toFloat() / imageSize.height
|
||||
val scale = minOf(widthRatio, heightRatio)
|
||||
Pair((imageSize.width * scale).fastRoundToInt(), (imageSize.height * scale).fastRoundToInt())
|
||||
val scale = minOf(width.toFloat() / srcWidth, height.toFloat() / srcHeight)
|
||||
decoder.setTargetSize(
|
||||
(srcWidth * scale).fastRoundToInt(),
|
||||
(srcHeight * scale).fastRoundToInt()
|
||||
)
|
||||
}
|
||||
ScalingType.STRETCH -> decoder.setTargetSize(width, height)
|
||||
ScalingType.NONE -> {
|
||||
val maxWidth = width * 2
|
||||
val maxHeight = height * 2
|
||||
if (srcWidth > maxWidth || srcHeight > maxHeight) {
|
||||
val scale = minOf(maxWidth.toFloat() / srcWidth, maxHeight.toFloat() / srcHeight)
|
||||
decoder.setTargetSize(
|
||||
(srcWidth * scale).fastRoundToInt(),
|
||||
(srcHeight * scale).fastRoundToInt()
|
||||
)
|
||||
}
|
||||
// else: decode at original resolution
|
||||
}
|
||||
ScalingType.STRETCH -> Pair(width, height)
|
||||
ScalingType.NONE -> Pair(imageSize.width, imageSize.height)
|
||||
}
|
||||
|
||||
decoder.setTargetSize(targetWidth, targetHeight)
|
||||
decoder.isMutableRequired = true
|
||||
// Use high quality when possible
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
}
|
||||
decodedWithImageDecoder = true
|
||||
result
|
||||
} 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
|
||||
try {
|
||||
// Compute inSampleSize from a bounds-only pass, then decode in a second pass.
|
||||
// Two opens only on the rare fallback path — the primary ImageDecoder path is free.
|
||||
val sampleSize = context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
|
||||
val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeStream(stream, null, opts)
|
||||
if (scaling == ScalingType.NONE || opts.outWidth <= 0 || opts.outHeight <= 0) 1
|
||||
else calculateInSampleSize(Size(opts.outWidth, opts.outHeight), width, height)
|
||||
} ?: 1
|
||||
context.contentResolver.openInputStream(wallpaperUri)?.use { stream ->
|
||||
BitmapFactory.decodeStream(stream, null, BitmapFactory.Options().apply {
|
||||
inSampleSize = sampleSize
|
||||
inMutable = true
|
||||
inPreferredConfig = Bitmap.Config.ARGB_8888
|
||||
})
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
} catch (oom: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM during BitmapFactory fallback for $wallpaperUri: $oom")
|
||||
null
|
||||
}
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.e(TAG, "OOM during retrieveBitmap for $wallpaperUri: $e")
|
||||
null
|
||||
}
|
||||
|
||||
// Handle EXIF orientation
|
||||
return bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
|
||||
// Only apply EXIF orientation for the BitmapFactory path — ImageDecoder already handles it
|
||||
val oriented = if (decodedWithImageDecoder) bitmap else bitmap?.let { applyExifOrientation(it, wallpaperUri, context) }
|
||||
|
||||
// Composite onto an exact (width × height) canvas so WallpaperManager.setBitmap() receives
|
||||
// a bitmap that already matches the desired canvas dimensions. Without this step the launcher
|
||||
// still has to scale/position the bitmap, which undoes the scaling mode the user chose:
|
||||
// FILL → decoded bitmap may be taller than canvas; center-crop to canvas size.
|
||||
// FIT → decoded bitmap may be narrower/shorter than canvas; center on black canvas.
|
||||
// NONE → original-size image may be smaller than canvas; center on black canvas.
|
||||
// STRETCH → decoder was told the exact canvas size; no-op.
|
||||
return oriented?.let {
|
||||
if (preserveSourceOverflow && scaling == ScalingType.FILL) {
|
||||
scaleToFillPreservingOverflow(it, width, height)
|
||||
} else {
|
||||
finalizeToCanvas(it, width, height, scaling)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale [source] just enough to cover one screen while retaining any overflow.
|
||||
*
|
||||
* The returned bitmap may be wider than [width] or taller than [height]. That overflow is what a
|
||||
* launcher uses to scroll a static wallpaper without moving past the source image's real edge.
|
||||
*/
|
||||
private fun scaleToFillPreservingOverflow(
|
||||
source: Bitmap,
|
||||
width: Int,
|
||||
height: Int
|
||||
): Bitmap {
|
||||
val scale = maxOf(
|
||||
width.toFloat() / source.width,
|
||||
height.toFloat() / source.height
|
||||
)
|
||||
val targetW = (source.width * scale).fastRoundToInt()
|
||||
val targetH = (source.height * scale).fastRoundToInt()
|
||||
if (targetW == source.width && targetH == source.height) return source
|
||||
|
||||
val scaled = source.scale(targetW, targetH)
|
||||
if (scaled !== source) source.recycle()
|
||||
return scaled
|
||||
}
|
||||
|
||||
/**
|
||||
* Produce a bitmap of exactly [canvasW] × [canvasH] pixels according to [scaling]:
|
||||
*
|
||||
* - FILL: the source already fills (or overflows) the canvas because [retrieveBitmap]
|
||||
* decoded it at fill-scale. Center-crop any overflow.
|
||||
* - FIT: the source fits within the canvas but may leave empty margins.
|
||||
* Draw it centered on a black [canvasW]×[canvasH] bitmap.
|
||||
* - STRETCH: [retrieveBitmap] decoded to the exact canvas size; nothing to do.
|
||||
* - NONE: the source is at most canvas-sized (possibly smaller).
|
||||
* Draw it centered on a black [canvasW]×[canvasH] bitmap.
|
||||
*/
|
||||
private fun finalizeToCanvas(source: Bitmap, canvasW: Int, canvasH: Int, scaling: ScalingType): Bitmap {
|
||||
val sw = source.width
|
||||
val sh = source.height
|
||||
|
||||
return when (scaling) {
|
||||
ScalingType.FILL -> {
|
||||
// Primary path (ImageDecoder): source was decoded at fill-scale so it is
|
||||
// >= canvasW wide AND >= canvasH tall. Center-crop to exact canvas size.
|
||||
// Fallback path (BitmapFactory): source may be smaller if the image needed
|
||||
// upscaling — scale up first, then center-crop.
|
||||
val fillSrc = if (sw < canvasW || sh < canvasH) {
|
||||
val scale = maxOf(canvasW.toFloat() / sw, canvasH.toFloat() / sh)
|
||||
val scaledW = (sw * scale).fastRoundToInt()
|
||||
val scaledH = (sh * scale).fastRoundToInt()
|
||||
val scaled = Bitmap.createScaledBitmap(source, scaledW, scaledH, true)
|
||||
if (scaled !== source) source.recycle()
|
||||
scaled
|
||||
} else source
|
||||
val fsw = fillSrc.width
|
||||
val fsh = fillSrc.height
|
||||
if (fsw == canvasW && fsh == canvasH) return fillSrc
|
||||
val x = ((fsw - canvasW) / 2).coerceAtLeast(0)
|
||||
val y = ((fsh - canvasH) / 2).coerceAtLeast(0)
|
||||
val cropped = Bitmap.createBitmap(fillSrc, x, y, canvasW, canvasH)
|
||||
if (cropped !== fillSrc) fillSrc.recycle()
|
||||
cropped
|
||||
}
|
||||
|
||||
ScalingType.FIT, ScalingType.NONE -> {
|
||||
// FIT / NONE: source fits within the canvas; center it on a black background.
|
||||
if (sw == canvasW && sh == canvasH) return source
|
||||
compositeCenter(source, canvasW, canvasH)
|
||||
}
|
||||
|
||||
ScalingType.STRETCH -> source // decoder was given exact canvas dimensions
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw [source] centered on a new [canvasW]×[canvasH] black bitmap and return the result.
|
||||
* [source] is recycled unless it is the same object as the returned bitmap.
|
||||
*/
|
||||
private fun compositeCenter(source: Bitmap, canvasW: Int, canvasH: Int): Bitmap {
|
||||
val canvas = Bitmap.createBitmap(canvasW, canvasH, Bitmap.Config.ARGB_8888)
|
||||
val c = Canvas(canvas)
|
||||
c.drawColor(Color.BLACK)
|
||||
val offsetX = ((canvasW - source.width) / 2f).coerceAtLeast(0f)
|
||||
val offsetY = ((canvasH - source.height) / 2f).coerceAtLeast(0f)
|
||||
c.drawBitmap(source, offsetX, offsetY, null)
|
||||
source.recycle()
|
||||
return canvas
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -281,7 +493,7 @@ fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "darkenBitmap received an immutable bitmap. Creating a mutable copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle()
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return darkenBitmap(mutableCopy, darkenPercent)
|
||||
}
|
||||
|
||||
@@ -295,6 +507,7 @@ fun darkenBitmap(source: Bitmap, darkenPercent: Int): Bitmap {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(targetBrightnessFactor, targetBrightnessFactor, targetBrightnessFactor, 1f)
|
||||
})
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
@@ -328,7 +541,7 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
renderNode.setPosition(0, 0, source.width, source.height)
|
||||
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.MIRROR)
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP)
|
||||
renderNode.setRenderEffect(blurEffect)
|
||||
|
||||
val canvas = renderNode.beginRecording()
|
||||
@@ -342,20 +555,26 @@ fun blurBitmapHardware(source: Bitmap, percent: Int): Bitmap {
|
||||
val image = imageReader.acquireNextImage()
|
||||
?: throw IllegalStateException("Failed to acquire blurred image")
|
||||
|
||||
val hardwareBuffer = image.hardwareBuffer
|
||||
?: throw IllegalStateException("Failed to acquire hardware buffer")
|
||||
try {
|
||||
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")
|
||||
try {
|
||||
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")
|
||||
// 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")
|
||||
|
||||
hardwareBitmap.recycle()
|
||||
hardwareBuffer.close()
|
||||
image.close()
|
||||
hardwareBitmap.recycle()
|
||||
} finally {
|
||||
hardwareBuffer.close()
|
||||
}
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error blurring bitmap: $e")
|
||||
@@ -388,14 +607,17 @@ fun vignetteBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "vignetteBitmap received an immutable bitmap. Creating a mutable copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle()
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
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) / Constants.VIGNETTE_DIVISOR))).coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
|
||||
// Use corner-to-center diagonal so the vignette darkens uniformly in all directions
|
||||
val halfW = source.width / 2f
|
||||
val halfH = source.height / 2f
|
||||
val diagonal = kotlin.math.sqrt(halfW * halfW + halfH * halfH)
|
||||
val rad = (diagonal * (1 - (percent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR))).coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
|
||||
val centerX = source.width / 2f
|
||||
val centerY = source.height / 2f
|
||||
|
||||
@@ -432,7 +654,7 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "grayscaleBitmap received an immutable bitmap. Creating a mutable copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle()
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return grayscaleBitmap(mutableCopy, percent)
|
||||
}
|
||||
|
||||
@@ -440,7 +662,10 @@ fun grayscaleBitmap(source: Bitmap, percent: Int): Bitmap {
|
||||
if (factor <= 0f) return source
|
||||
|
||||
val colorMatrix = ColorMatrix().apply { setSaturation(1 - factor) }
|
||||
val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(colorMatrix) }
|
||||
val paint = Paint().apply {
|
||||
colorFilter = ColorMatrixColorFilter(colorMatrix)
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
@@ -463,7 +688,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
if (!source.isMutable) {
|
||||
Log.w(TAG, "adjustBitmapBrightness received an immutable bitmap. Returning a copy.")
|
||||
val mutableCopy = source.copy(source.config ?: Bitmap.Config.ARGB_8888, true)
|
||||
source.recycle() // Recycle source to prevent memory leak
|
||||
// Do not recycle source here — caller owns the lifecycle and handles recycling
|
||||
return adjustBitmapBrightness(mutableCopy, brightnessFactor)
|
||||
}
|
||||
|
||||
@@ -471,6 +696,7 @@ fun adjustBitmapBrightness(source: Bitmap, brightnessFactor: Float): Bitmap {
|
||||
colorFilter = ColorMatrixColorFilter(ColorMatrix().apply {
|
||||
setScale(brightnessFactor, brightnessFactor, brightnessFactor, 1f)
|
||||
})
|
||||
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
|
||||
}
|
||||
Canvas(source).drawBitmap(source, 0f, 0f, paint)
|
||||
return source
|
||||
@@ -510,6 +736,12 @@ fun adaptiveBrightnessAdjustment(context: Context, source: Bitmap): Bitmap {
|
||||
/**
|
||||
* Process bitmap with all effects - now respects enable flags
|
||||
* Properly manages bitmap lifecycle by recycling intermediate results
|
||||
*
|
||||
* Uses a GPU-accelerated pipeline via [RenderEffect] chaining when possible (API 31+).
|
||||
* All colour-filter effects (darken, grayscale) and blur are composed into a single
|
||||
* RenderNode draw call so there is only **one** GPU→CPU copy at the end.
|
||||
* Vignette is drawn on the same RenderNode canvas before read-back.
|
||||
* Falls back to the sequential CPU path on error.
|
||||
*/
|
||||
fun processBitmap(
|
||||
source: Bitmap,
|
||||
@@ -521,41 +753,195 @@ fun processBitmap(
|
||||
vignettePercent: Int = 0,
|
||||
enableGrayscale: Boolean = false,
|
||||
grayscalePercent: Int = 0
|
||||
): Bitmap {
|
||||
// Fast path – nothing to do
|
||||
val hasDarken = enableDarken && darkenPercent > 0
|
||||
val hasBlur = enableBlur && blurPercent > 0
|
||||
val hasVignette = enableVignette && vignettePercent > 0
|
||||
val hasGrayscale = enableGrayscale && grayscalePercent > 0
|
||||
if (!hasDarken && !hasBlur && !hasVignette && !hasGrayscale) return source
|
||||
|
||||
// Try GPU-chained path
|
||||
try {
|
||||
return processBitmapGpu(
|
||||
source,
|
||||
hasDarken, darkenPercent,
|
||||
hasBlur, blurPercent,
|
||||
hasVignette, vignettePercent,
|
||||
hasGrayscale, grayscalePercent
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "GPU effects pipeline failed, falling back to CPU: $e")
|
||||
} catch (e: OutOfMemoryError) {
|
||||
Log.w(TAG, "OOM in GPU effects pipeline, falling back to CPU: $e")
|
||||
}
|
||||
|
||||
// CPU fallback
|
||||
return processBitmapCpu(
|
||||
source,
|
||||
hasDarken, darkenPercent,
|
||||
hasBlur, blurPercent,
|
||||
hasVignette, vignettePercent,
|
||||
hasGrayscale, grayscalePercent
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* GPU-accelerated effects pipeline.
|
||||
*
|
||||
* Chains darken, blur, and grayscale as [RenderEffect]s on a single [RenderNode],
|
||||
* draws the vignette overlay on the same canvas, and reads back the result once.
|
||||
*/
|
||||
private fun processBitmapGpu(
|
||||
source: Bitmap,
|
||||
hasDarken: Boolean, darkenPercent: Int,
|
||||
hasBlur: Boolean, blurPercent: Int,
|
||||
hasVignette: Boolean, vignettePercent: Int,
|
||||
hasGrayscale: Boolean, grayscalePercent: Int
|
||||
): Bitmap {
|
||||
val w = source.width
|
||||
val h = source.height
|
||||
|
||||
val imageReader = ImageReader.newInstance(
|
||||
w, h, PixelFormat.RGBA_8888, 1,
|
||||
HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE or HardwareBuffer.USAGE_GPU_COLOR_OUTPUT
|
||||
)
|
||||
val renderNode = RenderNode("EffectsChain")
|
||||
val hardwareRenderer = HardwareRenderer()
|
||||
|
||||
try {
|
||||
hardwareRenderer.setSurface(imageReader.surface)
|
||||
hardwareRenderer.setContentRoot(renderNode)
|
||||
renderNode.setPosition(0, 0, w, h)
|
||||
|
||||
// --- Build chained RenderEffect (darken → blur → grayscale) ---
|
||||
var effect: RenderEffect? = null
|
||||
|
||||
if (hasDarken) {
|
||||
val factor = (100 - darkenPercent.coerceIn(0, 100)) / 100f
|
||||
val cm = ColorMatrix().apply { setScale(factor, factor, factor, 1f) }
|
||||
val darkenEffect = RenderEffect.createColorFilterEffect(ColorMatrixColorFilter(cm))
|
||||
effect = darkenEffect
|
||||
}
|
||||
|
||||
if (hasBlur) {
|
||||
val radius = (blurPercent.coerceIn(0, 100) / 100f) * Constants.MAX_BLUR_RADIUS
|
||||
val blurEffect = RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP)
|
||||
effect = if (effect != null) {
|
||||
RenderEffect.createChainEffect(blurEffect, effect)
|
||||
} else {
|
||||
blurEffect
|
||||
}
|
||||
}
|
||||
|
||||
if (hasGrayscale) {
|
||||
val factor = grayscalePercent.coerceIn(0, 100) / 100f
|
||||
val cm = ColorMatrix().apply { setSaturation(1 - factor) }
|
||||
val gsEffect = RenderEffect.createColorFilterEffect(ColorMatrixColorFilter(cm))
|
||||
effect = if (effect != null) {
|
||||
RenderEffect.createChainEffect(gsEffect, effect)
|
||||
} else {
|
||||
gsEffect
|
||||
}
|
||||
}
|
||||
|
||||
if (effect != null) {
|
||||
renderNode.setRenderEffect(effect)
|
||||
}
|
||||
|
||||
// --- Record canvas commands ---
|
||||
val canvas = renderNode.beginRecording()
|
||||
canvas.drawBitmap(source, 0f, 0f, null)
|
||||
|
||||
// Vignette is an overlay drawn on top of the source in the same pass
|
||||
if (hasVignette) {
|
||||
val halfW = w / 2f
|
||||
val halfH = h / 2f
|
||||
val diagonal = kotlin.math.sqrt(halfW * halfW + halfH * halfH)
|
||||
val rad = (diagonal * (1 - (vignettePercent.coerceIn(0, 100) / Constants.VIGNETTE_DIVISOR)))
|
||||
.coerceAtLeast(Constants.VIGNETTE_MIN_RADIUS)
|
||||
val colors = intArrayOf(
|
||||
Color.TRANSPARENT,
|
||||
Color.argb((Constants.VIGNETTE_INNER_ALPHA * 255).toInt(), 0, 0, 0),
|
||||
Color.argb((Constants.VIGNETTE_OUTER_ALPHA * 255).toInt(), 0, 0, 0)
|
||||
)
|
||||
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
shader = RadialGradient(
|
||||
halfW, halfH, rad,
|
||||
colors, Constants.VIGNETTE_GRADIENT_POSITIONS, Shader.TileMode.CLAMP
|
||||
)
|
||||
}
|
||||
canvas.drawRect(0f, 0f, w.toFloat(), h.toFloat(), paint)
|
||||
}
|
||||
|
||||
renderNode.endRecording()
|
||||
|
||||
// --- Single GPU render + single read-back ---
|
||||
hardwareRenderer.createRenderRequest()
|
||||
.setWaitForPresent(true)
|
||||
.syncAndDraw()
|
||||
|
||||
val image = imageReader.acquireNextImage()
|
||||
?: throw IllegalStateException("Failed to acquire image after GPU render")
|
||||
|
||||
try {
|
||||
val hwBuffer = image.hardwareBuffer
|
||||
?: throw IllegalStateException("Failed to acquire hardware buffer")
|
||||
try {
|
||||
val hwBitmap = Bitmap.wrapHardwareBuffer(hwBuffer, null)
|
||||
?: throw IllegalStateException("Failed to wrap hardware buffer")
|
||||
val result = hwBitmap.copy(Bitmap.Config.ARGB_8888, true)
|
||||
?: throw IllegalStateException("Failed to copy hardware bitmap")
|
||||
hwBitmap.recycle()
|
||||
return result
|
||||
} finally {
|
||||
hwBuffer.close()
|
||||
}
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
} finally {
|
||||
hardwareRenderer.destroy()
|
||||
renderNode.discardDisplayList()
|
||||
imageReader.close()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CPU fallback: applies effects sequentially (original implementation).
|
||||
*/
|
||||
private fun processBitmapCpu(
|
||||
source: Bitmap,
|
||||
hasDarken: Boolean, darkenPercent: Int,
|
||||
hasBlur: Boolean, blurPercent: Int,
|
||||
hasVignette: Boolean, vignettePercent: Int,
|
||||
hasGrayscale: Boolean, grayscalePercent: Int
|
||||
): Bitmap {
|
||||
var result = source
|
||||
|
||||
// Apply effects in order, respecting enable flags
|
||||
// Recycle intermediate bitmaps to prevent memory leaks
|
||||
|
||||
// Darken modifies in-place for mutable bitmaps, no need to track previous
|
||||
if (enableDarken && darkenPercent > 0) {
|
||||
if (hasDarken) {
|
||||
result = darkenBitmap(result, darkenPercent)
|
||||
}
|
||||
|
||||
// Blur always creates a new bitmap
|
||||
if (enableBlur && blurPercent > 0) {
|
||||
if (hasBlur) {
|
||||
val previous = result
|
||||
result = blurBitmap(result, blurPercent)
|
||||
// Recycle the previous one if different from source
|
||||
if (result !== previous && previous !== source) {
|
||||
previous.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (enableVignette && vignettePercent > 0) {
|
||||
if (hasVignette) {
|
||||
val previous = result
|
||||
result = vignetteBitmap(result, vignettePercent)
|
||||
// Vignette modifies in-place for mutable bitmaps, may create copy for immutable
|
||||
if (result !== previous && previous !== source) {
|
||||
previous.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
if (enableGrayscale && grayscalePercent > 0) {
|
||||
if (hasGrayscale) {
|
||||
val previous = result
|
||||
result = grayscaleBitmap(result, grayscalePercent)
|
||||
// Grayscale modifies in-place for mutable bitmaps, may create copy for immutable
|
||||
if (result !== previous && previous !== source) {
|
||||
previous.recycle()
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.data.database.converters.TypeConverters as PaperizeTypeConverters
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
@@ -32,7 +34,8 @@ import com.anthonyla.paperize.core.constants.Constants
|
||||
AlbumEntity::class,
|
||||
WallpaperEntity::class,
|
||||
FolderEntity::class,
|
||||
WallpaperQueueEntity::class
|
||||
WallpaperQueueEntity::class,
|
||||
WallpaperCurrentEntity::class
|
||||
],
|
||||
version = Constants.DATABASE_VERSION,
|
||||
exportSchema = true
|
||||
@@ -43,4 +46,5 @@ abstract class PaperizeDatabase : RoomDatabase() {
|
||||
abstract fun wallpaperDao(): WallpaperDao
|
||||
abstract fun folderDao(): FolderDao
|
||||
abstract fun wallpaperQueueDao(): WallpaperQueueDao
|
||||
abstract fun wallpaperCurrentDao(): WallpaperCurrentDao
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
@Dao
|
||||
interface WallpaperCurrentDao {
|
||||
|
||||
/**
|
||||
* Return the wallpaper entity that was last applied for this album/screen,
|
||||
* or null if none has been recorded yet (or if it was deleted via CASCADE).
|
||||
*/
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
|
||||
WHERE wc.albumId = :albumId AND wc.screenType = :screenType
|
||||
LIMIT 1
|
||||
""")
|
||||
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity?
|
||||
|
||||
/** Reactive variant of [getCurrentWallpaper]; re-emits when the recorded wallpaper changes. */
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
|
||||
WHERE wc.albumId = :albumId AND wc.screenType = :screenType
|
||||
LIMIT 1
|
||||
""")
|
||||
fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<WallpaperEntity?>
|
||||
|
||||
/** Record (or overwrite) the current wallpaper for an album/screen pair. */
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun upsertCurrentWallpaper(entity: WallpaperCurrentEntity)
|
||||
}
|
||||
@@ -121,4 +121,30 @@ interface WallpaperDao {
|
||||
*/
|
||||
@Query("SELECT COUNT(*) FROM wallpapers WHERE albumId = :albumId")
|
||||
suspend fun getWallpaperCountByAlbum(albumId: String): Int
|
||||
|
||||
/**
|
||||
* Get all URIs for wallpapers in a folder — used for duplicate detection during folder rescan.
|
||||
*/
|
||||
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId AND folderId = :folderId")
|
||||
suspend fun getWallpaperUrisByAlbumAndFolder(albumId: String, folderId: String): List<String>
|
||||
|
||||
/**
|
||||
* Get wallpaper IDs only for queue building (shuffle mode).
|
||||
* Avoids loading full entities when only IDs are needed.
|
||||
*/
|
||||
@Query("SELECT id FROM wallpapers WHERE albumId = :albumId")
|
||||
suspend fun getWallpaperIdsByAlbum(albumId: String): List<String>
|
||||
|
||||
/**
|
||||
* Get wallpaper IDs with display order for queue building (sequential mode).
|
||||
* Avoids loading full entities when only ID + order are needed.
|
||||
*/
|
||||
@Query("SELECT id, displayOrder FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
suspend fun getWallpaperIdsAndOrderByAlbum(albumId: String): List<WallpaperIdAndOrder>
|
||||
}
|
||||
|
||||
/** Lightweight projection used for queue building — avoids loading full WallpaperEntity. */
|
||||
data class WallpaperIdAndOrder(
|
||||
val id: String,
|
||||
val displayOrder: Int
|
||||
)
|
||||
@@ -8,7 +8,6 @@ import androidx.room.Transaction
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Wallpaper Queue operations
|
||||
@@ -55,49 +54,47 @@ interface WallpaperQueueDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertQueueItems(items: List<WallpaperQueueEntity>)
|
||||
|
||||
/**
|
||||
* Delete a specific queue item by wallpaperId.
|
||||
*
|
||||
* The MIN() subquery was removed because [getAndDequeueWallpaper] already retrieves
|
||||
* the item at the minimum position before calling this, so the subquery is redundant.
|
||||
* The [wallpaperId] index makes this O(log n) instead of O(n) with the subquery.
|
||||
*/
|
||||
@Query("""
|
||||
DELETE FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
AND wallpaperId = :wallpaperId
|
||||
AND queuePosition = (
|
||||
SELECT MIN(queuePosition)
|
||||
FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
)
|
||||
""")
|
||||
suspend fun deleteQueueItem(albumId: String, screenType: ScreenType, wallpaperId: String)
|
||||
|
||||
@Query("""
|
||||
DELETE FROM wallpaper_queue
|
||||
SELECT MIN(queuePosition) 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)
|
||||
suspend fun getFirstQueuePosition(albumId: String, screenType: ScreenType): Int?
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Restore a dequeued wallpaper to the front after the platform rejected the change.
|
||||
*/
|
||||
@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)
|
||||
suspend fun restoreQueueItem(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
deleteQueueItem(albumId, screenType, wallpaperId)
|
||||
val firstPosition = getFirstQueuePosition(albumId, screenType) ?: 0
|
||||
insertQueueItems(
|
||||
listOf(
|
||||
WallpaperQueueEntity(
|
||||
albumId = albumId,
|
||||
wallpaperId = wallpaperId,
|
||||
screenType = screenType,
|
||||
queuePosition = firstPosition - 1
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/**
|
||||
* Room entity tracking the last-applied wallpaper per (album, screen).
|
||||
*
|
||||
* A CASCADE on both FKs means: if the album or wallpaper is deleted the entry
|
||||
* disappears automatically — the service will then fall back to a normal queue
|
||||
* advance instead of reapplying a stale URI.
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "wallpaper_current",
|
||||
primaryKeys = ["albumId", "screenType"],
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = AlbumEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["albumId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
),
|
||||
ForeignKey(
|
||||
entity = WallpaperEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["wallpaperId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
],
|
||||
indices = [Index(value = ["wallpaperId"])]
|
||||
)
|
||||
data class WallpaperCurrentEntity(
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
val screenType: ScreenType,
|
||||
|
||||
@ColumnInfo(name = "wallpaperId")
|
||||
val wallpaperId: String,
|
||||
|
||||
val appliedAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
@@ -52,17 +52,5 @@ data class WallpaperEntity(
|
||||
val sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
|
||||
val addedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
/**
|
||||
* Media type (IMAGE)
|
||||
* Added in database version 2 for live wallpaper support
|
||||
*/
|
||||
val mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE,
|
||||
|
||||
/**
|
||||
* Manual crop parameters for live wallpaper rendering
|
||||
* Added in database version 2
|
||||
*/
|
||||
val cropOffsetX: Float? = null,
|
||||
val cropOffsetY: Float? = null,
|
||||
val cropScale: Float? = null
|
||||
)
|
||||
@@ -36,7 +36,7 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
*/
|
||||
@Singleton
|
||||
class PreferencesManager @Inject constructor(
|
||||
private val context: Context
|
||||
context: Context
|
||||
) {
|
||||
private val dataStore = context.dataStore
|
||||
|
||||
@@ -45,38 +45,32 @@ class PreferencesManager @Inject constructor(
|
||||
suspend fun getAppSettings(): AppSettings {
|
||||
val prefs = dataStore.data.first()
|
||||
return AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: true,
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)],
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: false,
|
||||
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
|
||||
currentHomeWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)],
|
||||
currentLockWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)]
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true
|
||||
)
|
||||
}
|
||||
|
||||
fun getAppSettingsFlow(): Flow<AppSettings> = dataStore.data.map { prefs ->
|
||||
AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] ?: false,
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: true,
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)],
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: false,
|
||||
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true,
|
||||
currentHomeWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID)],
|
||||
currentLockWallpaperId = prefs[stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID)]
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun updateAppSettings(settings: AppSettings) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = settings.darkMode ?: false
|
||||
if (settings.darkMode != null) {
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = settings.darkMode
|
||||
} else {
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.DARK_MODE))
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +162,7 @@ class PreferencesManager @Inject constructor(
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
enableChangeOnScreenOn = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON)] ?: false,
|
||||
enableChangeOnScreenOff = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF)] ?: false,
|
||||
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
|
||||
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
),
|
||||
@@ -231,7 +225,7 @@ class PreferencesManager @Inject constructor(
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
enableChangeOnScreenOn = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON)] ?: false,
|
||||
enableChangeOnScreenOff = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF)] ?: false,
|
||||
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] ?: false,
|
||||
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
),
|
||||
@@ -304,7 +298,7 @@ class PreferencesManager @Inject constructor(
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] = settings.liveEffects.enableGrayscale
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] = settings.liveEffects.grayscalePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] = settings.liveEffects.enableDoubleTap
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON)] = settings.liveEffects.enableChangeOnScreenOn
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF)] = settings.liveEffects.enableChangeOnScreenOff
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] = settings.liveEffects.enableParallax
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] = settings.liveEffects.parallaxIntensity
|
||||
|
||||
@@ -364,6 +358,9 @@ class PreferencesManager @Inject constructor(
|
||||
suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean {
|
||||
var wasCleared = false
|
||||
dataStore.edit { prefs ->
|
||||
// Reset on each attempt — DataStore may retry the lambda on concurrent write conflicts
|
||||
wasCleared = false
|
||||
|
||||
val homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)]
|
||||
val lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)]
|
||||
val liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)]
|
||||
@@ -464,17 +461,6 @@ class PreferencesManager @Inject constructor(
|
||||
} 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
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear schedule settings (reset to defaults)
|
||||
* Used when switching wallpaper modes
|
||||
@@ -530,7 +516,7 @@ class PreferencesManager @Inject constructor(
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_ON))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_CHANGE_ON_SCREEN_OFF))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY))
|
||||
|
||||
@@ -539,10 +525,6 @@ class PreferencesManager @Inject constructor(
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE))
|
||||
|
||||
// Clear current wallpapers
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_HOME_WALLPAPER_ID))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.CURRENT_LOCK_WALLPAPER_ID))
|
||||
|
||||
// Clear adaptive brightness
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS))
|
||||
}
|
||||
|
||||
@@ -43,6 +43,11 @@ class AlbumRepositoryImpl @Inject constructor(
|
||||
private val wallpaperRepository: dagger.Lazy<com.anthonyla.paperize.domain.repository.WallpaperRepository>
|
||||
) : AlbumRepository {
|
||||
|
||||
companion object {
|
||||
/** Number of wallpapers written per insert/progress step during an import. */
|
||||
private const val WALLPAPER_INSERT_CHUNK_SIZE = 500
|
||||
}
|
||||
|
||||
override fun getAlbumSummaries(): Flow<List<AlbumSummary>> =
|
||||
albumDao.getAlbumSummaries().map { it.toDomainModelsFromSummaries() }
|
||||
|
||||
@@ -115,12 +120,13 @@ class AlbumRepositoryImpl @Inject constructor(
|
||||
|
||||
override suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (saved: Int, total: Int) -> Unit
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - insert wallpapers, update timestamp, and update cover
|
||||
database.withTransaction {
|
||||
wallpaperDao.insertWallpapers(wallpapers.toEntities())
|
||||
insertWallpapersChunked(wallpapers, onProgress)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Update album cover if it doesn't have one
|
||||
@@ -132,13 +138,17 @@ class AlbumRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun addFolderToAlbum(albumId: String, folder: Folder): Result<Unit> {
|
||||
override suspend fun addFolderToAlbum(
|
||||
albumId: String,
|
||||
folder: Folder,
|
||||
onProgress: (saved: Int, total: Int) -> Unit
|
||||
): 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())
|
||||
insertWallpapersChunked(folder.wallpapers, onProgress)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Update album cover if it doesn't have one
|
||||
@@ -150,6 +160,24 @@ class AlbumRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert [wallpapers] in chunks, mapping each chunk to entities only as it is written so the
|
||||
* full entity list is never materialized at once, and reporting progress after each chunk.
|
||||
* Must be called inside a transaction so the overall insert stays atomic.
|
||||
*/
|
||||
private suspend fun insertWallpapersChunked(
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (saved: Int, total: Int) -> Unit
|
||||
) {
|
||||
val total = wallpapers.size
|
||||
var saved = 0
|
||||
wallpapers.chunked(WALLPAPER_INSERT_CHUNK_SIZE).forEach { chunk ->
|
||||
wallpaperDao.insertWallpapers(chunk.toEntities())
|
||||
saved += chunk.size
|
||||
onProgress(saved, total)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateFolder(folder: Folder): Result<Unit> {
|
||||
return try {
|
||||
folderDao.updateFolder(folder.toEntity())
|
||||
|
||||
@@ -4,15 +4,16 @@ import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
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.core.util.scanFolderImages
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperCurrentEntity
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModel
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModels
|
||||
import com.anthonyla.paperize.data.mapper.toEntity
|
||||
@@ -20,7 +21,6 @@ import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
@@ -35,7 +35,8 @@ import java.util.concurrent.ConcurrentHashMap
|
||||
class WallpaperRepositoryImpl @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val wallpaperDao: WallpaperDao,
|
||||
private val wallpaperQueueDao: WallpaperQueueDao
|
||||
private val wallpaperQueueDao: WallpaperQueueDao,
|
||||
private val wallpaperCurrentDao: WallpaperCurrentDao
|
||||
) : WallpaperRepository {
|
||||
|
||||
private val contentResolver: ContentResolver = context.contentResolver
|
||||
@@ -117,19 +118,27 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
|
||||
override suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result<Int> {
|
||||
return try {
|
||||
val totalCount = wallpaperDao.getWallpaperCountByAlbum(albumId)
|
||||
var totalRemoved = 0
|
||||
val batchSize = 100 // Process in smaller batches to avoid memory spikes
|
||||
var offset = 0
|
||||
|
||||
for (offset in 0 until totalCount step batchSize) {
|
||||
while (true) {
|
||||
val wallpapers = wallpaperDao.getWallpapersByAlbumPaged(albumId, batchSize, offset)
|
||||
if (wallpapers.isEmpty()) break
|
||||
|
||||
val invalidUris = wallpapers
|
||||
.filter { !it.uri.toUri().isValid(contentResolver) }
|
||||
.map { it.uri }
|
||||
.toSet()
|
||||
|
||||
if (invalidUris.isNotEmpty()) {
|
||||
wallpaperDao.deleteWallpapersByUris(invalidUris)
|
||||
wallpaperDao.deleteWallpapersByUris(invalidUris.toList())
|
||||
totalRemoved += invalidUris.size
|
||||
// Advance offset only by the number of valid items in this batch,
|
||||
// so valid items already checked are not re-fetched next iteration
|
||||
offset += wallpapers.size - invalidUris.size
|
||||
} else {
|
||||
offset += batchSize
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,6 +154,22 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
override suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getAndDequeueWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun removeWallpaperFromQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
wallpaperQueueDao.deleteQueueItem(albumId, screenType, wallpaperId)
|
||||
}
|
||||
|
||||
override suspend fun restoreWallpaperToQueueFront(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
wallpaperQueueDao.restoreQueueItem(albumId, screenType, wallpaperId)
|
||||
}
|
||||
|
||||
override suspend fun buildWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
@@ -157,35 +182,55 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
|
||||
return mutex.withLock {
|
||||
try {
|
||||
val wallpapers = wallpaperDao.getWallpapersByAlbum(albumId).first()
|
||||
|
||||
// If shuffle is enabled, check if there's an existing queue for another screen type
|
||||
// with the same album to maintain synchronized order
|
||||
val otherScreenType = if (shuffle) {
|
||||
when (screenType) {
|
||||
ScreenType.HOME -> ScreenType.LOCK
|
||||
ScreenType.LOCK -> ScreenType.HOME
|
||||
ScreenType.BOTH -> null
|
||||
ScreenType.LIVE -> null
|
||||
}
|
||||
// Load only IDs (+ order for sequential mode) instead of full WallpaperEntity
|
||||
// objects, to avoid deserializing every field for every wallpaper in the album.
|
||||
val otherScreenType: ScreenType? = if (shuffle) when (screenType) {
|
||||
ScreenType.HOME -> ScreenType.LOCK
|
||||
ScreenType.LOCK -> ScreenType.HOME
|
||||
else -> null
|
||||
} else null
|
||||
|
||||
val otherScreenQueueIds = otherScreenType?.let {
|
||||
val wallpaperIds = if (shuffle) {
|
||||
val ids = wallpaperDao.getWallpaperIdsByAlbum(albumId)
|
||||
|
||||
// In shuffle mode, sync with the other screen's queue if it exists
|
||||
val otherScreenQueueIds = otherScreenType?.let {
|
||||
try {
|
||||
wallpaperQueueDao.getQueueItems(albumId, it)
|
||||
.map { item -> item.wallpaperId }
|
||||
} catch (_: Exception) { null }
|
||||
}
|
||||
|
||||
if (otherScreenQueueIds != null && otherScreenQueueIds.isNotEmpty()) {
|
||||
com.anthonyla.paperize.core.util.QueueBuilder.mergeWithExistingQueue(otherScreenQueueIds, ids)
|
||||
} else {
|
||||
com.anthonyla.paperize.core.util.QueueBuilder.buildShuffledQueue(ids)
|
||||
}
|
||||
} else {
|
||||
val idsWithOrder = wallpaperDao.getWallpaperIdsAndOrderByAlbum(albumId)
|
||||
com.anthonyla.paperize.core.util.QueueBuilder.buildSequentialQueue(
|
||||
idsWithOrder.map { it.id to it.displayOrder }
|
||||
)
|
||||
}
|
||||
|
||||
wallpaperQueueDao.rebuildQueue(albumId, screenType, wallpaperIds)
|
||||
|
||||
// In shuffle mode, pre-populate the other screen's queue with the same order
|
||||
// if it doesn't yet exist. This ensures both screens start from the same
|
||||
// shuffle sequence, preventing drift when switching to separate schedules.
|
||||
if (shuffle && otherScreenType != null) {
|
||||
try {
|
||||
wallpaperQueueDao.getQueueItems(albumId, it)
|
||||
.map { queueItem -> queueItem.wallpaperId }
|
||||
val otherQueueIsEmpty = wallpaperQueueDao
|
||||
.getQueueItems(albumId, otherScreenType).isEmpty()
|
||||
if (otherQueueIsEmpty) {
|
||||
wallpaperQueueDao.rebuildQueue(albumId, otherScreenType, wallpaperIds)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
// Best-effort: if pre-population fails the other screen will build its
|
||||
// own queue on demand via mergeWithExistingQueue
|
||||
}
|
||||
}
|
||||
|
||||
val wallpaperIds = com.anthonyla.paperize.core.util.QueueBuilder.buildQueue(
|
||||
wallpapers = wallpapers.toDomainModels(),
|
||||
shuffle = shuffle,
|
||||
otherScreenQueue = otherScreenQueueIds
|
||||
)
|
||||
|
||||
wallpaperQueueDao.rebuildQueue(albumId, screenType, wallpaperIds)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
@@ -208,7 +253,8 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
|
||||
// Prune mutexes for this album to prevent memory leak
|
||||
// Keys are either albumId (shuffled) or $albumId:$screenType (sequential)
|
||||
queueRebuildMutexes.keys.filter { it.startsWith(albumId) }.forEach {
|
||||
// Use exact match or prefix with colon to avoid false positives (e.g., album1 vs album10)
|
||||
queueRebuildMutexes.keys.filter { it == albumId || it.startsWith("$albumId:") }.forEach {
|
||||
queueRebuildMutexes.remove(it)
|
||||
}
|
||||
|
||||
@@ -218,67 +264,41 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun normalizeAllQueuesForAlbum(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
// Normalize all queue types for this album
|
||||
// This fixes gaps in queue positions caused by CASCADE deletes
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.HOME)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LOCK)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.LIVE)
|
||||
wallpaperQueueDao.normalizeQueuePositions(albumId, ScreenType.BOTH)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
|
||||
override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<Wallpaper?> =
|
||||
wallpaperCurrentDao.getCurrentWallpaperFlow(albumId, screenType).map { it?.toDomainModel() }
|
||||
|
||||
override suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String) {
|
||||
wallpaperCurrentDao.upsertCurrentWallpaper(
|
||||
WallpaperCurrentEntity(albumId = albumId, screenType = screenType, wallpaperId = wallpaperId)
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun scanFolderForWallpapers(folderUri: Uri): Result<List<Wallpaper>> {
|
||||
return try {
|
||||
val documentFile = DocumentFile.fromTreeUri(context, folderUri)
|
||||
?: return Result.Error(Exception("Invalid folder URI"))
|
||||
|
||||
val wallpapers = mutableListOf<Wallpaper>()
|
||||
scanDirectoryRecursive(documentFile, wallpapers)
|
||||
|
||||
val wallpapers = folderUri.scanFolderImages(context).map { image ->
|
||||
Wallpaper(
|
||||
id = generateId(),
|
||||
albumId = "",
|
||||
folderId = null,
|
||||
uri = image.uri.toString(),
|
||||
fileName = image.name,
|
||||
dateModified = image.lastModified,
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
}
|
||||
Result.Success(wallpapers)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun scanDirectoryRecursive(directory: DocumentFile, result: MutableList<Wallpaper>) {
|
||||
directory.listFiles().forEach { file ->
|
||||
if (file.isDirectory) {
|
||||
scanDirectoryRecursive(file, result)
|
||||
} else if (file.isFile && file.name?.let { name -> isImageFile(name) } == true) {
|
||||
try {
|
||||
val uri = file.uri.toString()
|
||||
val fileName = file.name ?: return@forEach
|
||||
val dateModified = file.lastModified()
|
||||
|
||||
result.add(
|
||||
Wallpaper(
|
||||
id = generateId(),
|
||||
albumId = "",
|
||||
folderId = null,
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
sourceType = WallpaperSourceType.FOLDER
|
||||
)
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
// Skip failed items
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isImageFile(fileName: String): Boolean {
|
||||
val extension = fileName.substringAfterLast('.', "").lowercase()
|
||||
return extension in Constants.SUPPORTED_IMAGE_EXTENSIONS
|
||||
}
|
||||
|
||||
override suspend fun isWallpaperInAlbum(albumId: String, uri: String): Boolean =
|
||||
wallpaperDao.getWallpaperByUri(uri)?.let { it.albumId == albumId } ?: false
|
||||
|
||||
override suspend fun getExistingWallpaperUris(albumId: String, folderId: String): Set<String> =
|
||||
wallpaperDao.getWallpaperUrisByAlbumAndFolder(albumId, folderId).toHashSet()
|
||||
}
|
||||
@@ -5,11 +5,9 @@ package com.anthonyla.paperize.domain.model
|
||||
*/
|
||||
data class AppSettings(
|
||||
val darkMode: Boolean? = null, // null = system default, true = dark, false = light
|
||||
val dynamicTheming: Boolean = true,
|
||||
val dynamicTheming: Boolean = false,
|
||||
val animate: Boolean = true,
|
||||
val firstLaunch: Boolean = true,
|
||||
val currentHomeWallpaperId: String? = null,
|
||||
val currentLockWallpaperId: String? = null
|
||||
val firstLaunch: Boolean = true
|
||||
) {
|
||||
companion object {
|
||||
fun default() = AppSettings()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/**
|
||||
* A decoded and processed wallpaper that has not yet been committed as current.
|
||||
*
|
||||
* The queue item is only committed after WallpaperManager confirms that the platform accepted
|
||||
* the bitmap. If applying fails, callers restore this item to the front of its queue.
|
||||
*/
|
||||
data class PreparedWallpaper(
|
||||
val bitmap: Bitmap,
|
||||
val albumId: String,
|
||||
val screenType: ScreenType,
|
||||
val wallpaperId: String,
|
||||
val shuffle: Boolean
|
||||
)
|
||||
@@ -21,7 +21,7 @@ data class WallpaperEffects(
|
||||
|
||||
// Interactive effects (live wallpaper mode only)
|
||||
val enableDoubleTap: Boolean = false,
|
||||
val enableChangeOnScreenOn: Boolean = false,
|
||||
val enableChangeOnScreenOff: Boolean = false,
|
||||
val enableParallax: Boolean = false,
|
||||
val parallaxIntensity: Int = Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
) {
|
||||
|
||||
@@ -64,17 +64,28 @@ interface AlbumRepository {
|
||||
suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result<Unit>
|
||||
|
||||
/**
|
||||
* Add wallpapers to album
|
||||
* Add wallpapers to album.
|
||||
*
|
||||
* [onProgress] is invoked as rows are written, with the number saved so far and the total,
|
||||
* so callers can show import progress.
|
||||
*/
|
||||
suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
|
||||
): Result<Unit>
|
||||
|
||||
/**
|
||||
* Add folder to album
|
||||
* Add folder to album.
|
||||
*
|
||||
* [onProgress] is invoked as the folder's wallpapers are written, with the number saved so far
|
||||
* and the total, so callers can show import progress.
|
||||
*/
|
||||
suspend fun addFolderToAlbum(albumId: String, folder: Folder): Result<Unit>
|
||||
suspend fun addFolderToAlbum(
|
||||
albumId: String,
|
||||
folder: Folder,
|
||||
onProgress: (saved: Int, total: Int) -> Unit = { _, _ -> }
|
||||
): Result<Unit>
|
||||
|
||||
/**
|
||||
* Update folder
|
||||
|
||||
@@ -76,6 +76,24 @@ interface WallpaperRepository {
|
||||
*/
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
/**
|
||||
* Remove a specific wallpaper from a screen queue.
|
||||
*/
|
||||
suspend fun removeWallpaperFromQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Restore a prepared wallpaper to the front when applying it did not succeed.
|
||||
*/
|
||||
suspend fun restoreWallpaperToQueueFront(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Build wallpaper queue for album
|
||||
*/
|
||||
@@ -98,11 +116,22 @@ interface WallpaperRepository {
|
||||
suspend fun clearQueuesForAlbum(albumId: String): 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
|
||||
* Get the last-applied wallpaper for a given album/screen.
|
||||
* Returns null if none has been recorded yet or if it was deleted.
|
||||
*/
|
||||
suspend fun normalizeAllQueuesForAlbum(albumId: String): Result<Unit>
|
||||
suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper?
|
||||
|
||||
/**
|
||||
* Reactive variant of [getCurrentWallpaper] that re-emits whenever the recorded wallpaper
|
||||
* for this album/screen changes. Used by the in-app current-wallpaper preview.
|
||||
*/
|
||||
fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<Wallpaper?>
|
||||
|
||||
/**
|
||||
* Record the wallpaper that was just applied for a given album/screen.
|
||||
* Called by WallpaperChangeService after a successful setBitmap().
|
||||
*/
|
||||
suspend fun setCurrentWallpaper(albumId: String, screenType: ScreenType, wallpaperId: String)
|
||||
|
||||
/**
|
||||
* Scan folder for wallpapers
|
||||
@@ -114,4 +143,10 @@ interface WallpaperRepository {
|
||||
* Optimized for checking duplicates during folder sync
|
||||
*/
|
||||
suspend fun isWallpaperInAlbum(albumId: String, uri: String): Boolean
|
||||
|
||||
/**
|
||||
* Get all existing wallpaper URIs for a specific folder within an album.
|
||||
* Used for bulk duplicate detection during folder rescan (avoids N+1 queries).
|
||||
*/
|
||||
suspend fun getExistingWallpaperUris(albumId: String, folderId: String): Set<String>
|
||||
}
|
||||
@@ -2,60 +2,57 @@ package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.NoValidWallpaperException
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
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.getWallpaperRenderSize
|
||||
import com.anthonyla.paperize.core.util.processBitmap
|
||||
import com.anthonyla.paperize.core.util.retrieveBitmap
|
||||
import com.anthonyla.paperize.core.util.usesLauncherManagedScrolling
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Use case to change wallpaper
|
||||
* Prepares the next wallpaper without marking it as current.
|
||||
*
|
||||
* 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
|
||||
* The queue item is dequeued while it is decoded, but callers must invoke [complete] only after
|
||||
* WallpaperManager confirms the bitmap was applied. If the platform rejects it, [restore] puts
|
||||
* the item back at the front of the queue.
|
||||
*/
|
||||
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> {
|
||||
suspend operator fun invoke(
|
||||
albumId: String,
|
||||
screenType: ScreenType
|
||||
): Result<PreparedWallpaper> {
|
||||
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 (wallpaperRepository.getNextWallpaperInQueue(albumId, screenType) == null) {
|
||||
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)))
|
||||
return Result.Error(
|
||||
Exception(context.getString(R.string.error_failed_to_build_queue))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Atomically get and dequeue wallpaper, skipping invalid or corrupted ones
|
||||
var finalBitmap: Bitmap? = null
|
||||
var maxRetries = Constants.MAX_WALLPAPER_LOAD_RETRIES
|
||||
var queueRebuildAttempts = 0
|
||||
|
||||
// Get screen dimensions once for the retry loop
|
||||
val screenSize = getDeviceScreenSize(context)
|
||||
val effects = when (screenType) {
|
||||
ScreenType.LIVE -> settings.liveEffects
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
|
||||
@@ -66,87 +63,167 @@ class ChangeWallpaperUseCase @Inject constructor(
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
|
||||
ScreenType.LOCK -> settings.lockScalingType
|
||||
}
|
||||
val preserveSourceOverflow = usesLauncherManagedScrolling(screenType, scaling)
|
||||
val screenSize = getWallpaperRenderSize(context, screenType, scaling)
|
||||
|
||||
while (finalBitmap == null && maxRetries > 0) {
|
||||
var finalBitmap: Bitmap? = null
|
||||
var preparedWallpaperId: String? = null
|
||||
var remainingRetries = Constants.MAX_WALLPAPER_LOAD_RETRIES
|
||||
var queueRebuildAttempts = 0
|
||||
|
||||
while (finalBitmap == null && remainingRetries > 0) {
|
||||
val candidate = wallpaperRepository.getAndDequeueWallpaper(albumId, screenType)
|
||||
|
||||
if (candidate == null) {
|
||||
queueRebuildAttempts++
|
||||
if (queueRebuildAttempts > 2) {
|
||||
return Result.Error(Exception(context.getString(R.string.no_wallpapers_in_album)))
|
||||
if (queueRebuildAttempts > Constants.MAX_QUEUE_REBUILD_ATTEMPTS) {
|
||||
return Result.Error(
|
||||
EmptyAlbumException(context.getString(R.string.no_wallpapers_in_album))
|
||||
)
|
||||
}
|
||||
val rebuildResult = wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
val rebuildResult = wallpaperRepository.buildWallpaperQueue(
|
||||
albumId,
|
||||
screenType,
|
||||
settings.shuffleEnabled
|
||||
)
|
||||
if (rebuildResult is Result.Error) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_failed_to_build_queue)))
|
||||
return Result.Error(
|
||||
Exception(context.getString(R.string.error_failed_to_build_queue))
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
val uri = candidate.uri.toUri()
|
||||
if (uri.isValid(context.contentResolver)) {
|
||||
// Try to load and process the bitmap
|
||||
try {
|
||||
val bitmap = retrieveBitmap(context, uri, screenSize.width, screenSize.height, scaling)
|
||||
if (bitmap != null) {
|
||||
// retrieveBitmap already applies scaling via ImageDecoder.setTargetSize
|
||||
// Apply effects directly to the retrieved bitmap
|
||||
|
||||
var processedBitmap = processBitmap(
|
||||
source = bitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
enableBlur = effects.enableBlur,
|
||||
blurPercent = effects.blurPercentage,
|
||||
enableVignette = effects.enableVignette,
|
||||
vignettePercent = effects.vignettePercentage,
|
||||
enableGrayscale = effects.enableGrayscale,
|
||||
grayscalePercent = effects.grayscalePercentage
|
||||
)
|
||||
|
||||
if (processedBitmap !== bitmap) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
|
||||
// Apply adaptive brightness
|
||||
if (settings.adaptiveBrightness) {
|
||||
val previousBitmap = processedBitmap
|
||||
processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
|
||||
if (processedBitmap !== previousBitmap) {
|
||||
previousBitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
finalBitmap = processedBitmap
|
||||
} else {
|
||||
// File exists but failed to decode (corrupted)
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
maxRetries--
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Error during processing, skip this wallpaper
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
maxRetries--
|
||||
try {
|
||||
val bitmap = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = candidate.uri.toUri(),
|
||||
width = screenSize.width,
|
||||
height = screenSize.height,
|
||||
scaling = scaling,
|
||||
preserveSourceOverflow = preserveSourceOverflow
|
||||
)
|
||||
if (bitmap == null) {
|
||||
// A temporarily inaccessible/corrupt item is skipped for this cycle.
|
||||
// AlbumRefreshWorker owns permanent pruning.
|
||||
remainingRetries--
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
// URI invalid
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
maxRetries--
|
||||
|
||||
var processedBitmap: Bitmap? = null
|
||||
try {
|
||||
processedBitmap = processBitmap(
|
||||
source = bitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
enableBlur = effects.enableBlur,
|
||||
blurPercent = effects.blurPercentage,
|
||||
enableVignette = effects.enableVignette,
|
||||
vignettePercent = effects.vignettePercentage,
|
||||
enableGrayscale = effects.enableGrayscale,
|
||||
grayscalePercent = effects.grayscalePercentage
|
||||
)
|
||||
|
||||
if (processedBitmap !== bitmap) bitmap.recycle()
|
||||
|
||||
if (settings.adaptiveBrightness) {
|
||||
val previousBitmap = processedBitmap
|
||||
processedBitmap = adaptiveBrightnessAdjustment(context, processedBitmap)
|
||||
if (processedBitmap !== previousBitmap) previousBitmap.recycle()
|
||||
}
|
||||
|
||||
finalBitmap = processedBitmap
|
||||
preparedWallpaperId = candidate.id
|
||||
} catch (e: Exception) {
|
||||
if (processedBitmap != null && !processedBitmap.isRecycled) {
|
||||
processedBitmap.recycle()
|
||||
} else if (!bitmap.isRecycled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
throw e
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
remainingRetries--
|
||||
}
|
||||
}
|
||||
|
||||
if (finalBitmap == null) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
}
|
||||
val preparedBitmap = finalBitmap
|
||||
?: return Result.Error(
|
||||
NoValidWallpaperException(
|
||||
context.getString(R.string.error_no_valid_wallpaper_after_retries)
|
||||
)
|
||||
)
|
||||
|
||||
// Check if queue needs refilling
|
||||
val nextItem = wallpaperRepository.getNextWallpaperInQueue(albumId, screenType)
|
||||
if (nextItem == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(albumId, screenType, settings.shuffleEnabled)
|
||||
}
|
||||
|
||||
Result.Success(finalBitmap)
|
||||
Result.Success(
|
||||
PreparedWallpaper(
|
||||
bitmap = preparedBitmap,
|
||||
albumId = albumId,
|
||||
screenType = screenType,
|
||||
wallpaperId = checkNotNull(preparedWallpaperId),
|
||||
shuffle = settings.shuffleEnabled
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a successfully applied wallpaper and keep the target screen queue in sync.
|
||||
*
|
||||
* [screenType] can differ from the prepared queue when one HOME item was atomically applied to
|
||||
* both screens. The exact item is removed from LOCK rather than blindly dequeuing its head.
|
||||
*/
|
||||
suspend fun complete(
|
||||
prepared: PreparedWallpaper,
|
||||
screenType: ScreenType = prepared.screenType
|
||||
) {
|
||||
try {
|
||||
wallpaperRepository.setCurrentWallpaper(
|
||||
prepared.albumId,
|
||||
screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Applied wallpaper could not be recorded as current", e)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
if (wallpaperRepository.getNextWallpaperInQueue(prepared.albumId, screenType) == null) {
|
||||
wallpaperRepository.buildWallpaperQueue(
|
||||
prepared.albumId,
|
||||
screenType,
|
||||
prepared.shuffle
|
||||
)
|
||||
}
|
||||
// Build first when this is the first synchronized use of a screen queue, then remove
|
||||
// the exact applied item. This prevents the just-applied wallpaper from being
|
||||
// reintroduced at the head of a freshly built queue.
|
||||
wallpaperRepository.removeWallpaperFromQueue(
|
||||
prepared.albumId,
|
||||
screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Queue sync failed; it will rebuild on the next change", e)
|
||||
}
|
||||
}
|
||||
|
||||
/** Restore a prepared item after WallpaperManager rejected it. */
|
||||
suspend fun restore(prepared: PreparedWallpaper) {
|
||||
try {
|
||||
wallpaperRepository.restoreWallpaperToQueueFront(
|
||||
prepared.albumId,
|
||||
prepared.screenType,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to restore rejected wallpaper to its queue", e)
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ChangeWallpaperUseCase"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.anthonyla.paperize.domain.usecase
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
|
||||
import com.anthonyla.paperize.core.util.getWallpaperRenderSize
|
||||
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.usesLauncherManagedScrolling
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Reapply current visual effects to the last-applied wallpaper without advancing the queue.
|
||||
*
|
||||
* Used when display settings (blur, darken, scaling, etc.) change and the user wants
|
||||
* to see the effect on the current wallpaper immediately rather than jumping to the next one.
|
||||
*
|
||||
* Returns Result.Error if no current wallpaper has been recorded yet — callers should
|
||||
* fall back to [ChangeWallpaperUseCase] in that case.
|
||||
*/
|
||||
class ReapplyEffectsUseCase @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val wallpaperRepository: WallpaperRepository,
|
||||
private val settingsRepository: SettingsRepository
|
||||
) {
|
||||
suspend operator fun invoke(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String? = null
|
||||
): Result<Bitmap> {
|
||||
return try {
|
||||
val current = wallpaperId
|
||||
?.let { wallpaperRepository.getWallpaperById(it) }
|
||||
?: wallpaperRepository.getCurrentWallpaper(albumId, screenType)
|
||||
?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
|
||||
val effects = when (screenType) {
|
||||
ScreenType.LIVE -> settings.liveEffects
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
|
||||
ScreenType.LOCK -> settings.lockEffects
|
||||
}
|
||||
val scaling = when (screenType) {
|
||||
ScreenType.LIVE -> settings.liveScalingType
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
|
||||
ScreenType.LOCK -> settings.lockScalingType
|
||||
}
|
||||
val preserveSourceOverflow = usesLauncherManagedScrolling(screenType, scaling)
|
||||
val screenSize = getWallpaperRenderSize(context, screenType, scaling)
|
||||
|
||||
val uri = current.uri.toUri()
|
||||
if (!uri.isValid(context.contentResolver)) {
|
||||
return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
}
|
||||
|
||||
val bitmap = retrieveBitmap(
|
||||
context,
|
||||
uri,
|
||||
screenSize.width,
|
||||
screenSize.height,
|
||||
scaling,
|
||||
preserveSourceOverflow
|
||||
)
|
||||
?: return Result.Error(Exception(context.getString(R.string.error_no_valid_wallpaper_after_retries)))
|
||||
|
||||
var processed: Bitmap? = null
|
||||
try {
|
||||
processed = processBitmap(
|
||||
source = bitmap,
|
||||
enableDarken = effects.enableDarken,
|
||||
darkenPercent = effects.darkenPercentage,
|
||||
enableBlur = effects.enableBlur,
|
||||
blurPercent = effects.blurPercentage,
|
||||
enableVignette = effects.enableVignette,
|
||||
vignettePercent = effects.vignettePercentage,
|
||||
enableGrayscale = effects.enableGrayscale,
|
||||
grayscalePercent = effects.grayscalePercentage
|
||||
)
|
||||
|
||||
if (processed !== bitmap) bitmap.recycle()
|
||||
|
||||
if (settings.adaptiveBrightness) {
|
||||
val prev = processed
|
||||
processed = adaptiveBrightnessAdjustment(context, processed)
|
||||
if (processed !== prev) prev.recycle()
|
||||
}
|
||||
|
||||
Result.Success(processed)
|
||||
} catch (e: Exception) {
|
||||
if (processed != null && !processed.isRecycled) {
|
||||
processed.recycle()
|
||||
} else if (!bitmap.isRecycled) {
|
||||
bitmap.recycle()
|
||||
}
|
||||
throw e
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,14 +31,8 @@ class RefreshAlbumUseCase @Inject constructor(
|
||||
totalRemoved += wallpapersResult.data
|
||||
}
|
||||
|
||||
// If wallpapers were removed, normalize queue positions to fix gaps from CASCADE deletes
|
||||
if (totalRemoved > 0) {
|
||||
// Refresh album cover after validation (in case cover wallpaper was removed)
|
||||
albumRepository.refreshAlbumCover(albumId)
|
||||
|
||||
// Normalize both HOME and LOCK queues to fix position gaps
|
||||
// CASCADE deletes may leave gaps in queue positions (e.g., 0, 2, 4 instead of 0, 1, 2)
|
||||
wallpaperRepository.normalizeAllQueuesForAlbum(albumId)
|
||||
}
|
||||
|
||||
// Return error if either operation failed
|
||||
|
||||
@@ -3,11 +3,13 @@ package com.anthonyla.paperize.presentation
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -30,6 +32,7 @@ import dagger.hilt.android.AndroidEntryPoint
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
installSplashScreen()
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
setContent {
|
||||
@@ -37,12 +40,20 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
// Track if DataStore has loaded at least once
|
||||
// This prevents the loading screen from showing again if the composable is recomposed
|
||||
val appSettings by settingsViewModel.appSettings.collectAsStateWithLifecycle()
|
||||
val appSettingsState by settingsViewModel.appSettings.collectAsStateWithLifecycle()
|
||||
|
||||
// Remember if we've ever loaded settings to prevent losing NavigationGraph during recreation
|
||||
var settingsLoadedOnce by rememberSaveable { mutableStateOf(false) }
|
||||
val currentSettings = appSettingsState
|
||||
|
||||
if (currentSettings != null) {
|
||||
settingsLoadedOnce = true
|
||||
}
|
||||
|
||||
|
||||
PaperizeTheme(
|
||||
darkMode = appSettings?.darkMode ?: false,
|
||||
dynamicTheming = appSettings?.dynamicTheming ?: true
|
||||
darkMode = currentSettings?.darkMode ?: false,
|
||||
dynamicTheming = currentSettings?.dynamicTheming ?: false
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -50,11 +61,10 @@ class MainActivity : ComponentActivity() {
|
||||
) {
|
||||
// Only render navigation once DataStore has loaded
|
||||
// After first load, always show navigation even during updates
|
||||
val currentSettings = appSettings
|
||||
if (currentSettings != null) {
|
||||
if (settingsLoadedOnce) {
|
||||
NavigationGraph(
|
||||
startDestination = if (currentSettings.firstLaunch) StartupRoute else HomeRoute,
|
||||
animate = currentSettings.animate,
|
||||
startDestination = if (currentSettings?.firstLaunch != false) StartupRoute else HomeRoute,
|
||||
animate = currentSettings?.animate ?: true,
|
||||
onFirstLaunchComplete = {
|
||||
settingsViewModel.updateFirstLaunch(false)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.presentation.common.components
|
||||
|
||||
import androidx.compose.animation.core.animateDpAsState
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.foundation.interaction.collectIsPressedAsState
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
@@ -11,8 +12,6 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -24,11 +23,11 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
@Composable
|
||||
fun SettingSwitchItem(
|
||||
title: String,
|
||||
description: String? = null,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true
|
||||
description: String? = null,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier
|
||||
@@ -39,7 +38,10 @@ fun SettingSwitchItem(
|
||||
),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
) {
|
||||
Column(modifier = Modifier.padding(AppSpacing.large)) {
|
||||
Column(modifier = Modifier
|
||||
.padding(AppSpacing.large)
|
||||
.semantics(mergeDescendants = true) {}
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
@@ -77,290 +79,6 @@ fun SettingSwitchItem(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setting item with a slider - Enhanced with better surface layering
|
||||
*/
|
||||
@Composable
|
||||
fun SettingSliderItem(
|
||||
title: String,
|
||||
description: String? = null,
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit,
|
||||
valueRange: ClosedFloatingPointRange<Float>,
|
||||
steps: Int = 0,
|
||||
valueLabel: String? = null,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
|
||||
),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
) {
|
||||
Column(modifier = Modifier.padding(AppSpacing.large)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
if (description != null) {
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
|
||||
Text(
|
||||
text = description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
if (valueLabel != null) {
|
||||
Text(
|
||||
text = valueLabel,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.small))
|
||||
|
||||
Slider(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
valueRange = valueRange,
|
||||
steps = steps,
|
||||
enabled = enabled
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setting item with a switch and slider combined - Enhanced with better surface layering
|
||||
*/
|
||||
@Composable
|
||||
fun SettingSwitchWithSliderItem(
|
||||
title: String,
|
||||
description: String? = null,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
sliderValue: Float,
|
||||
onSliderValueChange: (Float) -> Unit,
|
||||
valueRange: ClosedFloatingPointRange<Float>,
|
||||
steps: Int = 0,
|
||||
valueLabel: String? = null,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
|
||||
),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
) {
|
||||
Column(modifier = Modifier.padding(AppSpacing.large)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
if (description != null) {
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
|
||||
Text(
|
||||
text = description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(modifier = Modifier.width(AppSpacing.large))
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
|
||||
if (checked) {
|
||||
Spacer(modifier = Modifier.height(AppSpacing.large))
|
||||
|
||||
if (valueLabel != null) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End
|
||||
) {
|
||||
Text(
|
||||
text = valueLabel,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
|
||||
}
|
||||
|
||||
Slider(
|
||||
value = sliderValue,
|
||||
onValueChange = onSliderValueChange,
|
||||
valueRange = valueRange,
|
||||
steps = steps
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setting clickable item - Enhanced with better surface layering
|
||||
*/
|
||||
@Composable
|
||||
fun SettingClickableItem(
|
||||
title: String,
|
||||
description: String? = null,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
trailingContent: @Composable (() -> Unit)? = null
|
||||
) {
|
||||
Card(
|
||||
onClick = onClick,
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
enabled = enabled,
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
|
||||
),
|
||||
shape = MaterialTheme.shapes.medium
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(AppSpacing.large),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
if (description != null) {
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraSmall))
|
||||
Text(
|
||||
text = description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
if (trailingContent != null) {
|
||||
Spacer(modifier = Modifier.width(AppSpacing.large))
|
||||
trailingContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interactive list item with dynamic corner radius animation
|
||||
* Inspired by Material 3 Expressive design with press feedback
|
||||
*
|
||||
* @param headlineContent Main content for the headline
|
||||
* @param supportingContent Optional supporting text content
|
||||
* @param leadingContent Optional leading icon or content
|
||||
* @param trailingContent Optional trailing content (e.g., arrow, switch)
|
||||
* @param onClick Click handler
|
||||
* @param items Total number of items in list (for contextual styling)
|
||||
* @param index Current item index (for contextual styling)
|
||||
* @param enabled Whether the item is enabled
|
||||
* @param modifier Modifier for the item
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun InteractiveListItem(
|
||||
headlineContent: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
supportingContent: (@Composable () -> Unit)? = null,
|
||||
leadingContent: (@Composable () -> Unit)? = null,
|
||||
trailingContent: (@Composable () -> Unit)? = null,
|
||||
onClick: () -> Unit = {},
|
||||
items: Int = 1,
|
||||
index: Int = 0,
|
||||
enabled: Boolean = true
|
||||
) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val isPressed by interactionSource.collectIsPressedAsState()
|
||||
|
||||
// Dynamic corner radius based on press state and position
|
||||
val cornerRadius by animateDpAsState(
|
||||
targetValue = when {
|
||||
isPressed -> 40.dp // Large radius when pressed
|
||||
items == 1 -> 20.dp // Single item gets medium radius
|
||||
index == 0 || index == items - 1 -> 20.dp // First/last items
|
||||
else -> 4.dp // Middle items get small radius
|
||||
},
|
||||
label = "corner_radius_animation"
|
||||
)
|
||||
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = modifier.clip(RoundedCornerShape(cornerRadius)),
|
||||
enabled = enabled,
|
||||
interactionSource = interactionSource,
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface
|
||||
) {
|
||||
ListItem(
|
||||
headlineContent = headlineContent,
|
||||
supportingContent = supportingContent,
|
||||
leadingContent = leadingContent,
|
||||
trailingContent = trailingContent,
|
||||
colors = ListItemDefaults.colors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainer,
|
||||
headlineColor = MaterialTheme.colorScheme.onSurface,
|
||||
supportingColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
leadingIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
trailingIconColor = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Elevated interactive card with dynamic corner radius
|
||||
* Perfect for cards in lists or grids with press feedback
|
||||
|
||||
@@ -24,7 +24,6 @@ import com.anthonyla.paperize.presentation.screens.privacy.PrivacyScreen
|
||||
import com.anthonyla.paperize.presentation.screens.settings.SettingsScreen
|
||||
import com.anthonyla.paperize.presentation.screens.sort.SortViewScreen
|
||||
import com.anthonyla.paperize.presentation.screens.startup.StartupScreen
|
||||
import com.anthonyla.paperize.presentation.screens.storage.StoragePermissionScreen
|
||||
import com.anthonyla.paperize.presentation.screens.wallpaper_view.WallpaperViewScreen
|
||||
|
||||
/**
|
||||
@@ -47,7 +46,6 @@ fun NavigationGraph(
|
||||
if (animate) { { enterTransitionBackward() } } else { { EnterTransition.None } }
|
||||
val exitBackward: AnimatedContentTransitionScope<NavBackStackEntry>.() -> ExitTransition =
|
||||
if (animate) { { exitTransitionBackward() } } else { { ExitTransition.None } }
|
||||
// Helper functions for permission checks
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
|
||||
NavHost(
|
||||
@@ -67,6 +65,9 @@ fun NavigationGraph(
|
||||
navController.navigate(WallpaperModeSelectionRoute) {
|
||||
popUpTo<StartupRoute> { inclusive = true }
|
||||
}
|
||||
},
|
||||
onPrivacyClick = {
|
||||
navController.navigate(PrivacyRoute)
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -84,10 +85,6 @@ fun NavigationGraph(
|
||||
navController.navigate(NotificationRoute) {
|
||||
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
|
||||
}
|
||||
} else if (!PermissionUtil.hasStoragePermission()) {
|
||||
navController.navigate(StoragePermissionRoute) {
|
||||
popUpTo<WallpaperModeSelectionRoute> { inclusive = true }
|
||||
}
|
||||
} else {
|
||||
onFirstLaunchComplete()
|
||||
navController.navigate(HomeRoute) {
|
||||
@@ -106,33 +103,10 @@ fun NavigationGraph(
|
||||
popExitTransition = exitBackward
|
||||
) {
|
||||
NotificationPermissionScreen(
|
||||
onContinue = {
|
||||
if (!PermissionUtil.hasStoragePermission()) {
|
||||
navController.navigate(StoragePermissionRoute) {
|
||||
popUpTo<NotificationRoute> { inclusive = true }
|
||||
}
|
||||
} else {
|
||||
onFirstLaunchComplete()
|
||||
navController.navigate(HomeRoute) {
|
||||
popUpTo<NotificationRoute> { inclusive = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Storage permission screen
|
||||
composable<StoragePermissionRoute>(
|
||||
enterTransition = enterForward,
|
||||
exitTransition = exitForward,
|
||||
popEnterTransition = enterBackward,
|
||||
popExitTransition = exitBackward
|
||||
) {
|
||||
StoragePermissionScreen(
|
||||
onContinue = {
|
||||
onFirstLaunchComplete()
|
||||
navController.navigate(HomeRoute) {
|
||||
popUpTo<StoragePermissionRoute> { inclusive = true }
|
||||
popUpTo<NotificationRoute> { inclusive = true }
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -162,7 +136,7 @@ fun NavigationGraph(
|
||||
popEnterTransition = enterBackward,
|
||||
popExitTransition = exitBackward
|
||||
) { backStackEntry ->
|
||||
val route = backStackEntry.toRoute<AlbumRoute>()
|
||||
backStackEntry.toRoute<AlbumRoute>()
|
||||
AlbumViewScreen(
|
||||
onBackClick = { navController.popBackStack() },
|
||||
onNavigateToFolder = { folderId ->
|
||||
@@ -170,9 +144,6 @@ fun NavigationGraph(
|
||||
},
|
||||
onNavigateToWallpaperView = { wallpaperUri, wallpaperName ->
|
||||
navController.navigate(WallpaperViewRoute(wallpaperUri, wallpaperName))
|
||||
},
|
||||
onNavigateToSort = {
|
||||
navController.navigate(SortRoute(route.albumId))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@@ -12,9 +12,6 @@ object StartupRoute
|
||||
@Serializable
|
||||
object NotificationRoute
|
||||
|
||||
@Serializable
|
||||
object StoragePermissionRoute
|
||||
|
||||
@Serializable
|
||||
object WallpaperModeSelectionRoute
|
||||
|
||||
|
||||
@@ -5,19 +5,21 @@ import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -28,7 +30,6 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -37,9 +38,9 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
|
||||
@Composable
|
||||
fun OnboardingLayout(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
iconContent: @Composable () -> Unit,
|
||||
content: @Composable () -> Unit,
|
||||
actions: @Composable () -> Unit
|
||||
) {
|
||||
@@ -52,92 +53,101 @@ fun OnboardingLayout(
|
||||
visible = true
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.padding(AppSpacing.extraLarge)
|
||||
) {
|
||||
BoxWithConstraints(modifier = modifier.fillMaxSize()) {
|
||||
val maxHeight = maxHeight
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(AppSpacing.extraLarge),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500),
|
||||
initialOffsetY = { 50 }
|
||||
)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(120.dp) // Larger container for the icon background
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
|
||||
shape = CircleShape
|
||||
),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(AppIconSizes.huge),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500, delayMillis = 100)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500, delayMillis = 100),
|
||||
initialOffsetY = { 50 }
|
||||
)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.headlineLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.large))
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500, delayMillis = 200)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500, delayMillis = 200),
|
||||
initialOffsetY = { 50 }
|
||||
)
|
||||
) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.medium))
|
||||
|
||||
// Actions pinned to bottom
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500, delayMillis = 300)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500, delayMillis = 300),
|
||||
initialOffsetY = { 100 }
|
||||
)
|
||||
verticalArrangement = Arrangement.Top // Top here, centering happens in inner Column
|
||||
) {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = maxHeight - (AppSpacing.extraLarge * 2)),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
actions()
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500),
|
||||
initialOffsetY = { 50 }
|
||||
)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(120.dp) // Larger container for the icon background
|
||||
.background(
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f),
|
||||
shape = CircleShape
|
||||
),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
iconContent()
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500, delayMillis = 100)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500, delayMillis = 100),
|
||||
initialOffsetY = { 50 }
|
||||
)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.headlineLarge,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.large))
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500, delayMillis = 200)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500, delayMillis = 200),
|
||||
initialOffsetY = { 50 }
|
||||
)
|
||||
) {
|
||||
content()
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.extraLarge))
|
||||
|
||||
// Actions now part of the scrollable content to handle small heights (landscape)
|
||||
AnimatedVisibility(
|
||||
visible = visible,
|
||||
enter = fadeIn(animationSpec = tween(500, delayMillis = 300)) +
|
||||
slideInVertically(
|
||||
animationSpec = tween(500, delayMillis = 300),
|
||||
initialOffsetY = { 100 }
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
|
||||
) {
|
||||
actions()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.anthonyla.paperize.presentation.screens.album_view
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -17,10 +19,9 @@ import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -28,12 +29,15 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import android.net.Uri
|
||||
import com.anthonyla.paperize.R
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.presentation.common.components.AddAlbumAnimatedFab
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.AlbumViewTopBar
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.FolderItem
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.ImportProgressDialog
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.SortBottomSheet
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.SortOption
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.WallpaperItem
|
||||
@@ -45,21 +49,21 @@ fun AlbumViewScreen(
|
||||
onBackClick: () -> Unit,
|
||||
onNavigateToFolder: (String) -> Unit,
|
||||
onNavigateToWallpaperView: (String, String) -> Unit,
|
||||
onNavigateToSort: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: AlbumViewViewModel = hiltViewModel()
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val lazyListState = rememberLazyGridState()
|
||||
|
||||
val album by viewModel.album.collectAsState()
|
||||
val folders by viewModel.folders.collectAsState()
|
||||
val wallpapers by viewModel.wallpapers.collectAsState()
|
||||
val album by viewModel.album.collectAsStateWithLifecycle()
|
||||
val folders by viewModel.folders.collectAsStateWithLifecycle()
|
||||
val wallpapers by viewModel.wallpapers.collectAsStateWithLifecycle()
|
||||
|
||||
// Selection state
|
||||
val selectedWallpapers by viewModel.selectedWallpapers.collectAsState()
|
||||
val selectedFolders by viewModel.selectedFolders.collectAsState()
|
||||
val isSelectionMode by viewModel.isSelectionMode.collectAsState()
|
||||
val selectedWallpapers by viewModel.selectedWallpapers.collectAsStateWithLifecycle()
|
||||
val selectedFolders by viewModel.selectedFolders.collectAsStateWithLifecycle()
|
||||
val isSelectionMode by viewModel.isSelectionMode.collectAsStateWithLifecycle()
|
||||
val importProgress by viewModel.importProgress.collectAsStateWithLifecycle()
|
||||
val selectedCount = selectedWallpapers.size + selectedFolders.size
|
||||
|
||||
// Check if all items are selected
|
||||
@@ -67,6 +71,7 @@ fun AlbumViewScreen(
|
||||
val allSelected = selectedCount == totalItemsCount && totalItemsCount > 0
|
||||
|
||||
var showSortSheet by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeleteAlbumDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var sortOption by rememberSaveable { mutableStateOf(SortOption.DATE_ADDED_DESC) }
|
||||
|
||||
// Handle back press when in selection mode
|
||||
@@ -112,7 +117,7 @@ fun AlbumViewScreen(
|
||||
uris.forEach { uri ->
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(uri, takeFlags)
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Handle permission failure
|
||||
}
|
||||
}
|
||||
@@ -129,7 +134,7 @@ fun AlbumViewScreen(
|
||||
try {
|
||||
context.contentResolver.takePersistableUriPermission(it, takeFlags)
|
||||
viewModel.addFolder(it.toString())
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Handle permission failure
|
||||
}
|
||||
}
|
||||
@@ -143,8 +148,8 @@ fun AlbumViewScreen(
|
||||
selectedCount = selectedCount,
|
||||
allSelected = allSelected,
|
||||
onBackClick = onBackClick,
|
||||
onSortClick = onNavigateToSort,
|
||||
onDeleteAlbum = { viewModel.deleteAlbum(); onBackClick() },
|
||||
onSortClick = { showSortSheet = true },
|
||||
onDeleteAlbum = { showDeleteAlbumDialog = true },
|
||||
onSelectAll = { if (allSelected) viewModel.clearSelection() else viewModel.selectAll() },
|
||||
onDeleteSelected = { viewModel.deleteSelected() },
|
||||
onClearSelection = { viewModel.clearSelection() }
|
||||
@@ -154,7 +159,7 @@ fun AlbumViewScreen(
|
||||
// Hide FAB when in selection mode
|
||||
if (!isSelectionMode) {
|
||||
AddAlbumAnimatedFab(
|
||||
isLoading = false,
|
||||
isLoading = importProgress !is ImportProgress.Idle,
|
||||
onImageClick = { imagePickerLauncher.launch(arrayOf("image/*")) },
|
||||
onFolderClick = { folderPickerLauncher.launch(null) }
|
||||
)
|
||||
@@ -244,4 +249,29 @@ fun AlbumViewScreen(
|
||||
onDismiss = { showSortSheet = false }
|
||||
)
|
||||
}
|
||||
|
||||
// Import progress (add folder / add wallpapers)
|
||||
ImportProgressDialog(progress = importProgress)
|
||||
|
||||
// Delete Album Confirmation Dialog
|
||||
if (showDeleteAlbumDialog) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showDeleteAlbumDialog = false },
|
||||
title = { Text(stringResource(R.string.delete_album_question)) },
|
||||
text = { Text(stringResource(R.string.are_you_sure_you_want_to_delete_this)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
viewModel.deleteAlbum()
|
||||
onBackClick()
|
||||
}
|
||||
) { Text(stringResource(R.string.confirm)) }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showDeleteAlbumDialog = false }) {
|
||||
Text(stringResource(R.string.cancel))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package com.anthonyla.paperize.presentation.screens.album_view
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.core.net.toUri
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
@@ -10,7 +11,7 @@ import androidx.navigation.toRoute
|
||||
import com.anthonyla.paperize.core.util.detectMediaType
|
||||
import com.anthonyla.paperize.core.util.generateId
|
||||
import com.anthonyla.paperize.core.util.getFileName
|
||||
import com.anthonyla.paperize.core.util.scanFolderForImages
|
||||
import com.anthonyla.paperize.core.util.scanFolderImages
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
@@ -39,6 +40,10 @@ class AlbumViewViewModel @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "AlbumViewViewModel"
|
||||
}
|
||||
|
||||
private val albumRoute = savedStateHandle.toRoute<AlbumRoute>()
|
||||
private val albumId: String = albumRoute.albumId
|
||||
|
||||
@@ -75,9 +80,14 @@ class AlbumViewViewModel @Inject constructor(
|
||||
private val _isSelectionMode = MutableStateFlow(false)
|
||||
val isSelectionMode: StateFlow<Boolean> = _isSelectionMode.asStateFlow()
|
||||
|
||||
private val _importProgress = MutableStateFlow<ImportProgress>(ImportProgress.Idle)
|
||||
val importProgress: StateFlow<ImportProgress> = _importProgress.asStateFlow()
|
||||
|
||||
fun addWallpapers(uris: List<String>) {
|
||||
viewModelScope.launch {
|
||||
val wallpapers = uris.mapIndexed { index, uri ->
|
||||
_importProgress.value = ImportProgress.Saving(saved = 0, total = uris.size)
|
||||
val existingCount = wallpapers.value.size
|
||||
val newWallpapers = uris.mapIndexed { index, uri ->
|
||||
val parsedUri = uri.toUri()
|
||||
val mediaType = parsedUri.detectMediaType(context) ?: WallpaperMediaType.IMAGE
|
||||
|
||||
@@ -88,41 +98,53 @@ class AlbumViewViewModel @Inject constructor(
|
||||
uri = uri,
|
||||
fileName = parsedUri.getFileName(context) ?: uri.substringAfterLast('/'),
|
||||
dateModified = System.currentTimeMillis(),
|
||||
displayOrder = index,
|
||||
displayOrder = existingCount + index,
|
||||
mediaType = mediaType
|
||||
)
|
||||
}
|
||||
when (albumRepository.addWallpapersToAlbum(albumId, wallpapers)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
val result = albumRepository.addWallpapersToAlbum(albumId, newWallpapers) { saved, total ->
|
||||
_importProgress.value = ImportProgress.Saving(saved, total)
|
||||
}
|
||||
when (result) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> {
|
||||
// Clear queues so the new wallpapers are included on the next cycle
|
||||
wallpaperRepository.clearQueuesForAlbum(albumId)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error adding wallpapers to album", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
_importProgress.value = ImportProgress.Idle
|
||||
}
|
||||
}
|
||||
|
||||
fun addFolder(uri: String) {
|
||||
viewModelScope.launch {
|
||||
// Scan folder for images on IO dispatcher
|
||||
val imageUris = withContext(Dispatchers.IO) {
|
||||
uri.toUri().scanFolderForImages(context)
|
||||
_importProgress.value = ImportProgress.Scanning(found = 0)
|
||||
// Scan folder for images on IO dispatcher. The scan already returns each file's
|
||||
// name and modified time, so no per-file follow-up query is needed below.
|
||||
val images = withContext(Dispatchers.IO) {
|
||||
uri.toUri().scanFolderImages(context) { found ->
|
||||
_importProgress.value = ImportProgress.Scanning(found)
|
||||
}.sortedBy { it.uri.toString() }
|
||||
}
|
||||
|
||||
// Create folder with scanned wallpapers
|
||||
val folderId = generateId()
|
||||
val wallpapers = imageUris.mapIndexed { index, imageUri ->
|
||||
val mediaType = imageUri.detectMediaType(context) ?: WallpaperMediaType.IMAGE
|
||||
|
||||
val wallpapers = images.mapIndexed { index, image ->
|
||||
Wallpaper(
|
||||
id = generateId(),
|
||||
albumId = albumId,
|
||||
folderId = folderId,
|
||||
uri = imageUri.toString(),
|
||||
fileName = imageUri.getFileName(context) ?: imageUri.lastPathSegment ?: imageUri.toString().substringAfterLast('/'),
|
||||
dateModified = System.currentTimeMillis(),
|
||||
uri = image.uri.toString(),
|
||||
fileName = image.name,
|
||||
dateModified = image.lastModified,
|
||||
displayOrder = index,
|
||||
mediaType = mediaType
|
||||
mediaType = WallpaperMediaType.fromExtension(image.name.substringAfterLast('.', "")) ?: WallpaperMediaType.IMAGE
|
||||
)
|
||||
}
|
||||
_importProgress.value = ImportProgress.Saving(saved = 0, total = wallpapers.size)
|
||||
|
||||
val folder = Folder(
|
||||
id = folderId,
|
||||
@@ -131,23 +153,34 @@ class AlbumViewViewModel @Inject constructor(
|
||||
name = uri.toUri().getFileName(context) ?: uri.substringAfterLast('/'),
|
||||
coverUri = wallpapers.firstOrNull()?.uri, // Use first image as cover
|
||||
dateModified = System.currentTimeMillis(),
|
||||
displayOrder = 0,
|
||||
displayOrder = folders.value.size,
|
||||
wallpapers = wallpapers
|
||||
)
|
||||
|
||||
when (albumRepository.addFolderToAlbum(albumId, folder)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
val result = albumRepository.addFolderToAlbum(albumId, folder) { saved, total ->
|
||||
_importProgress.value = ImportProgress.Saving(saved, total)
|
||||
}
|
||||
when (result) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> {
|
||||
// Clear queues so the new folder's wallpapers are included on the next cycle
|
||||
wallpaperRepository.clearQueuesForAlbum(albumId)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error adding folder to album", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
_importProgress.value = ImportProgress.Idle
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAlbum() {
|
||||
viewModelScope.launch {
|
||||
when (albumRepository.deleteAlbum(albumId)) {
|
||||
when (val result = albumRepository.deleteAlbum(albumId)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error deleting album", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
@@ -188,13 +221,14 @@ class AlbumViewViewModel @Inject constructor(
|
||||
viewModelScope.launch {
|
||||
val wallpaperIds = _selectedWallpapers.value.toList()
|
||||
val folderIds = _selectedFolders.value.toList()
|
||||
var hasError = false
|
||||
|
||||
// Batch delete wallpapers from album (includes timestamp update and cover refresh)
|
||||
if (wallpaperIds.isNotEmpty()) {
|
||||
when (albumRepository.removeWallpapersFromAlbum(albumId, wallpaperIds)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> hasError = true
|
||||
is com.anthonyla.paperize.core.Result.Success -> {
|
||||
_selectedWallpapers.value = _selectedWallpapers.value - wallpaperIds.toSet()
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Leave failed items selected */ }
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
@@ -203,17 +237,16 @@ class AlbumViewViewModel @Inject constructor(
|
||||
if (folderIds.isNotEmpty()) {
|
||||
folderIds.forEach { folderId ->
|
||||
when (albumRepository.removeFolderFromAlbum(albumId, folderId)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> hasError = true
|
||||
is com.anthonyla.paperize.core.Result.Success -> {
|
||||
_selectedFolders.value = _selectedFolders.value - folderId
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Leave failed item selected */ }
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only clear selection if all operations succeeded
|
||||
if (!hasError) {
|
||||
clearSelection()
|
||||
}
|
||||
updateSelectionMode()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.anthonyla.paperize.presentation.screens.album_view
|
||||
|
||||
/**
|
||||
* Progress of an ongoing add-folder / add-wallpapers import, surfaced to the UI so it can
|
||||
* show a live count instead of a bare spinner.
|
||||
*/
|
||||
sealed interface ImportProgress {
|
||||
/** No import running. */
|
||||
data object Idle : ImportProgress
|
||||
|
||||
/** Walking the folder tree; the total is not yet known. */
|
||||
data class Scanning(val found: Int) : ImportProgress
|
||||
|
||||
/** Writing the discovered images to the database. */
|
||||
data class Saving(val saved: Int, val total: Int) : ImportProgress
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.anthonyla.paperize.presentation.screens.album_view.components
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
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.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
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.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.ImportProgress
|
||||
|
||||
/**
|
||||
* Non-dismissable modal shown while a folder/wallpaper import is running, displaying a live count
|
||||
* (and a determinate bar once the total is known) instead of a bare spinner.
|
||||
*
|
||||
* Renders nothing when [progress] is [ImportProgress.Idle].
|
||||
*/
|
||||
@Composable
|
||||
fun ImportProgressDialog(progress: ImportProgress) {
|
||||
if (progress is ImportProgress.Idle) return
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = { /* Block dismissal while importing */ },
|
||||
properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)
|
||||
) {
|
||||
Surface(
|
||||
shape = MaterialTheme.shapes.extraLarge,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 6.dp
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
val titleRes = when (progress) {
|
||||
is ImportProgress.Scanning -> R.string.import_adding_folder
|
||||
else -> R.string.import_adding_wallpapers
|
||||
}
|
||||
Text(
|
||||
text = stringResource(titleRes),
|
||||
style = MaterialTheme.typography.titleMedium
|
||||
)
|
||||
|
||||
when (progress) {
|
||||
is ImportProgress.Scanning -> {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(24.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.import_scanning, progress.found),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is ImportProgress.Saving -> {
|
||||
Text(
|
||||
text = stringResource(R.string.import_saving, progress.saved, progress.total),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
val fraction by animateFloatAsState(
|
||||
targetValue = if (progress.total > 0) progress.saved.toFloat() / progress.total else 0f,
|
||||
label = "importProgress"
|
||||
)
|
||||
LinearProgressIndicator(
|
||||
progress = { fraction },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(6.dp)
|
||||
)
|
||||
}
|
||||
|
||||
ImportProgress.Idle -> Unit // unreachable, guarded above
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.anthonyla.paperize.presentation.screens.folder_view
|
||||
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -16,14 +16,13 @@ import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.SortBottomSheet
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.SortOption
|
||||
@@ -41,8 +40,8 @@ fun FolderViewScreen(
|
||||
) {
|
||||
val lazyListState = rememberLazyGridState()
|
||||
|
||||
val folder by viewModel.folder.collectAsState()
|
||||
val wallpapers by viewModel.wallpapers.collectAsState()
|
||||
val folder by viewModel.folder.collectAsStateWithLifecycle()
|
||||
val wallpapers by viewModel.wallpapers.collectAsStateWithLifecycle()
|
||||
|
||||
var showSortSheet by rememberSaveable { mutableStateOf(false) }
|
||||
var sortOption by rememberSaveable { mutableStateOf(SortOption.DATE_ADDED_DESC) }
|
||||
@@ -59,8 +58,6 @@ fun FolderViewScreen(
|
||||
}
|
||||
}
|
||||
|
||||
BackHandler { onBackClick() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
FolderViewTopBar(
|
||||
@@ -83,28 +80,22 @@ fun FolderViewScreen(
|
||||
items = sortedWallpapers,
|
||||
key = { wallpaper -> wallpaper.id }
|
||||
) { wallpaper ->
|
||||
val itemModifier = remember {
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(9f / 16f)
|
||||
.then(
|
||||
Modifier.animateItem(
|
||||
placementSpec = tween(
|
||||
durationMillis = Constants.ANIMATION_DURATION_LONG_MS,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
WallpaperItem(
|
||||
wallpaperUri = wallpaper.uri,
|
||||
isSelected = false,
|
||||
isSelectionMode = false,
|
||||
onClick = { onNavigateToWallpaperView(wallpaper.uri, wallpaper.fileName) },
|
||||
onLongClick = { /* No selection in folder view */ },
|
||||
modifier = itemModifier
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(9f / 16f)
|
||||
.animateItem(
|
||||
placementSpec = tween(
|
||||
durationMillis = Constants.ANIMATION_DURATION_LONG_MS,
|
||||
delayMillis = 0,
|
||||
easing = FastOutSlowInEasing
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
package com.anthonyla.paperize.presentation.screens.home
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Intent
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -24,14 +21,11 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -39,7 +33,6 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.presentation.screens.home.components.HomeTopBar
|
||||
import com.anthonyla.paperize.presentation.screens.home.components.getTabItems
|
||||
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
|
||||
@@ -54,11 +47,13 @@ fun HomeScreen(
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: HomeViewModel = hiltViewModel()
|
||||
) {
|
||||
val albums by viewModel.albums.collectAsState()
|
||||
val scheduleSettings by viewModel.scheduleSettings.collectAsState()
|
||||
val appSettings by viewModel.appSettings.collectAsState()
|
||||
val wallpaperMode by viewModel.wallpaperMode.collectAsState()
|
||||
val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsState()
|
||||
val albums by viewModel.albums.collectAsStateWithLifecycle()
|
||||
val scheduleSettings by viewModel.scheduleSettings.collectAsStateWithLifecycle()
|
||||
val appSettings by viewModel.appSettings.collectAsStateWithLifecycle()
|
||||
val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle()
|
||||
val showLiveWallpaperPrompt by viewModel.showLiveWallpaperPrompt.collectAsStateWithLifecycle()
|
||||
val currentHomeWallpaperUri by viewModel.currentHomeWallpaperUri.collectAsStateWithLifecycle()
|
||||
val currentLockWallpaperUri by viewModel.currentLockWallpaperUri.collectAsStateWithLifecycle()
|
||||
val coroutineScope = rememberCoroutineScope()
|
||||
val context = LocalContext.current
|
||||
|
||||
@@ -114,21 +109,27 @@ fun HomeScreen(
|
||||
state = pagerState,
|
||||
beyondViewportPageCount = 1
|
||||
) { index ->
|
||||
when (index.coerceIn(tabItems.indices)) {
|
||||
when (index) {
|
||||
0 -> {
|
||||
if (wallpaperMode == null) {
|
||||
Box(modifier = Modifier.fillMaxSize())
|
||||
} else {
|
||||
WallpaperScreen(
|
||||
albums = albums,
|
||||
scheduleSettings = scheduleSettings,
|
||||
persistedScheduleSettings = scheduleSettings,
|
||||
appSettings = appSettings,
|
||||
wallpaperMode = wallpaperMode!!,
|
||||
onToggleChanger = { viewModel.toggleWallpaperChanger(it, onlyIfNotScheduled = true) },
|
||||
onSelectHomeAlbum = { album -> viewModel.selectHomeAlbum(album) },
|
||||
onSelectLockAlbum = { album -> viewModel.selectLockAlbum(album) },
|
||||
onSelectLiveAlbum = { album -> viewModel.selectLiveAlbum(album) },
|
||||
onUpdateScheduleSettings = { viewModel.updateScheduleSettings(it) }
|
||||
onUpdateScheduleSettings = { viewModel.updateScheduleSettings(it) },
|
||||
onUpdateScheduleSettingsDebounced = { viewModel.updateScheduleSettingsDebounced(it) },
|
||||
onChangeWallpaperNow = {
|
||||
viewModel.changeWallpaperNowForActiveScreens()
|
||||
},
|
||||
homeWallpaperUri = currentHomeWallpaperUri,
|
||||
lockWallpaperUri = currentLockWallpaperUri
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -181,12 +182,12 @@ fun HomeScreen(
|
||||
)
|
||||
}
|
||||
context.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Fallback: Open general wallpaper settings
|
||||
try {
|
||||
val fallbackIntent = Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER)
|
||||
context.startActivity(fallbackIntent)
|
||||
} catch (e2: Exception) {
|
||||
} catch (_: Exception) {
|
||||
// Last resort: Open wallpaper settings
|
||||
val settingsIntent = Intent(android.provider.Settings.ACTION_SETTINGS)
|
||||
context.startActivity(settingsIntent)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
package com.anthonyla.paperize.presentation.screens.home
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -7,21 +6,27 @@ import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.isPaperizeLiveWallpaperActive
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.usecase.CreateAlbumUseCase
|
||||
import com.anthonyla.paperize.domain.usecase.DeleteAlbumUseCase
|
||||
import com.anthonyla.paperize.domain.usecase.GetAlbumSummariesUseCase
|
||||
import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService
|
||||
import com.anthonyla.paperize.service.worker.WallpaperScheduler
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
@@ -34,7 +39,6 @@ class HomeViewModel @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
getAlbumSummariesUseCase: GetAlbumSummariesUseCase,
|
||||
private val createAlbumUseCase: CreateAlbumUseCase,
|
||||
private val deleteAlbumUseCase: DeleteAlbumUseCase,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val wallpaperScheduler: WallpaperScheduler,
|
||||
private val wallpaperRepository: com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
@@ -77,6 +81,31 @@ class HomeViewModel @Inject constructor(
|
||||
initialValue = null
|
||||
)
|
||||
|
||||
/**
|
||||
* URI of the wallpaper Paperize last applied for the home / lock screen, for the in-app preview.
|
||||
* Reading the source URI (rather than WallpaperManager.getDrawable) avoids the storage permission
|
||||
* the preview would otherwise need. Falls back to the BOTH-mode record when home/lock are synced.
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
val currentHomeWallpaperUri: StateFlow<String?> = scheduleSettings
|
||||
.flatMapLatest { settings -> currentWallpaperUriFlow(settings.homeAlbumId, ScreenType.HOME) }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), null)
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
val currentLockWallpaperUri: StateFlow<String?> = scheduleSettings
|
||||
.flatMapLatest { settings -> currentWallpaperUriFlow(settings.lockAlbumId, ScreenType.LOCK) }
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS), null)
|
||||
|
||||
private fun currentWallpaperUriFlow(albumId: String?, screenType: ScreenType): Flow<String?> =
|
||||
if (albumId == null) {
|
||||
flowOf(null)
|
||||
} else {
|
||||
combine(
|
||||
wallpaperRepository.getCurrentWallpaperFlow(albumId, screenType),
|
||||
wallpaperRepository.getCurrentWallpaperFlow(albumId, ScreenType.BOTH)
|
||||
) { specific, both -> (specific ?: both)?.uri }
|
||||
}
|
||||
|
||||
// Show prompt to select live wallpaper when enabling changer in LIVE mode
|
||||
private val _showLiveWallpaperPrompt = MutableStateFlow(false)
|
||||
val showLiveWallpaperPrompt: StateFlow<Boolean> = _showLiveWallpaperPrompt
|
||||
@@ -117,37 +146,11 @@ class HomeViewModel @Inject constructor(
|
||||
|
||||
fun createAlbum(name: String) {
|
||||
viewModelScope.launch {
|
||||
when (createAlbumUseCase(name)) {
|
||||
when (val result = createAlbumUseCase(name)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAlbum(albumId: String) {
|
||||
viewModelScope.launch {
|
||||
// Atomically clear album selections if they match (prevents race conditions)
|
||||
val wasCleared = settingsRepository.clearAlbumSelectionsIfMatches(albumId)
|
||||
|
||||
// Disable changer if albums were cleared and no albums remain selected
|
||||
if (wasCleared) {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
// Check appropriate album IDs based on wallpaper mode
|
||||
val shouldDisable = if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
|
||||
settings.liveAlbumId == null
|
||||
} else {
|
||||
settings.homeAlbumId == null && settings.lockAlbumId == null
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error creating album", result.exception)
|
||||
}
|
||||
if (shouldDisable) {
|
||||
toggleWallpaperChanger(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Delete the album
|
||||
when (deleteAlbumUseCase(albumId)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
@@ -363,6 +366,12 @@ class HomeViewModel @Inject constructor(
|
||||
}
|
||||
|
||||
fun updateScheduleSettings(settings: ScheduleSettings) {
|
||||
pendingSettingsJob?.cancel()
|
||||
pendingSettingsJob = null
|
||||
applyScheduleSettings(settings)
|
||||
}
|
||||
|
||||
private fun applyScheduleSettings(settings: ScheduleSettings) {
|
||||
viewModelScope.launch {
|
||||
// Check if settings have changed before validation
|
||||
val currentSettings = settingsRepository.getScheduleSettings()
|
||||
@@ -372,11 +381,12 @@ class HomeViewModel @Inject constructor(
|
||||
val screenToggleChanged = currentSettings.homeEnabled != settings.homeEnabled ||
|
||||
currentSettings.lockEnabled != settings.lockEnabled
|
||||
|
||||
// If screen toggles changed, clear all album selections
|
||||
// If a screen was disabled, clear only that screen's album selection.
|
||||
// Clearing both when only one changes would lose the other screen's selection.
|
||||
val settingsWithClearedAlbums = if (screenToggleChanged) {
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
lockAlbumId = null
|
||||
homeAlbumId = if (!settings.homeEnabled) null else settings.homeAlbumId,
|
||||
lockAlbumId = if (!settings.lockEnabled) null else settings.lockAlbumId
|
||||
)
|
||||
} else {
|
||||
settings
|
||||
@@ -437,15 +447,26 @@ class HomeViewModel @Inject constructor(
|
||||
validated.homeAlbumId == validated.lockAlbumId &&
|
||||
!validated.separateSchedules
|
||||
if (isSynced) {
|
||||
changeWallpaperNow(ScreenType.BOTH)
|
||||
reapplyEffectsNow(ScreenType.BOTH)
|
||||
} else {
|
||||
if (homeActive) changeWallpaperNow(ScreenType.HOME)
|
||||
if (lockActive) changeWallpaperNow(ScreenType.LOCK)
|
||||
if (homeActive) reapplyEffectsNow(ScreenType.HOME)
|
||||
if (lockActive) reapplyEffectsNow(ScreenType.LOCK)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var pendingSettingsJob: Job? = null
|
||||
|
||||
fun updateScheduleSettingsDebounced(settings: ScheduleSettings) {
|
||||
pendingSettingsJob?.cancel()
|
||||
pendingSettingsJob = viewModelScope.launch {
|
||||
delay(Constants.SETTINGS_DEBOUNCE_MS)
|
||||
pendingSettingsJob = null
|
||||
applyScheduleSettings(settings)
|
||||
}
|
||||
}
|
||||
|
||||
fun changeWallpaperNow(screenType: ScreenType) {
|
||||
val intent = Intent(context, WallpaperChangeService::class.java).apply {
|
||||
action = WallpaperChangeService.ACTION_CHANGE_WALLPAPER
|
||||
@@ -454,7 +475,42 @@ class HomeViewModel @Inject constructor(
|
||||
context.startForegroundService(intent)
|
||||
}
|
||||
|
||||
private fun scheduleAlarms(settings: ScheduleSettings, onlyIfNotScheduled: Boolean = false) {
|
||||
/**
|
||||
* Change whichever wallpaper destinations are currently configured.
|
||||
*
|
||||
* Synchronized home/lock settings use one BOTH request; independent schedules are
|
||||
* changed separately. LIVE is routed through the service to reload the renderer.
|
||||
*/
|
||||
fun changeWallpaperNowForActiveScreens() {
|
||||
val settings = scheduleSettings.value
|
||||
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
|
||||
changeWallpaperNow(ScreenType.LIVE)
|
||||
return
|
||||
}
|
||||
|
||||
val homeActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
val lockActive = settings.lockEnabled && settings.lockAlbumId != null
|
||||
val synchronized = homeActive && lockActive &&
|
||||
settings.homeAlbumId == settings.lockAlbumId &&
|
||||
!settings.separateSchedules
|
||||
|
||||
if (synchronized) {
|
||||
changeWallpaperNow(ScreenType.BOTH)
|
||||
} else {
|
||||
if (homeActive) changeWallpaperNow(ScreenType.HOME)
|
||||
if (lockActive) changeWallpaperNow(ScreenType.LOCK)
|
||||
}
|
||||
}
|
||||
|
||||
fun reapplyEffectsNow(screenType: ScreenType) {
|
||||
val intent = Intent(context, WallpaperChangeService::class.java).apply {
|
||||
action = WallpaperChangeService.ACTION_REAPPLY_EFFECTS
|
||||
putExtra(WallpaperChangeService.EXTRA_SCREEN_TYPE, screenType.name)
|
||||
}
|
||||
context.startForegroundService(intent)
|
||||
}
|
||||
|
||||
private suspend fun scheduleAlarms(settings: ScheduleSettings, onlyIfNotScheduled: Boolean = false) {
|
||||
// Check if we're in LIVE mode
|
||||
if (wallpaperMode.value == com.anthonyla.paperize.core.WallpaperMode.LIVE) {
|
||||
// LIVE mode: schedule live wallpaper changes
|
||||
@@ -463,8 +519,10 @@ class HomeViewModel @Inject constructor(
|
||||
ScreenType.LIVE,
|
||||
settings.liveIntervalMinutes
|
||||
)
|
||||
wallpaperScheduler.scheduleAlbumRefresh()
|
||||
} else {
|
||||
wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE)
|
||||
wallpaperScheduler.cancelAlbumRefresh()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -23,14 +23,12 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.presentation.common.components.AddAlbumDialog
|
||||
@@ -47,7 +45,8 @@ fun LibraryScreen(
|
||||
) {
|
||||
val lazyListState = rememberLazyGridState()
|
||||
var showAddAlbumDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var albumNameError by remember { mutableStateOf<String?>(null) }
|
||||
var albumNameError by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
val albumNameExistsError = stringResource(R.string.album_name_exists_error)
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier.fillMaxSize(),
|
||||
@@ -102,7 +101,9 @@ fun LibraryScreen(
|
||||
} else {
|
||||
LazyVerticalGrid(
|
||||
state = lazyListState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(paddingValues),
|
||||
columns = GridCells.Adaptive(AppGrid.itemMinSize),
|
||||
contentPadding = PaddingValues(AppSpacing.gridPadding),
|
||||
horizontalArrangement = Arrangement.Start
|
||||
@@ -119,9 +120,8 @@ fun LibraryScreen(
|
||||
}
|
||||
|
||||
if (showAddAlbumDialog) {
|
||||
val errorMessageString = stringResource(R.string.album_name_exists_error)
|
||||
AddAlbumDialog(
|
||||
onDismiss = {
|
||||
onDismiss = {
|
||||
showAddAlbumDialog = false
|
||||
albumNameError = null
|
||||
},
|
||||
@@ -129,7 +129,7 @@ fun LibraryScreen(
|
||||
// Check if album with this name already exists
|
||||
val isDuplicate = albums.any { it.name.equals(name, ignoreCase = true) }
|
||||
if (isDuplicate) {
|
||||
albumNameError = errorMessageString
|
||||
albumNameError = albumNameExistsError
|
||||
} else {
|
||||
onCreateAlbum(name)
|
||||
showAddAlbumDialog = false
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.anthonyla.paperize.presentation.theme.AppShapes
|
||||
import com.anthonyla.paperize.presentation.theme.AppBorderWidths
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -20,15 +19,17 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PhotoAlbum
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
@@ -37,6 +38,7 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import coil3.compose.AsyncImage
|
||||
import coil3.request.ImageRequest
|
||||
import coil3.size.Size
|
||||
@@ -54,8 +56,11 @@ fun AlbumItem(
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val showCoverUri by remember(album.coverUri) {
|
||||
mutableStateOf(!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri))
|
||||
var showCoverUri by remember(album.coverUri) { mutableStateOf(false) }
|
||||
LaunchedEffect(album.coverUri) {
|
||||
showCoverUri = withContext(Dispatchers.IO) {
|
||||
!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri)
|
||||
}
|
||||
}
|
||||
|
||||
InteractiveCard(
|
||||
@@ -87,7 +92,7 @@ fun AlbumItem(
|
||||
if (showCoverUri) {
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context)
|
||||
.data(Uri.parse(album.coverUri))
|
||||
.data(album.coverUri!!.toUri())
|
||||
.size(Size(400, 400)) // Limit size for performance
|
||||
.build(),
|
||||
contentDescription = album.name,
|
||||
@@ -126,9 +131,9 @@ fun AlbumItem(
|
||||
private fun isValidUri(context: Context, uriString: String?): Boolean {
|
||||
if (uriString.isNullOrEmpty()) return false
|
||||
return try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val uri = uriString.toUri()
|
||||
context.contentResolver.openInputStream(uri)?.use { true } ?: false
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.anthonyla.paperize.R
|
||||
@@ -51,9 +52,16 @@ fun NotificationPermissionScreen(
|
||||
}
|
||||
|
||||
OnboardingLayout(
|
||||
icon = Icons.Default.Notifications,
|
||||
title = stringResource(R.string.notification_permission_title),
|
||||
modifier = modifier,
|
||||
iconContent = {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Notifications,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(AppIconSizes.huge),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
},
|
||||
content = {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
|
||||
@@ -25,7 +25,7 @@ fun PrivacyScreen(
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.privacy_screen)) },
|
||||
title = { Text(stringResource(R.string.privacy_policy)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onNavigateBack) {
|
||||
Icon(
|
||||
|
||||
@@ -17,17 +17,17 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.presentation.common.components.SettingSwitchItem
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
import com.anthonyla.paperize.core.util.BatteryOptimizationUtil
|
||||
import com.anthonyla.paperize.core.util.BatteryOptimizationUtil.isIgnoringBatteryOptimizations
|
||||
import com.anthonyla.paperize.core.util.BatteryOptimizationUtil.requestIgnoreBatteryOptimizations
|
||||
|
||||
@@ -42,15 +42,15 @@ fun SettingsScreen(
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: SettingsViewModel = hiltViewModel()
|
||||
) {
|
||||
val appSettings by viewModel.appSettings.collectAsState()
|
||||
val wallpaperMode by viewModel.wallpaperMode.collectAsState()
|
||||
val appSettings by viewModel.appSettings.collectAsStateWithLifecycle()
|
||||
val wallpaperMode by viewModel.wallpaperMode.collectAsStateWithLifecycle()
|
||||
var showResetDialog by remember { mutableStateOf(false) }
|
||||
var showModeChangeDialog by remember { mutableStateOf(false) }
|
||||
var pendingMode by remember { mutableStateOf<com.anthonyla.paperize.core.WallpaperMode?>(null) }
|
||||
val context = LocalContext.current
|
||||
|
||||
var isIgnoringBatteryOptimizations by remember {
|
||||
mutableStateOf(BatteryOptimizationUtil.isIgnoringBatteryOptimizations(context))
|
||||
mutableStateOf(isIgnoringBatteryOptimizations(context))
|
||||
}
|
||||
|
||||
// Refresh battery optimization status when returning to the screen
|
||||
@@ -58,7 +58,7 @@ fun SettingsScreen(
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) {
|
||||
isIgnoringBatteryOptimizations = BatteryOptimizationUtil.isIgnoringBatteryOptimizations(context)
|
||||
isIgnoringBatteryOptimizations = isIgnoringBatteryOptimizations(context)
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
@@ -178,7 +178,7 @@ fun SettingsScreen(
|
||||
SettingSwitchItem(
|
||||
title = stringResource(R.string.dynamic_theming),
|
||||
description = stringResource(R.string.material_you),
|
||||
checked = appSettings?.dynamicTheming ?: true,
|
||||
checked = appSettings?.dynamicTheming ?: false,
|
||||
onCheckedChange = { viewModel.updateDynamicTheming(it) }
|
||||
)
|
||||
|
||||
@@ -250,8 +250,8 @@ fun SettingsScreen(
|
||||
|
||||
if (!isIgnoringBatteryOptimizations) {
|
||||
Button(
|
||||
onClick = {
|
||||
BatteryOptimizationUtil.requestIgnoreBatteryOptimizations(context)
|
||||
onClick = {
|
||||
requestIgnoreBatteryOptimizations(context)
|
||||
}
|
||||
) {
|
||||
Text(stringResource(R.string.check_status))
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.anthonyla.paperize.presentation.screens.settings
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
@@ -26,6 +27,10 @@ class SettingsViewModel @Inject constructor(
|
||||
private val wallpaperScheduler: WallpaperScheduler
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SettingsViewModel"
|
||||
}
|
||||
|
||||
val appSettings: StateFlow<AppSettings?> = settingsRepository.getAppSettingsFlow()
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
@@ -79,9 +84,11 @@ class SettingsViewModel @Inject constructor(
|
||||
wallpaperScheduler.cancelAllWallpaperChanges()
|
||||
|
||||
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
|
||||
when (albumRepository.deleteAllAlbums()) {
|
||||
when (val result = albumRepository.deleteAllAlbums()) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error deleting albums during mode switch", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
|
||||
@@ -103,9 +110,11 @@ class SettingsViewModel @Inject constructor(
|
||||
wallpaperScheduler.cancelAllWallpaperChanges()
|
||||
|
||||
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
|
||||
when (albumRepository.deleteAllAlbums()) {
|
||||
when (val result = albumRepository.deleteAllAlbums()) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error deleting albums during reset", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.anthonyla.paperize.presentation.screens.sort
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
@@ -25,6 +26,11 @@ class SortViewModel @Inject constructor(
|
||||
private val albumRepository: AlbumRepository,
|
||||
private val wallpaperRepository: WallpaperRepository
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SortViewModel"
|
||||
}
|
||||
|
||||
private val sortRoute = savedStateHandle.toRoute<SortRoute>()
|
||||
private val albumId: String = sortRoute.albumId
|
||||
|
||||
@@ -42,9 +48,9 @@ class SortViewModel @Inject constructor(
|
||||
private fun loadAlbumData() {
|
||||
viewModelScope.launch {
|
||||
val album = albumRepository.getAlbumById(albumId).first()
|
||||
val wallpapers = wallpaperRepository.getWallpapersByAlbum(albumId).first()
|
||||
val wallpapers = wallpaperRepository.getDirectWallpapersByAlbum(albumId).first()
|
||||
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = album?.folders ?: emptyList(),
|
||||
wallpapers = wallpapers
|
||||
)
|
||||
@@ -56,19 +62,25 @@ class SortViewModel @Inject constructor(
|
||||
var hasError = false
|
||||
|
||||
// Update folders with new display orders
|
||||
state.value.folders.forEach { folder ->
|
||||
when (albumRepository.updateFolder(folder)) {
|
||||
_state.value.folders.forEach { folder ->
|
||||
when (val result = albumRepository.updateFolder(folder)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> hasError = true
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
hasError = true
|
||||
Log.e(TAG, "Error updating folder", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
|
||||
// Update wallpapers with new display orders
|
||||
state.value.wallpapers.forEach { wallpaper ->
|
||||
when (wallpaperRepository.updateWallpaper(wallpaper)) {
|
||||
_state.value.wallpapers.forEach { wallpaper ->
|
||||
when (val result = wallpaperRepository.updateWallpaper(wallpaper)) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> hasError = true
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
hasError = true
|
||||
Log.e(TAG, "Error updating wallpaper", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
}
|
||||
@@ -84,38 +96,44 @@ class SortViewModel @Inject constructor(
|
||||
fun onEvent(event: SortEvent) {
|
||||
when (event) {
|
||||
is SortEvent.LoadSortView -> {
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = event.folders,
|
||||
wallpapers = event.wallpapers
|
||||
)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftFolder -> {
|
||||
val fromUri = event.from.key as? String ?: return
|
||||
val toUri = event.to.key as? String ?: return
|
||||
val updatedFolders = com.anthonyla.paperize.core.util.WallpaperSorter.shiftFolder(
|
||||
folders = state.value.folders,
|
||||
fromUri = event.from.key as String,
|
||||
toUri = event.to.key as String
|
||||
fromUri = fromUri,
|
||||
toUri = toUri
|
||||
)
|
||||
_state.value = state.value.copy(folders = updatedFolders)
|
||||
_state.value = _state.value.copy(folders = updatedFolders)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftFolderWallpaper -> {
|
||||
val fromUri = event.from.key as? String ?: return
|
||||
val toUri = event.to.key as? String ?: return
|
||||
val updatedFolders = com.anthonyla.paperize.core.util.WallpaperSorter.shiftWallpaperInFolder(
|
||||
folders = state.value.folders,
|
||||
folderId = event.folderId,
|
||||
fromUri = event.from.key as String,
|
||||
toUri = event.to.key as String
|
||||
fromUri = fromUri,
|
||||
toUri = toUri
|
||||
)
|
||||
_state.value = state.value.copy(folders = updatedFolders)
|
||||
_state.value = _state.value.copy(folders = updatedFolders)
|
||||
}
|
||||
|
||||
is SortEvent.ShiftWallpaper -> {
|
||||
val fromUri = event.from.key as? String ?: return
|
||||
val toUri = event.to.key as? String ?: return
|
||||
val updatedWallpapers = com.anthonyla.paperize.core.util.WallpaperSorter.shiftWallpaper(
|
||||
wallpapers = state.value.wallpapers,
|
||||
fromUri = event.from.key as String,
|
||||
toUri = event.to.key as String
|
||||
fromUri = fromUri,
|
||||
toUri = toUri
|
||||
)
|
||||
_state.value = state.value.copy(wallpapers = updatedWallpapers)
|
||||
_state.value = _state.value.copy(wallpapers = updatedWallpapers)
|
||||
}
|
||||
|
||||
is SortEvent.Reset -> {
|
||||
@@ -128,7 +146,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = true
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
@@ -140,7 +158,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = false
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
@@ -152,7 +170,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = true
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
@@ -164,7 +182,7 @@ class SortViewModel @Inject constructor(
|
||||
wallpapers = state.value.wallpapers,
|
||||
ascending = false
|
||||
)
|
||||
_state.value = state.value.copy(
|
||||
_state.value = _state.value.copy(
|
||||
folders = sortedFolders,
|
||||
wallpapers = sortedWallpapers
|
||||
)
|
||||
|
||||
@@ -22,7 +22,6 @@ import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
@@ -43,10 +42,10 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -130,7 +129,7 @@ fun SortViewScreen(
|
||||
AnimatedContent(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
targetState = !expandedFolderId.isNullOrEmpty(),
|
||||
label = "",
|
||||
label = "sort_view_content",
|
||||
) { targetState ->
|
||||
with(this@SharedTransitionLayout) {
|
||||
if (!targetState) {
|
||||
@@ -155,7 +154,7 @@ fun SortViewScreen(
|
||||
ReorderableItem(
|
||||
state = reorderableLazyListStateFolder,
|
||||
key = folder.uri
|
||||
) { isDragging ->
|
||||
) { _ ->
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
Card(
|
||||
modifier = Modifier
|
||||
@@ -234,7 +233,7 @@ fun SortViewScreen(
|
||||
ReorderableItem(
|
||||
reorderableLazyListStateWallpaper,
|
||||
key = wallpaper.uri
|
||||
) { isDragging ->
|
||||
) { _ ->
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
Card(
|
||||
modifier = Modifier
|
||||
@@ -357,7 +356,7 @@ fun SortViewScreen(
|
||||
ReorderableItem(
|
||||
reorderableFolderWallpapersState,
|
||||
key = wallpaper.uri
|
||||
) { isDragging ->
|
||||
) { _ ->
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
Card(
|
||||
modifier = Modifier
|
||||
|
||||
@@ -1,16 +1,34 @@
|
||||
package com.anthonyla.paperize.presentation.screens.startup
|
||||
import com.anthonyla.paperize.presentation.theme.AppIconSizes
|
||||
import com.anthonyla.paperize.presentation.components.OnboardingLayout
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import android.graphics.Canvas
|
||||
import androidx.core.graphics.createBitmap
|
||||
import androidx.appcompat.content.res.AppCompatResources
|
||||
import com.anthonyla.paperize.presentation.components.OnboardingLayout
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
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.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Wallpaper
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
@@ -25,12 +43,34 @@ import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
@Composable
|
||||
fun StartupScreen(
|
||||
onAgree: () -> Unit,
|
||||
onPrivacyClick: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val appIcon = remember {
|
||||
val drawable = AppCompatResources.getDrawable(context, R.mipmap.ic_launcher_round)
|
||||
if (drawable != null) {
|
||||
val size = 192 // Use a fixed high resolution size
|
||||
val bitmap = createBitmap(size, size)
|
||||
val canvas = Canvas(bitmap)
|
||||
drawable.setBounds(0, 0, size, size)
|
||||
drawable.draw(canvas)
|
||||
bitmap.asImageBitmap()
|
||||
} else null
|
||||
}
|
||||
|
||||
OnboardingLayout(
|
||||
icon = Icons.Default.Wallpaper,
|
||||
title = stringResource(R.string.app_name),
|
||||
modifier = modifier,
|
||||
iconContent = {
|
||||
if (appIcon != null) {
|
||||
Image(
|
||||
bitmap = appIcon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(100.dp)
|
||||
)
|
||||
}
|
||||
},
|
||||
content = {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
@@ -48,34 +88,48 @@ fun StartupScreen(
|
||||
|
||||
// Cleaner privacy notice
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPrivacyClick() },
|
||||
shape = MaterialTheme.shapes.large,
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
||||
),
|
||||
border = androidx.compose.foundation.BorderStroke(
|
||||
border = BorderStroke(
|
||||
width = 1.dp,
|
||||
color = MaterialTheme.colorScheme.outlineVariant
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(AppSpacing.large)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(AppSpacing.large),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.privacy_notice),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.privacy_notice),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(AppSpacing.small))
|
||||
Spacer(modifier = Modifier.height(AppSpacing.small))
|
||||
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.please_read_and_agree_to_the_following_privacy_notice_to_use_the_app
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
Text(
|
||||
text = stringResource(
|
||||
R.string.please_read_and_agree_to_the_following_privacy_notice_to_use_the_app
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = AppSpacing.small)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
package com.anthonyla.paperize.presentation.screens.storage
|
||||
import com.anthonyla.paperize.presentation.theme.AppIconSizes
|
||||
import com.anthonyla.paperize.presentation.components.OnboardingLayout
|
||||
import com.anthonyla.paperize.core.util.PermissionUtil
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
|
||||
/**
|
||||
* Screen to request storage permission for wallpaper preview
|
||||
* Allows optional MANAGE_EXTERNAL_STORAGE permission to read current wallpaper
|
||||
*/
|
||||
@Composable
|
||||
fun StoragePermissionScreen(
|
||||
onContinue: () -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
var permissionGranted by remember { mutableStateOf(PermissionUtil.hasStoragePermission()) }
|
||||
// Check permission status on resume (when user returns from settings)
|
||||
DisposableEffect(Unit) {
|
||||
val listener = object : DefaultLifecycleObserver {
|
||||
override fun onResume(owner: LifecycleOwner) {
|
||||
permissionGranted = PermissionUtil.hasStoragePermission()
|
||||
}
|
||||
}
|
||||
val lifecycleOwner = context as? LifecycleOwner
|
||||
lifecycleOwner?.lifecycle?.addObserver(listener)
|
||||
|
||||
onDispose {
|
||||
lifecycleOwner?.lifecycle?.removeObserver(listener)
|
||||
}
|
||||
}
|
||||
|
||||
// Automatically continue when permission is granted
|
||||
LaunchedEffect(permissionGranted) {
|
||||
if (permissionGranted) {
|
||||
onContinue()
|
||||
}
|
||||
}
|
||||
|
||||
OnboardingLayout(
|
||||
icon = Icons.Default.Folder,
|
||||
title = stringResource(R.string.storage_permission_title),
|
||||
modifier = modifier,
|
||||
content = {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.medium)
|
||||
) {
|
||||
// Cleaner explanation card
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.5f)
|
||||
),
|
||||
border = androidx.compose.foundation.BorderStroke(
|
||||
width = 1.dp,
|
||||
color = MaterialTheme.colorScheme.outlineVariant
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(AppSpacing.large),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.small),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.storage_permission_description),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
textAlign = TextAlign.Center,
|
||||
color = MaterialTheme.colorScheme.onTertiaryContainer
|
||||
)
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.storage_permission_optional),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onTertiaryContainer.copy(alpha = 0.8f),
|
||||
textAlign = TextAlign.Center,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
// Allow button
|
||||
Button(
|
||||
onClick = {
|
||||
if (!PermissionUtil.hasStoragePermission()) {
|
||||
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION).apply {
|
||||
data = Uri.parse("package:${context.packageName}")
|
||||
}
|
||||
context.startActivity(intent)
|
||||
} else {
|
||||
onContinue()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large
|
||||
) {
|
||||
Text(
|
||||
text = if (permissionGranted) {
|
||||
stringResource(R.string.permission_granted)
|
||||
} else {
|
||||
stringResource(R.string.allow)
|
||||
},
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(vertical = AppSpacing.small)
|
||||
)
|
||||
}
|
||||
|
||||
// Continue without permission button
|
||||
FilledTonalButton(
|
||||
onClick = onContinue,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
colors = ButtonDefaults.filledTonalButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
contentColor = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.continue_without_storage),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
|
||||
modifier = Modifier.padding(vertical = AppSpacing.small)
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.Home
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
@@ -31,7 +32,6 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -43,9 +43,7 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
@@ -56,7 +54,6 @@ import com.anthonyla.paperize.presentation.screens.wallpaper.components.SettingS
|
||||
import com.anthonyla.paperize.presentation.screens.wallpaper.components.SettingSwitchWithSlider
|
||||
import com.anthonyla.paperize.presentation.screens.wallpaper.components.TimeIntervalPicker
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
enum class AlbumSelectionContext {
|
||||
HOME, LOCK, BOTH, LIVE
|
||||
@@ -65,7 +62,7 @@ enum class AlbumSelectionContext {
|
||||
@Composable
|
||||
fun WallpaperScreen(
|
||||
albums: List<AlbumSummary>,
|
||||
scheduleSettings: ScheduleSettings,
|
||||
persistedScheduleSettings: ScheduleSettings,
|
||||
appSettings: AppSettings,
|
||||
wallpaperMode: WallpaperMode,
|
||||
onToggleChanger: (Boolean) -> Unit,
|
||||
@@ -73,37 +70,30 @@ fun WallpaperScreen(
|
||||
onSelectLockAlbum: (AlbumSummary?) -> Unit,
|
||||
onSelectLiveAlbum: (AlbumSummary?) -> Unit,
|
||||
onUpdateScheduleSettings: (ScheduleSettings) -> Unit,
|
||||
onUpdateScheduleSettingsDebounced: (ScheduleSettings) -> Unit,
|
||||
onChangeWallpaperNow: () -> Unit,
|
||||
homeWallpaperUri: String?,
|
||||
lockWallpaperUri: String?,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
var showAlbumSelectionSheet by rememberSaveable { mutableStateOf(false) }
|
||||
var albumSelectionContext by rememberSaveable { mutableStateOf(AlbumSelectionContext.BOTH) }
|
||||
var showEmptyAlbumWarning by remember { mutableStateOf(false) }
|
||||
var showEmptyAlbumWarning by rememberSaveable { mutableStateOf(false) }
|
||||
var scheduleSettings by remember { mutableStateOf(persistedScheduleSettings) }
|
||||
|
||||
// Settings debouncing
|
||||
var pendingSettings by remember { mutableStateOf<ScheduleSettings?>(null) }
|
||||
var lastSettingsChangeTimestamp by remember { mutableLongStateOf(0L) }
|
||||
|
||||
// Debounce settings updates to avoid excessive database writes and rescheduling
|
||||
LaunchedEffect(lastSettingsChangeTimestamp) {
|
||||
if (lastSettingsChangeTimestamp > 0 && pendingSettings != null) {
|
||||
delay(Constants.SETTINGS_DEBOUNCE_MS)
|
||||
pendingSettings?.let { onUpdateScheduleSettings(it) }
|
||||
pendingSettings = null
|
||||
}
|
||||
// Keep an immediate local draft so a slider value waiting for the ViewModel debounce
|
||||
// is included in a switch or other setting changed before that debounce expires.
|
||||
LaunchedEffect(persistedScheduleSettings) {
|
||||
scheduleSettings = persistedScheduleSettings
|
||||
}
|
||||
|
||||
// Helper function to update settings with debouncing
|
||||
fun updateSettingsDebounced(newSettings: ScheduleSettings) {
|
||||
pendingSettings = newSettings
|
||||
lastSettingsChangeTimestamp = System.currentTimeMillis()
|
||||
scheduleSettings = newSettings
|
||||
onUpdateScheduleSettingsDebounced(newSettings)
|
||||
}
|
||||
|
||||
// Wrapper for immediate updates that cancels pending debounced updates
|
||||
fun updateSettingsImmediate(newSettings: ScheduleSettings) {
|
||||
// Cancel any pending debounced updates
|
||||
pendingSettings = null
|
||||
lastSettingsChangeTimestamp = 0L
|
||||
// Apply the update immediately
|
||||
scheduleSettings = newSettings
|
||||
onUpdateScheduleSettings(newSettings)
|
||||
}
|
||||
|
||||
@@ -165,9 +155,10 @@ fun WallpaperScreen(
|
||||
stringResource(R.string.none)
|
||||
)
|
||||
|
||||
var selectedScalingIndex by rememberSaveable {
|
||||
val scalingTypeFromSettings = if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType
|
||||
var selectedScalingIndex by remember(scalingTypeFromSettings) {
|
||||
mutableIntStateOf(
|
||||
when (if (wallpaperMode == WallpaperMode.LIVE) scheduleSettings.liveScalingType else scheduleSettings.homeScalingType) {
|
||||
when (scalingTypeFromSettings) {
|
||||
ScalingType.FILL -> 0
|
||||
ScalingType.FIT -> 1
|
||||
ScalingType.STRETCH -> 2
|
||||
@@ -293,7 +284,8 @@ fun WallpaperScreen(
|
||||
}
|
||||
|
||||
// Album Selection - Enhanced with better card styling
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
// Only show album selection when at least one screen is enabled
|
||||
if (wallpaperMode == WallpaperMode.STATIC && (homeEnabled || lockEnabled)) {
|
||||
if (homeEnabled && lockEnabled) {
|
||||
// Lock Screen Album
|
||||
Card(
|
||||
@@ -363,7 +355,8 @@ fun WallpaperScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(AppSpacing.large),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
@@ -373,12 +366,14 @@ fun WallpaperScreen(
|
||||
stringResource(R.string.no_album_selected)
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.home_album_label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
@@ -387,7 +382,7 @@ fun WallpaperScreen(
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowForward,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -443,7 +438,7 @@ fun WallpaperScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if (wallpaperMode == WallpaperMode.LIVE) {
|
||||
// Live Mode: Single Album Selector
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLow,
|
||||
@@ -518,7 +513,7 @@ fun WallpaperScreen(
|
||||
title = stringResource(R.string.interval_text),
|
||||
minutes = scheduleSettings.homeIntervalMinutes,
|
||||
onMinutesChange = { minutes ->
|
||||
onUpdateScheduleSettings(
|
||||
updateSettingsDebounced(
|
||||
scheduleSettings.copy(
|
||||
homeIntervalMinutes = minutes,
|
||||
lockIntervalMinutes = minutes
|
||||
@@ -570,7 +565,11 @@ fun WallpaperScreen(
|
||||
|
||||
// Current Wallpaper Preview (Static Mode Only)
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
CurrentWallpaperPreview(animate = appSettings.animate)
|
||||
CurrentWallpaperPreview(
|
||||
homeWallpaperUri = homeWallpaperUri,
|
||||
lockWallpaperUri = lockWallpaperUri,
|
||||
animate = appSettings.animate
|
||||
)
|
||||
HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.small))
|
||||
}
|
||||
|
||||
@@ -644,6 +643,22 @@ fun WallpaperScreen(
|
||||
}
|
||||
}
|
||||
|
||||
if (scheduleSettings.enableChanger) {
|
||||
Button(
|
||||
onClick = onChangeWallpaperNow,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(
|
||||
PaddingValues(
|
||||
horizontal = AppSpacing.small,
|
||||
vertical = AppSpacing.extraSmall
|
||||
)
|
||||
)
|
||||
) {
|
||||
Text(text = stringResource(R.string.change_wallpaper_now))
|
||||
}
|
||||
}
|
||||
|
||||
// Shuffle Card
|
||||
Card(
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
@@ -721,9 +736,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.darkenPercentage else scheduleSettings.liveEffects.darkenPercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableDarken,
|
||||
lockChecked = scheduleSettings.lockEffects.enableDarken,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableDarken = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableDarken = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.darkenPercentage
|
||||
else scheduleSettings.lockEffects.darkenPercentage
|
||||
} else scheduleSettings.liveEffects.darkenPercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.darkenPercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -772,9 +810,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.blurPercentage else scheduleSettings.liveEffects.blurPercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableBlur,
|
||||
lockChecked = scheduleSettings.lockEffects.enableBlur,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableBlur = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableBlur = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.blurPercentage
|
||||
else scheduleSettings.lockEffects.blurPercentage
|
||||
} else scheduleSettings.liveEffects.blurPercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.blurPercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -823,9 +884,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.vignettePercentage else scheduleSettings.liveEffects.vignettePercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableVignette,
|
||||
lockChecked = scheduleSettings.lockEffects.enableVignette,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableVignette = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableVignette = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.vignettePercentage
|
||||
else scheduleSettings.lockEffects.vignettePercentage
|
||||
} else scheduleSettings.liveEffects.vignettePercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.vignettePercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -874,9 +958,32 @@ fun WallpaperScreen(
|
||||
)
|
||||
}
|
||||
},
|
||||
// Show separate sliders only when both enabled AND separate schedules is on (Static only)
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC && homeEnabled && lockEnabled && scheduleSettings.separateSchedules,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) scheduleSettings.homeEffects.grayscalePercentage else scheduleSettings.liveEffects.grayscalePercentage,
|
||||
homeChecked = scheduleSettings.homeEffects.enableGrayscale,
|
||||
lockChecked = scheduleSettings.lockEffects.enableGrayscale,
|
||||
onHomeCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
homeEffects = scheduleSettings.homeEffects.copy(
|
||||
enableGrayscale = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
onLockCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
lockEffects = scheduleSettings.lockEffects.copy(
|
||||
enableGrayscale = enabled
|
||||
)
|
||||
)
|
||||
)
|
||||
},
|
||||
bothEnabled = wallpaperMode == WallpaperMode.STATIC &&
|
||||
homeEnabled && lockEnabled,
|
||||
homePercentage = if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
if (homeEnabled) scheduleSettings.homeEffects.grayscalePercentage
|
||||
else scheduleSettings.lockEffects.grayscalePercentage
|
||||
} else scheduleSettings.liveEffects.grayscalePercentage,
|
||||
lockPercentage = scheduleSettings.lockEffects.grayscalePercentage,
|
||||
onPercentageChange = { homePercent, lockPercent ->
|
||||
if (wallpaperMode == WallpaperMode.STATIC) {
|
||||
@@ -949,12 +1056,12 @@ fun WallpaperScreen(
|
||||
// Change wallpaper on screen off
|
||||
SettingSwitch(
|
||||
title = R.string.change_on_screen_off,
|
||||
description = if (scheduleSettings.liveEffects.enableChangeOnScreenOn) null else R.string.change_wallpaper_when_screen_turns_off,
|
||||
checked = scheduleSettings.liveEffects.enableChangeOnScreenOn,
|
||||
description = if (scheduleSettings.liveEffects.enableChangeOnScreenOff) null else R.string.change_wallpaper_when_screen_turns_off,
|
||||
checked = scheduleSettings.liveEffects.enableChangeOnScreenOff,
|
||||
onCheckedChange = { enabled ->
|
||||
updateSettingsImmediate(
|
||||
scheduleSettings.copy(
|
||||
liveEffects = scheduleSettings.liveEffects.copy(enableChangeOnScreenOn = enabled)
|
||||
liveEffects = scheduleSettings.liveEffects.copy(enableChangeOnScreenOff = enabled)
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -1082,8 +1189,6 @@ fun WallpaperScreen(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Dismiss the bottom sheet after selection
|
||||
showAlbumSelectionSheet = false
|
||||
},
|
||||
onDismiss = { showAlbumSelectionSheet = false }
|
||||
)
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.anthonyla.paperize.presentation.theme.AppBorderWidths
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -20,7 +19,6 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.PhotoAlbum
|
||||
@@ -33,9 +31,13 @@ import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
@@ -44,7 +46,7 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import coil3.compose.AsyncImage
|
||||
import coil3.request.ImageRequest
|
||||
import coil3.size.Size
|
||||
@@ -118,8 +120,11 @@ private fun AlbumSelectionItem(
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val showCoverUri by remember(album.coverUri) {
|
||||
mutableStateOf(!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri))
|
||||
var showCoverUri by remember(album.coverUri) { mutableStateOf(false) }
|
||||
LaunchedEffect(album.coverUri) {
|
||||
showCoverUri = withContext(Dispatchers.IO) {
|
||||
!album.coverUri.isNullOrEmpty() && isValidUri(context, album.coverUri)
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
@@ -146,7 +151,7 @@ private fun AlbumSelectionItem(
|
||||
if (showCoverUri) {
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context)
|
||||
.data(Uri.parse(album.coverUri))
|
||||
.data(album.coverUri!!.toUri())
|
||||
.size(Size(Constants.LIST_THUMBNAIL_SIZE, Constants.LIST_THUMBNAIL_SIZE)) // Small thumbnail for list item
|
||||
.build(),
|
||||
contentDescription = album.name,
|
||||
@@ -197,9 +202,9 @@ private fun AlbumSelectionItem(
|
||||
private fun isValidUri(context: Context, uriString: String?): Boolean {
|
||||
if (uriString.isNullOrEmpty()) return false
|
||||
return try {
|
||||
val uri = Uri.parse(uriString)
|
||||
val uri = uriString.toUri()
|
||||
context.contentResolver.openInputStream(uri)?.use { true } ?: false
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,6 @@ import com.anthonyla.paperize.presentation.theme.AppMaxWidths
|
||||
import com.anthonyla.paperize.presentation.theme.AppBorderWidths
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.fadeIn
|
||||
@@ -22,21 +17,13 @@ import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
@@ -45,7 +32,6 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.presentation.theme.AppShapes
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
@@ -53,176 +39,42 @@ import coil3.compose.AsyncImage
|
||||
import coil3.request.ImageRequest
|
||||
import coil3.request.crossfade
|
||||
import coil3.size.Size
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* Retry helper for reading wallpapers with exponential backoff
|
||||
* Displays the home and lock wallpapers Paperize last applied.
|
||||
*
|
||||
* Android's WallpaperManager writes wallpapers to disk asynchronously after setBitmap() returns.
|
||||
* The encoding process can take 1-2 seconds, during which time reading the wallpaper back will
|
||||
* fail with ImageDecoder.DecodeException. This helper retries with increasing delays to allow
|
||||
* the system time to complete encoding.
|
||||
* The images are loaded from the recorded source URIs ([homeWallpaperUri]/[lockWallpaperUri]) via
|
||||
* Coil, rather than read back from WallpaperManager.getDrawable(): the latter is privacy-restricted
|
||||
* on modern Android and returns null without the optional all-files-access permission, which left
|
||||
* the preview blank. The URIs already carry the album's persisted read access, so no extra
|
||||
* permission is needed. They update reactively whenever Paperize changes the wallpaper.
|
||||
*
|
||||
* @param maxAttempts Maximum number of retry attempts (default 4)
|
||||
* @param delayMs Initial delay in milliseconds between retries (default 500ms)
|
||||
* @param block The operation to retry
|
||||
* @return The result of the operation, or null if all attempts fail
|
||||
*/
|
||||
private suspend fun <T> retryWallpaperRead(
|
||||
maxAttempts: Int = 4,
|
||||
delayMs: Long = Constants.WALLPAPER_READ_INITIAL_DELAY_MS,
|
||||
block: suspend () -> T
|
||||
): T? {
|
||||
var lastException: Exception? = null
|
||||
|
||||
repeat(maxAttempts) { attempt ->
|
||||
try {
|
||||
return block()
|
||||
} catch (e: android.graphics.ImageDecoder.DecodeException) {
|
||||
lastException = e
|
||||
// Only delay if we have more attempts left
|
||||
if (attempt < maxAttempts - 1) {
|
||||
// Exponential backoff: 500ms, 1000ms, 1500ms, 2000ms
|
||||
delay(delayMs * (attempt + 1))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// For non-decode exceptions, don't retry
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// All attempts failed
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays current home and lock screen wallpapers
|
||||
* Note: this shows the source image, not the exact cropped/scaled/effected on-screen result.
|
||||
*
|
||||
* Automatically updates when wallpapers change using WallpaperManager.OnColorsChangedListener.
|
||||
* This allows the preview to stay in sync with system wallpaper changes from any source
|
||||
* (this app's wallpaper changer, system settings, other apps, etc.).
|
||||
*
|
||||
* Uses smooth fade animations and placeholder boxes to prevent layout jumping.
|
||||
* Adapts to different screen sizes and orientations following Material 3 responsive design.
|
||||
* Respects the app's animate setting for accessibility and user preference.
|
||||
* Adapts to the device screen aspect ratio and respects the app's animate setting.
|
||||
*/
|
||||
@Composable
|
||||
fun CurrentWallpaperPreview(
|
||||
homeWallpaperUri: String?,
|
||||
lockWallpaperUri: String?,
|
||||
animate: Boolean = true,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val configuration = LocalConfiguration.current
|
||||
|
||||
var homeWallpaper by remember { mutableStateOf<Drawable?>(null) }
|
||||
var lockWallpaper by remember { mutableStateOf<Drawable?>(null) }
|
||||
var hasPermission by remember { mutableStateOf(true) }
|
||||
|
||||
// Use rememberSaveable to prevent reloading on navigation
|
||||
var refreshTrigger by rememberSaveable { mutableIntStateOf(0) }
|
||||
var pendingRefresh by remember { mutableStateOf(false) }
|
||||
var isLoading by remember { mutableStateOf(true) }
|
||||
|
||||
// Calculate appropriate aspect ratio based on device screen
|
||||
// Use actual screen dimensions for accurate wallpaper preview
|
||||
// Portrait-oriented preview: shorter screen dimension as width.
|
||||
val screenAspectRatio = remember(configuration) {
|
||||
val screenWidth = configuration.screenWidthDp.toFloat()
|
||||
val screenHeight = configuration.screenHeightDp.toFloat()
|
||||
// Use the shorter dimension as width for portrait-oriented preview
|
||||
val aspectRatio = min(screenWidth, screenHeight) / kotlin.math.max(screenWidth, screenHeight)
|
||||
aspectRatio
|
||||
min(screenWidth, screenHeight) / max(screenWidth, screenHeight)
|
||||
}
|
||||
|
||||
// Listen for wallpaper changes with debouncing
|
||||
// When both home and lock wallpapers are set, the listener fires twice.
|
||||
// Debouncing prevents multiple rapid refreshes that can cause UI flashing.
|
||||
DisposableEffect(Unit) {
|
||||
val wallpaperManager = WallpaperManager.getInstance(context)
|
||||
val handler = Handler(Looper.getMainLooper())
|
||||
val listener = WallpaperManager.OnColorsChangedListener { _, _ ->
|
||||
// Mark that a refresh is pending instead of triggering immediately
|
||||
pendingRefresh = true
|
||||
}
|
||||
|
||||
// Register listener for both home and lock screen wallpaper changes
|
||||
wallpaperManager.addOnColorsChangedListener(listener, handler)
|
||||
|
||||
onDispose {
|
||||
wallpaperManager.removeOnColorsChangedListener(listener)
|
||||
}
|
||||
}
|
||||
|
||||
// Debounced refresh effect
|
||||
// Waits 2 seconds after the last wallpaper change before refreshing
|
||||
// This ensures both home and lock wallpaper changes complete before preview updates
|
||||
LaunchedEffect(pendingRefresh) {
|
||||
if (pendingRefresh) {
|
||||
delay(Constants.WALLPAPER_CHANGE_DEBOUNCE_MS)
|
||||
// Atomically update state to prevent race conditions
|
||||
pendingRefresh = false
|
||||
refreshTrigger++
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch wallpapers on initial load and when refreshTrigger changes
|
||||
LaunchedEffect(refreshTrigger) {
|
||||
// Only set loading on initial load, not on refresh
|
||||
if (refreshTrigger == 0) {
|
||||
isLoading = true
|
||||
}
|
||||
|
||||
val (home, lock, hasAccess) = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val wallpaperManager = WallpaperManager.getInstance(context)
|
||||
|
||||
// API 34+ has getDrawable(int which), earlier versions use getDrawable()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
// Get home screen wallpaper with retry logic
|
||||
val homeDrawable = retryWallpaperRead {
|
||||
wallpaperManager.getDrawable(WallpaperManager.FLAG_SYSTEM)
|
||||
}
|
||||
|
||||
// Get lock screen wallpaper with retry logic
|
||||
val lockDrawable = retryWallpaperRead {
|
||||
wallpaperManager.getDrawable(WallpaperManager.FLAG_LOCK)
|
||||
} ?: homeDrawable
|
||||
|
||||
Triple(homeDrawable, lockDrawable, true)
|
||||
} else {
|
||||
// For API [31-33], use getDrawable() which returns the current wallpaper
|
||||
val drawable = retryWallpaperRead {
|
||||
wallpaperManager.drawable
|
||||
}
|
||||
Triple(drawable, drawable, true)
|
||||
}
|
||||
} catch (e: SecurityException) {
|
||||
Triple(null, null, false)
|
||||
} catch (e: Exception) {
|
||||
// Handle other exceptions silently
|
||||
Triple(null, null, true)
|
||||
}
|
||||
}
|
||||
// Update state on main thread
|
||||
homeWallpaper = home
|
||||
lockWallpaper = lock
|
||||
hasPermission = hasAccess
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
// Don't show if no permission
|
||||
if (!hasPermission) {
|
||||
return
|
||||
}
|
||||
|
||||
// Always render the Card with reserved space to prevent layout jumping
|
||||
// Constrain max width for tablets following Material 3 responsive design
|
||||
Card(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.widthIn(max = AppMaxWidths.contentMaxWidth) // Material 3 guideline: max content width on large screens
|
||||
.widthIn(max = AppMaxWidths.contentMaxWidth)
|
||||
.padding(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall),
|
||||
shape = AppShapes.cardShape,
|
||||
colors = CardDefaults.cardColors(
|
||||
@@ -249,8 +101,7 @@ fun CurrentWallpaperPreview(
|
||||
) {
|
||||
// Lock wallpaper preview (on the left)
|
||||
WallpaperPreviewBox(
|
||||
wallpaper = lockWallpaper,
|
||||
isLoading = isLoading,
|
||||
wallpaperUri = lockWallpaperUri,
|
||||
aspectRatio = screenAspectRatio,
|
||||
contentDescription = stringResource(R.string.content_desc_current_lock_wallpaper),
|
||||
animate = animate,
|
||||
@@ -259,8 +110,7 @@ fun CurrentWallpaperPreview(
|
||||
|
||||
// Home wallpaper preview (on the right)
|
||||
WallpaperPreviewBox(
|
||||
wallpaper = homeWallpaper,
|
||||
isLoading = isLoading,
|
||||
wallpaperUri = homeWallpaperUri,
|
||||
aspectRatio = screenAspectRatio,
|
||||
contentDescription = stringResource(R.string.content_desc_current_home_wallpaper),
|
||||
animate = animate,
|
||||
@@ -272,15 +122,12 @@ fun CurrentWallpaperPreview(
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a single wallpaper preview with smooth fade animation
|
||||
*
|
||||
* Uses device screen aspect ratio for accurate representation and placeholder
|
||||
* background to prevent layout jumping during loading.
|
||||
* A single wallpaper preview. Shows a placeholder background until [wallpaperUri] is non-null,
|
||||
* then fades in the image. Uses the device screen aspect ratio to avoid layout jumps.
|
||||
*/
|
||||
@Composable
|
||||
private fun WallpaperPreviewBox(
|
||||
wallpaper: Drawable?,
|
||||
isLoading: Boolean,
|
||||
wallpaperUri: String?,
|
||||
aspectRatio: Float,
|
||||
contentDescription: String,
|
||||
animate: Boolean,
|
||||
@@ -300,26 +147,16 @@ private fun WallpaperPreviewBox(
|
||||
.background(MaterialTheme.colorScheme.surfaceContainerHighest)
|
||||
) {
|
||||
AnimatedVisibility(
|
||||
visible = !isLoading && wallpaper != null,
|
||||
enter = if (animate) {
|
||||
fadeIn(animationSpec = tween(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt()))
|
||||
} else {
|
||||
fadeIn(animationSpec = tween(0))
|
||||
},
|
||||
exit = if (animate) {
|
||||
fadeOut(animationSpec = tween(Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt()))
|
||||
} else {
|
||||
fadeOut(animationSpec = tween(0))
|
||||
}
|
||||
visible = wallpaperUri != null,
|
||||
enter = fadeIn(animationSpec = tween(if (animate) Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt() else 0)),
|
||||
exit = fadeOut(animationSpec = tween(if (animate) Constants.PERMISSION_SCREEN_TRANSITION_DELAY_MS.toInt() else 0))
|
||||
) {
|
||||
wallpaper?.let { drawable ->
|
||||
wallpaperUri?.let { uri ->
|
||||
AsyncImage(
|
||||
model = ImageRequest.Builder(context)
|
||||
.data(drawable)
|
||||
.size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT)) // Limit size for performance - suitable for preview
|
||||
.data(uri)
|
||||
.size(Size(Constants.PREVIEW_THUMBNAIL_WIDTH, Constants.PREVIEW_THUMBNAIL_HEIGHT))
|
||||
.crossfade(true)
|
||||
.memoryCachePolicy(coil3.request.CachePolicy.DISABLED) // Don't cache in memory (already in drawable)
|
||||
.diskCachePolicy(coil3.request.CachePolicy.DISABLED) // Don't cache on disk (already system-managed)
|
||||
.build(),
|
||||
contentDescription = contentDescription,
|
||||
contentScale = ContentScale.Crop,
|
||||
|
||||
@@ -20,6 +20,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
|
||||
@@ -46,7 +47,8 @@ fun SettingSwitch(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(AppSpacing.large),
|
||||
.padding(AppSpacing.large)
|
||||
.semantics(mergeDescendants = true) {},
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
package com.anthonyla.paperize.presentation.screens.wallpaper.components
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.compose.animation.animateContentSize
|
||||
@@ -9,6 +8,8 @@ import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Switch
|
||||
@@ -21,16 +22,16 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Setting switch with percentage sliders for home and lock screens
|
||||
* Enhanced with Material 3 Expressive design
|
||||
* Effect control with either one switch/slider or independent HOME and LOCK controls.
|
||||
*/
|
||||
@Composable
|
||||
fun SettingSwitchWithSlider(
|
||||
@@ -42,17 +43,25 @@ fun SettingSwitchWithSlider(
|
||||
homePercentage: Int,
|
||||
lockPercentage: Int,
|
||||
onPercentageChange: (Int, Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
modifier: Modifier = Modifier,
|
||||
homeChecked: Boolean = checked,
|
||||
lockChecked: Boolean = checked,
|
||||
onHomeCheckedChange: (Boolean) -> Unit = onCheckedChange,
|
||||
onLockCheckedChange: (Boolean) -> Unit = onCheckedChange
|
||||
) {
|
||||
var homeValue by remember(homePercentage) { mutableFloatStateOf(homePercentage.toFloat()) }
|
||||
var lockValue by remember(lockPercentage) { mutableFloatStateOf(lockPercentage.toFloat()) }
|
||||
var homeValue by remember(homePercentage) {
|
||||
mutableFloatStateOf(homePercentage.toFloat())
|
||||
}
|
||||
var lockValue by remember(lockPercentage) {
|
||||
mutableFloatStateOf(lockPercentage.toFloat())
|
||||
}
|
||||
|
||||
androidx.compose.material3.Card(
|
||||
Card(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(PaddingValues(horizontal = AppSpacing.small, vertical = AppSpacing.extraSmall)),
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
colors = androidx.compose.material3.CardDefaults.cardColors(
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
|
||||
)
|
||||
) {
|
||||
@@ -62,143 +71,162 @@ fun SettingSwitchWithSlider(
|
||||
.padding(AppSpacing.large),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.large)
|
||||
) {
|
||||
// Header with title and switch
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)
|
||||
) {
|
||||
if (bothEnabled) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)) {
|
||||
Text(
|
||||
text = stringResource(title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
if (!checked) {
|
||||
Text(
|
||||
text = stringResource(description),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
ScreenEffectControl(
|
||||
label = R.string.home,
|
||||
checked = homeChecked,
|
||||
onCheckedChange = onHomeCheckedChange,
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), lockValue.roundToInt())
|
||||
}
|
||||
)
|
||||
ScreenEffectControl(
|
||||
label = R.string.lock,
|
||||
checked = lockChecked,
|
||||
onCheckedChange = onLockCheckedChange,
|
||||
value = lockValue,
|
||||
onValueChange = {
|
||||
lockValue = it
|
||||
onPercentageChange(homeValue.roundToInt(), it.roundToInt())
|
||||
}
|
||||
)
|
||||
} else {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.semantics(mergeDescendants = true) {},
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.extraSmall)
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(description),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
text = stringResource(title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
|
||||
// Sliders (shown when enabled)
|
||||
if (checked) {
|
||||
if (bothEnabled) {
|
||||
// Lock screen slider
|
||||
Column(modifier = Modifier.padding(horizontal = AppSpacing.small)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.lock),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${lockValue.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = lockValue,
|
||||
onValueChange = {
|
||||
lockValue = it
|
||||
onPercentageChange(homeValue.roundToInt(), it.roundToInt())
|
||||
},
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
|
||||
// Home screen slider
|
||||
Column(modifier = Modifier.padding(horizontal = AppSpacing.small)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.home),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${homeValue.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), lockValue.roundToInt())
|
||||
},
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Single slider (for whichever screen is enabled)
|
||||
Column(modifier = Modifier.padding(horizontal = AppSpacing.small)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
if (!checked) {
|
||||
Text(
|
||||
text = stringResource(description),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 2,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${homeValue.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = AppSpacing.medium)
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), it.roundToInt())
|
||||
},
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
|
||||
if (checked) {
|
||||
PercentageSlider(
|
||||
label = description,
|
||||
value = homeValue,
|
||||
onValueChange = {
|
||||
homeValue = it
|
||||
onPercentageChange(it.roundToInt(), it.roundToInt())
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScreenEffectControl(
|
||||
@StringRes label: Int,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit,
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = AppSpacing.small),
|
||||
verticalArrangement = Arrangement.spacedBy(AppSpacing.small)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(label),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = onCheckedChange
|
||||
)
|
||||
}
|
||||
if (checked) {
|
||||
PercentageSlider(
|
||||
label = label,
|
||||
value = value,
|
||||
onValueChange = onValueChange
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PercentageSlider(
|
||||
@StringRes label: Int,
|
||||
value: Float,
|
||||
onValueChange: (Float) -> Unit
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(label),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
Text(
|
||||
text = "${value.roundToInt()}%",
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = AppSpacing.medium)
|
||||
)
|
||||
}
|
||||
Slider(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
valueRange = Constants.MIN_EFFECT_PERCENTAGE.toFloat()..
|
||||
Constants.MAX_EFFECT_PERCENTAGE.toFloat(),
|
||||
steps = Constants.SLIDER_EFFECT_STEPS
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,8 @@ import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
@@ -21,13 +19,11 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.pluralStringResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
@@ -60,8 +56,8 @@ fun TimeIntervalPicker(
|
||||
var hourInput by remember(minutes) { mutableStateOf(initialHours.toString()) }
|
||||
var minuteInput by remember(minutes) { mutableStateOf(initialMins.toString()) }
|
||||
|
||||
// Debounce state - tracks when user last made a change
|
||||
var lastChangeTimestamp by remember { mutableStateOf(0L) }
|
||||
// Debounce state - tracks when user last made a change; reset when external `minutes` prop changes
|
||||
var lastChangeTimestamp by remember(minutes) { mutableStateOf(0L) }
|
||||
|
||||
// Debounced update - only fires after user stops typing
|
||||
LaunchedEffect(dayValue, hourValue, minuteValue, lastChangeTimestamp) {
|
||||
@@ -170,27 +166,28 @@ fun TimeIntervalPicker(
|
||||
@Composable
|
||||
private fun formatIntervalComposable(minutes: Int): String {
|
||||
val minUnit = stringResource(R.string.time_unit_min)
|
||||
val hourUnit = pluralStringResource(R.plurals.time_unit_hours, 1)
|
||||
val hoursUnit = pluralStringResource(R.plurals.time_unit_hours, 2)
|
||||
val dayUnit = pluralStringResource(R.plurals.time_unit_days, 1)
|
||||
val daysUnit = pluralStringResource(R.plurals.time_unit_days, 2)
|
||||
|
||||
return when {
|
||||
minutes < Constants.MINUTES_PER_HOUR -> "$minutes $minUnit"
|
||||
minutes < Constants.MINUTES_PER_DAY -> {
|
||||
val hours = minutes / Constants.MINUTES_PER_HOUR
|
||||
val h = minutes / Constants.MINUTES_PER_HOUR
|
||||
val remainingMins = minutes % Constants.MINUTES_PER_HOUR
|
||||
if (remainingMins == 0) "$hours ${if (hours > 1) hoursUnit else hourUnit}"
|
||||
else "$hours ${if (hours > 1) hoursUnit else hourUnit} $remainingMins $minUnit"
|
||||
val hUnit = pluralStringResource(R.plurals.time_unit_hours, h)
|
||||
if (remainingMins == 0) "$h $hUnit"
|
||||
else "$h $hUnit $remainingMins $minUnit"
|
||||
}
|
||||
else -> {
|
||||
val days = minutes / Constants.MINUTES_PER_DAY
|
||||
val d = minutes / Constants.MINUTES_PER_DAY
|
||||
val remainingMinutes = minutes % Constants.MINUTES_PER_DAY
|
||||
val remainingHours = remainingMinutes / Constants.MINUTES_PER_HOUR
|
||||
val finalMins = remainingMinutes % Constants.MINUTES_PER_HOUR
|
||||
val dUnit = pluralStringResource(R.plurals.time_unit_days, d)
|
||||
buildString {
|
||||
append("$days ${if (days > 1) daysUnit else dayUnit}")
|
||||
if (remainingHours > 0) append(" $remainingHours ${if (remainingHours > 1) hoursUnit else hourUnit}")
|
||||
append("$d $dUnit")
|
||||
if (remainingHours > 0) {
|
||||
val hUnit = pluralStringResource(R.plurals.time_unit_hours, remainingHours)
|
||||
append(" $remainingHours $hUnit")
|
||||
}
|
||||
if (finalMins > 0) append(" $finalMins $minUnit")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.graphics.vector.rememberVectorPainter
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
|
||||
import com.anthonyla.paperize.R
|
||||
@@ -35,9 +36,16 @@ fun WallpaperModeSelectionScreen(
|
||||
var selectedMode by remember { mutableStateOf<WallpaperMode?>(null) }
|
||||
|
||||
OnboardingLayout(
|
||||
icon = Icons.Default.Wallpaper,
|
||||
title = stringResource(R.string.choose_wallpaper_mode),
|
||||
modifier = modifier,
|
||||
iconContent = {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Wallpaper,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(AppIconSizes.huge),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
},
|
||||
content = {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.anthonyla.paperize.presentation.screens.wallpaper_mode_selection
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
import android.util.Log
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
@@ -16,6 +17,10 @@ class WallpaperModeSelectionViewModel @Inject constructor(
|
||||
private val wallpaperScheduler: com.anthonyla.paperize.service.worker.WallpaperScheduler
|
||||
) : ViewModel() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WModeSelectionViewModel"
|
||||
}
|
||||
|
||||
/**
|
||||
* Set wallpaper mode (STATIC or LIVE)
|
||||
*/
|
||||
@@ -25,9 +30,11 @@ class WallpaperModeSelectionViewModel @Inject constructor(
|
||||
wallpaperScheduler.cancelAllWallpaperChanges()
|
||||
|
||||
// Delete all albums (cascades to delete all wallpapers, folders, and queues)
|
||||
when (albumRepository.deleteAllAlbums()) {
|
||||
when (val result = albumRepository.deleteAllAlbums()) {
|
||||
is com.anthonyla.paperize.core.Result.Success -> { /* Success */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> { /* Handle error */ }
|
||||
is com.anthonyla.paperize.core.Result.Error -> {
|
||||
Log.e(TAG, "Error deleting albums during mode selection", result.exception)
|
||||
}
|
||||
is com.anthonyla.paperize.core.Result.Loading -> { /* Loading state not used */ }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package com.anthonyla.paperize.presentation.screens.wallpaper_view
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
@@ -10,7 +8,6 @@ import androidx.compose.foundation.layout.requiredSize
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material3.BottomAppBar
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -30,7 +27,6 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.net.toUri
|
||||
import coil3.compose.AsyncImage
|
||||
import coil3.compose.AsyncImagePainter
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.presentation.theme.AppSpacing
|
||||
import net.engawapg.lib.zoomable.rememberZoomState
|
||||
@@ -46,8 +42,6 @@ fun WallpaperViewScreen(
|
||||
) {
|
||||
val zoomState = rememberZoomState()
|
||||
|
||||
BackHandler { onBackClick() }
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
@@ -56,7 +50,7 @@ fun WallpaperViewScreen(
|
||||
containerColor = Color.Transparent
|
||||
),
|
||||
title = {
|
||||
if (zoomState.scale == 1f) {
|
||||
if (zoomState.scale <= 1.01f) {
|
||||
Text(
|
||||
text = wallpaperName,
|
||||
color = MaterialTheme.colorScheme.surfaceBright,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.anthonyla.paperize.service
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Shared mutex for wallpaper change operations.
|
||||
*
|
||||
* Both [WallpaperChangeService] and [WallpaperChangeWorker] can trigger wallpaper
|
||||
* changes simultaneously (e.g. a manual change fires the service while a scheduled
|
||||
* WorkManager job fires the worker). This singleton ensures only one change runs
|
||||
* at a time across both entry points.
|
||||
*/
|
||||
@Singleton
|
||||
class WallpaperChangeLock @Inject constructor() {
|
||||
val mutex = Mutex()
|
||||
}
|
||||
@@ -58,8 +58,11 @@ class BootReceiver : BroadcastReceiver() {
|
||||
ScreenType.LIVE,
|
||||
settings.liveIntervalMinutes
|
||||
)
|
||||
wallpaperScheduler.scheduleAlbumRefresh()
|
||||
Log.d(TAG, "Live wallpaper changes scheduled on boot")
|
||||
} else {
|
||||
wallpaperScheduler.cancelWallpaperChange(ScreenType.LIVE)
|
||||
wallpaperScheduler.cancelAlbumRefresh()
|
||||
Log.d(TAG, "Live mode but no album or interval, not scheduling")
|
||||
}
|
||||
} else {
|
||||
@@ -105,10 +108,12 @@ class BootReceiver : BroadcastReceiver() {
|
||||
|
||||
Log.d(TAG, "Wallpaper changes rescheduled successfully")
|
||||
} else {
|
||||
wallpaperScheduler.cancelAllWallpaperChanges()
|
||||
Log.d(TAG, "Wallpaper changer enabled but required albums not selected, not scheduling")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
wallpaperScheduler.cancelAllWallpaperChanges()
|
||||
Log.d(TAG, "Wallpaper changer disabled, not scheduling")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import androidx.savedstate.SavedStateRegistry
|
||||
import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.service.livewallpaper.gl.GLWallpaperService
|
||||
@@ -102,6 +103,8 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
private lateinit var renderController: PaperizeRenderController
|
||||
private val engineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
private var currentAlbumId: String? = null
|
||||
@Volatile private var currentWallpaper: Wallpaper? = null
|
||||
private var observedScalingType: ScalingType? = null
|
||||
private var hasShownParallaxWarning = false
|
||||
|
||||
private val gestureDetector = GestureDetector(
|
||||
@@ -202,8 +205,9 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
if (uri.isValid(contentResolver)) {
|
||||
wallpaper = candidate
|
||||
} else {
|
||||
// Remove invalid wallpaper
|
||||
wallpaperRepository.deleteWallpaper(candidate.id)
|
||||
// Skip this cycle — do not permanently delete.
|
||||
// A transient permission or storage issue should not remove it from the album.
|
||||
// AlbumRefreshWorker handles pruning of truly invalid URIs on its daily scan.
|
||||
maxRetries--
|
||||
}
|
||||
}
|
||||
@@ -213,6 +217,8 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
return@withContext EmptyImageLoader
|
||||
}
|
||||
|
||||
currentWallpaper = wallpaper
|
||||
|
||||
// Peek at queue to see if it needs refilling (not dequeuing, just checking)
|
||||
val nextInQueue = wallpaperRepository.getNextWallpaperInQueue(albumId, ScreenType.LIVE)
|
||||
if (nextInQueue == null) {
|
||||
@@ -221,7 +227,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
|
||||
try {
|
||||
val uri = wallpaper.uri.toUri()
|
||||
ContentUriImageLoader(contentResolver, uri)
|
||||
ContentUriImageLoader(contentResolver, uri, settings.liveScalingType)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error creating image loader", e)
|
||||
EmptyImageLoader
|
||||
@@ -284,9 +290,31 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
val effects = settings.liveEffects
|
||||
val scalingType = settings.liveScalingType
|
||||
|
||||
val albumChanged = albumId != currentAlbumId
|
||||
if (albumChanged) {
|
||||
currentWallpaper = null
|
||||
}
|
||||
|
||||
renderer.updateEffects(effects)
|
||||
renderer.updateScalingType(scalingType)
|
||||
renderer.updateAdaptiveBrightness(settings.adaptiveBrightness)
|
||||
|
||||
val scalingChanged =
|
||||
observedScalingType != null && observedScalingType != scalingType
|
||||
observedScalingType = scalingType
|
||||
|
||||
if (scalingChanged && !albumChanged) {
|
||||
currentWallpaper?.let { wallpaper ->
|
||||
Log.d(TAG, "Live scaling changed; reloading current wallpaper without advancing")
|
||||
renderer.queueWallpaper(
|
||||
ContentUriImageLoader(
|
||||
contentResolver,
|
||||
wallpaper.uri.toUri(),
|
||||
scalingType
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Show Toast warning if parallax is enabled but device has offset issues
|
||||
if (effects.enableParallax && !hasShownParallaxWarning && GLCompatibility.shouldWarnAboutParallax()) {
|
||||
@@ -301,7 +329,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
}
|
||||
|
||||
// Reload if album changed
|
||||
if (albumId != currentAlbumId) {
|
||||
if (albumChanged) {
|
||||
Log.d(TAG, "Album changed from $currentAlbumId to $albumId, reloading")
|
||||
currentAlbumId = albumId
|
||||
renderController.reloadCurrentArtwork()
|
||||
@@ -317,6 +345,11 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
|
||||
override fun onVisibilityChanged(visible: Boolean) {
|
||||
renderController.visible = visible
|
||||
if (visible) {
|
||||
// Re-evaluate draw-time effects such as adaptive brightness after
|
||||
// configuration changes while the wallpaper was hidden.
|
||||
requestRender()
|
||||
}
|
||||
super.onVisibilityChanged(visible)
|
||||
}
|
||||
|
||||
@@ -386,7 +419,7 @@ class PaperizeLiveWallpaperService : GLWallpaperService(), LifecycleOwner {
|
||||
private fun handleScreenOff() {
|
||||
engineScope.launch {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
if (settings.liveEffects.enableChangeOnScreenOn) {
|
||||
if (settings.liveEffects.enableChangeOnScreenOff) {
|
||||
Log.d(TAG, "Screen off - changing wallpaper")
|
||||
// Use forceReload to bypass visibility check and load while screen is off
|
||||
renderController.forceReloadCurrentArtwork()
|
||||
|
||||
@@ -20,7 +20,12 @@ import kotlin.math.min
|
||||
*/
|
||||
class GLPicture(
|
||||
bitmap: Bitmap,
|
||||
val brightnessFactor: Float = 1.0f
|
||||
/**
|
||||
* Luminance of the unmodified source bitmap. The renderer derives the adaptive
|
||||
* brightness multiplier at draw time so toggling the setting affects the image
|
||||
* that is already on screen.
|
||||
*/
|
||||
val sourceBrightness: Float
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@@ -63,54 +68,64 @@ class GLPicture(
|
||||
|
||||
Log.d(TAG, "Creating GLPicture: ${width}x${height}, tiling to ${cols}x${rows} (tile size: $tileSize)")
|
||||
|
||||
tiles = Array(cols * rows) { index ->
|
||||
val col = index % cols
|
||||
val row = index / cols
|
||||
val partialTiles = ArrayList<Tile>(cols * rows)
|
||||
try {
|
||||
for (index in 0 until cols * rows) {
|
||||
val col = index % cols
|
||||
val row = index / cols
|
||||
|
||||
val tileX = col * tileSize
|
||||
val tileY = row * tileSize
|
||||
val tileWidth = min(tileSize, width - tileX)
|
||||
val tileHeight = min(tileSize, height - tileY)
|
||||
val tileX = col * tileSize
|
||||
val tileY = row * tileSize
|
||||
val tileWidth = min(tileSize, width - tileX)
|
||||
val tileHeight = min(tileSize, height - tileY)
|
||||
|
||||
// Calculate geometry once at creation time (not per-frame)
|
||||
val left = -1f + (tileX.toFloat() / width) * 2f
|
||||
val right = -1f + ((tileX + tileWidth).toFloat() / width) * 2f
|
||||
val bottom = 1f - ((tileY + tileHeight).toFloat() / height) * 2f
|
||||
val top = 1f - (tileY.toFloat() / height) * 2f
|
||||
// Calculate geometry once at creation time (not per-frame)
|
||||
val left = -1f + (tileX.toFloat() / width) * 2f
|
||||
val right = -1f + ((tileX + tileWidth).toFloat() / width) * 2f
|
||||
val bottom = 1f - ((tileY + tileHeight).toFloat() / height) * 2f
|
||||
val top = 1f - (tileY.toFloat() / height) * 2f
|
||||
|
||||
val vertices = floatArrayOf(
|
||||
left, bottom, // Bottom-left
|
||||
right, bottom, // Bottom-right
|
||||
left, top, // Top-left
|
||||
right, top // Top-right
|
||||
)
|
||||
val vertices = floatArrayOf(
|
||||
left, bottom, // Bottom-left
|
||||
right, bottom, // Bottom-right
|
||||
left, top, // Top-left
|
||||
right, top // Top-right
|
||||
)
|
||||
|
||||
val texCoords = floatArrayOf(
|
||||
0f, 1f, // Bottom-left
|
||||
1f, 1f, // Bottom-right
|
||||
0f, 0f, // Top-left
|
||||
1f, 0f // Top-right
|
||||
)
|
||||
val texCoords = floatArrayOf(
|
||||
0f, 1f, // Bottom-left
|
||||
1f, 1f, // Bottom-right
|
||||
0f, 0f, // Top-left
|
||||
1f, 0f // Top-right
|
||||
)
|
||||
|
||||
// Pre-allocate buffers (reused every frame)
|
||||
val vertexBuffer = createFloatBuffer(vertices)
|
||||
val texCoordBuffer = createFloatBuffer(texCoords)
|
||||
// Pre-allocate buffers (reused every frame)
|
||||
val vertexBuffer = createFloatBuffer(vertices)
|
||||
val texCoordBuffer = createFloatBuffer(texCoords)
|
||||
|
||||
// Extract and upload tile bitmap
|
||||
val tileBitmap = Bitmap.createBitmap(bitmap, tileX, tileY, tileWidth, tileHeight)
|
||||
val textureId = loadTexture(tileBitmap)
|
||||
tileBitmap.recycle()
|
||||
// Extract and upload tile bitmap
|
||||
val tileBitmap = Bitmap.createBitmap(bitmap, tileX, tileY, tileWidth, tileHeight)
|
||||
val textureId = loadTexture(tileBitmap)
|
||||
tileBitmap.recycle()
|
||||
|
||||
Tile(
|
||||
textureId = textureId,
|
||||
x = tileX,
|
||||
y = tileY,
|
||||
width = tileWidth,
|
||||
height = tileHeight,
|
||||
vertexBuffer = vertexBuffer,
|
||||
texCoordBuffer = texCoordBuffer
|
||||
)
|
||||
partialTiles.add(Tile(
|
||||
textureId = textureId,
|
||||
x = tileX,
|
||||
y = tileY,
|
||||
width = tileWidth,
|
||||
height = tileHeight,
|
||||
vertexBuffer = vertexBuffer,
|
||||
texCoordBuffer = texCoordBuffer
|
||||
))
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
// Recycle any textures already uploaded to the GPU before re-throwing
|
||||
for (tile in partialTiles) {
|
||||
GLUtil.deleteTexture(tile.textureId)
|
||||
}
|
||||
throw e
|
||||
}
|
||||
tiles = partialTiles.toTypedArray()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -139,7 +154,8 @@ class GLPicture(
|
||||
|
||||
// Draw each tile using pre-allocated buffers (no per-frame allocation)
|
||||
for (tile in tiles) {
|
||||
// Bind texture
|
||||
// Bind texture to unit 0 (must set active unit explicitly to avoid relying on GL state)
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, tile.textureId)
|
||||
|
||||
// Use pre-allocated buffers - no allocation here!
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.opengl.GLSurfaceView
|
||||
import android.service.wallpaper.WallpaperService
|
||||
import android.util.Log
|
||||
import android.view.SurfaceHolder
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import javax.microedition.khronos.egl.EGL10
|
||||
import javax.microedition.khronos.egl.EGLConfig
|
||||
import javax.microedition.khronos.egl.EGLContext
|
||||
@@ -149,8 +150,14 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
|
||||
@Volatile var renderMode = RENDERMODE_WHEN_DIRTY
|
||||
|
||||
private val eventQueue = mutableListOf<Runnable>()
|
||||
@Suppress("UseKotlinAny")
|
||||
// LinkedBlockingQueue is thread-safe — no explicit synchronization needed.
|
||||
// Using a single lock for render signalling eliminates the previous AB-BA deadlock
|
||||
// where the GL thread held `lock` while acquiring `eventQueue`, and callers held
|
||||
// `eventQueue` while trying to acquire `lock` in requestRender().
|
||||
private val eventQueue = LinkedBlockingQueue<Runnable>()
|
||||
// java.lang.Object is intentional: this monitor uses wait()/notifyAll(), which
|
||||
// Kotlin's Any does not expose directly.
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
|
||||
private val lock = Object()
|
||||
|
||||
@Volatile private var shouldExit = false
|
||||
@@ -175,9 +182,7 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
}
|
||||
|
||||
fun queueEvent(runnable: Runnable) {
|
||||
synchronized(eventQueue) {
|
||||
eventQueue.add(runnable)
|
||||
}
|
||||
eventQueue.add(runnable)
|
||||
requestRender()
|
||||
}
|
||||
|
||||
@@ -232,12 +237,11 @@ abstract class GLWallpaperService : WallpaperService() {
|
||||
return
|
||||
}
|
||||
|
||||
// Process events
|
||||
synchronized(eventQueue) {
|
||||
if (eventQueue.isNotEmpty()) {
|
||||
event = eventQueue.removeAt(0)
|
||||
break
|
||||
}
|
||||
// Process events — LinkedBlockingQueue.poll() is non-blocking and thread-safe
|
||||
val polled = eventQueue.poll()
|
||||
if (polled != null) {
|
||||
event = polled
|
||||
break
|
||||
}
|
||||
|
||||
// Check if we should render
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.renderer
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.FloatBuffer
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* Geometry utilities for OpenGL rendering including vertex positions,
|
||||
@@ -10,6 +13,85 @@ import java.nio.FloatBuffer
|
||||
*/
|
||||
object GLGeometry {
|
||||
|
||||
data class WallpaperTransform(
|
||||
val scaledWidth: Float,
|
||||
val scaledHeight: Float,
|
||||
val horizontalOffset: Float
|
||||
)
|
||||
|
||||
data class CrossfadeAlphas(
|
||||
val current: Float,
|
||||
val next: Float
|
||||
)
|
||||
|
||||
/**
|
||||
* Alpha values for source-over crossfading.
|
||||
*
|
||||
* The current layer must stay opaque while the next layer fades over it. Fading
|
||||
* both layers produces a visible brightness dip at the midpoint.
|
||||
*/
|
||||
fun calculateCrossfadeAlphas(
|
||||
progress: Float,
|
||||
hasNextPicture: Boolean
|
||||
): CrossfadeAlphas {
|
||||
val nextAlpha = if (hasNextPicture) progress.coerceIn(0f, 1f) else 0f
|
||||
return CrossfadeAlphas(current = 1f, next = nextAlpha)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate live-wallpaper scale and launcher-scroll offset without OpenGL dependencies.
|
||||
*/
|
||||
fun calculateWallpaperTransform(
|
||||
viewWidth: Float,
|
||||
viewHeight: Float,
|
||||
imageWidth: Float,
|
||||
imageHeight: Float,
|
||||
scalingType: ScalingType,
|
||||
parallaxEnabled: Boolean,
|
||||
parallaxIntensity: Int,
|
||||
normalizedOffsetX: Float
|
||||
): WallpaperTransform {
|
||||
require(viewWidth > 0f && viewHeight > 0f)
|
||||
require(imageWidth > 0f && imageHeight > 0f)
|
||||
|
||||
val scaleX = viewWidth / imageWidth
|
||||
val scaleY = viewHeight / imageHeight
|
||||
val (baseScaleX, baseScaleY) = when (scalingType) {
|
||||
ScalingType.FILL -> max(scaleX, scaleY).let { it to it }
|
||||
ScalingType.FIT -> min(scaleX, scaleY).let { it to it }
|
||||
ScalingType.STRETCH -> scaleX to scaleY
|
||||
ScalingType.NONE -> 1f to 1f
|
||||
}
|
||||
|
||||
var effectiveScaleX = baseScaleX
|
||||
var effectiveScaleY = baseScaleY
|
||||
val intensity = if (parallaxEnabled) {
|
||||
parallaxIntensity.coerceIn(0, 100) / 100f
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
|
||||
if (intensity > 0f) {
|
||||
val currentWidth = imageWidth * effectiveScaleX
|
||||
val minimumExtraWidth = viewWidth * intensity * 0.2f
|
||||
if (currentWidth - viewWidth < minimumExtraWidth) {
|
||||
val zoom = (viewWidth + minimumExtraWidth) / currentWidth
|
||||
effectiveScaleX *= zoom
|
||||
effectiveScaleY *= zoom
|
||||
}
|
||||
}
|
||||
|
||||
val scaledWidth = imageWidth * effectiveScaleX
|
||||
val scaledHeight = imageHeight * effectiveScaleY
|
||||
val extraWidth = max(0f, scaledWidth - viewWidth)
|
||||
val offset = normalizedOffsetX.coerceIn(0f, 1f)
|
||||
return WallpaperTransform(
|
||||
scaledWidth = scaledWidth,
|
||||
scaledHeight = scaledHeight,
|
||||
horizontalOffset = extraWidth * intensity * (0.5f - offset)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-screen quad vertices in normalized device coordinates (-1 to 1).
|
||||
* Layout: x, y for each vertex (2 floats per vertex, 4 vertices).
|
||||
|
||||
@@ -15,10 +15,15 @@ object GLShaders {
|
||||
attribute vec4 a_position;
|
||||
attribute vec2 a_texCoord;
|
||||
varying vec2 v_texCoord;
|
||||
varying vec2 v_imageCoord;
|
||||
|
||||
void main() {
|
||||
gl_Position = u_mvpMatrix * a_position;
|
||||
v_texCoord = a_texCoord;
|
||||
// a_position spans the complete picture even when its texture is split
|
||||
// into tiles. Keep a global image coordinate so image-wide effects do
|
||||
// not restart at every tile boundary.
|
||||
v_imageCoord = vec2(a_position.x * 0.5 + 0.5, 0.5 - a_position.y * 0.5);
|
||||
}
|
||||
"""
|
||||
|
||||
@@ -40,8 +45,9 @@ object GLShaders {
|
||||
|
||||
/**
|
||||
* Fragment shader for horizontal Gaussian blur pass.
|
||||
* Uses 9-tap kernel with branchless design for optimal GPU performance.
|
||||
* Weights are pre-computed for sigma ~= 2.0.
|
||||
* Uses 17-tap kernel (half-integer steps) to eliminate banding/ghosting at high blur radii.
|
||||
* Weights are pre-computed for sigma ~= 1.815 sampled at {0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4} steps.
|
||||
* Branchless: when blurRadius is 0, all offsets are 0 so all samples collapse to center.
|
||||
*/
|
||||
const val BLUR_HORIZONTAL_FRAGMENT_SHADER = """
|
||||
precision mediump float;
|
||||
@@ -52,23 +58,28 @@ object GLShaders {
|
||||
|
||||
void main() {
|
||||
vec2 pixelSize = 1.0 / u_resolution;
|
||||
|
||||
// Sample center pixel
|
||||
vec4 center = texture2D(u_texture, v_texCoord);
|
||||
|
||||
// 9-tap Gaussian blur (branchless - when radius is 0, offsets are 0)
|
||||
vec4 color = center * 0.2210;
|
||||
|
||||
// Symmetric pairs for efficiency
|
||||
float r = u_blurRadius;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-4.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 4.0 * pixelSize.x * r, 0.0))) * 0.0204;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-3.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 3.0 * pixelSize.x * r, 0.0))) * 0.0577;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-2.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 2.0 * pixelSize.x * r, 0.0))) * 0.1215;
|
||||
|
||||
// 17-tap Gaussian (half-integer steps: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0)
|
||||
// Doubles sampling density vs 9-tap to eliminate aliasing at high blur radii
|
||||
vec4 color = texture2D(u_texture, v_texCoord) * 0.1120;
|
||||
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-0.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 0.5 * pixelSize.x * r, 0.0))) * 0.1078;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-1.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 1.0 * pixelSize.x * r, 0.0))) * 0.1899;
|
||||
texture2D(u_texture, v_texCoord + vec2( 1.0 * pixelSize.x * r, 0.0))) * 0.0962;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-1.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 1.5 * pixelSize.x * r, 0.0))) * 0.0796;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-2.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 2.0 * pixelSize.x * r, 0.0))) * 0.0610;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-2.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 2.5 * pixelSize.x * r, 0.0))) * 0.0434;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-3.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 3.0 * pixelSize.x * r, 0.0))) * 0.0286;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-3.5 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 3.5 * pixelSize.x * r, 0.0))) * 0.0175;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(-4.0 * pixelSize.x * r, 0.0)) +
|
||||
texture2D(u_texture, v_texCoord + vec2( 4.0 * pixelSize.x * r, 0.0))) * 0.0099;
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -76,7 +87,7 @@ object GLShaders {
|
||||
|
||||
/**
|
||||
* Fragment shader for vertical Gaussian blur pass.
|
||||
* Uses 9-tap kernel with branchless design matching horizontal pass.
|
||||
* Uses 17-tap kernel matching the horizontal pass.
|
||||
*/
|
||||
const val BLUR_VERTICAL_FRAGMENT_SHADER = """
|
||||
precision mediump float;
|
||||
@@ -87,23 +98,27 @@ object GLShaders {
|
||||
|
||||
void main() {
|
||||
vec2 pixelSize = 1.0 / u_resolution;
|
||||
|
||||
// Sample center pixel
|
||||
vec4 center = texture2D(u_texture, v_texCoord);
|
||||
|
||||
// 9-tap Gaussian blur (branchless - when radius is 0, offsets are 0)
|
||||
vec4 color = center * 0.2210;
|
||||
|
||||
// Symmetric pairs for efficiency
|
||||
float r = u_blurRadius;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -4.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 4.0 * pixelSize.y * r))) * 0.0204;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 3.0 * pixelSize.y * r))) * 0.0577;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 2.0 * pixelSize.y * r))) * 0.1215;
|
||||
|
||||
// 17-tap Gaussian (half-integer steps: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0)
|
||||
vec4 color = texture2D(u_texture, v_texCoord) * 0.1120;
|
||||
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -0.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 0.5 * pixelSize.y * r))) * 0.1078;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 1.0 * pixelSize.y * r))) * 0.1899;
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 1.0 * pixelSize.y * r))) * 0.0962;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -1.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 1.5 * pixelSize.y * r))) * 0.0796;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 2.0 * pixelSize.y * r))) * 0.0610;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -2.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 2.5 * pixelSize.y * r))) * 0.0434;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 3.0 * pixelSize.y * r))) * 0.0286;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -3.5 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 3.5 * pixelSize.y * r))) * 0.0175;
|
||||
color += (texture2D(u_texture, v_texCoord + vec2(0.0, -4.0 * pixelSize.y * r)) +
|
||||
texture2D(u_texture, v_texCoord + vec2(0.0, 4.0 * pixelSize.y * r))) * 0.0099;
|
||||
|
||||
gl_FragColor = color;
|
||||
}
|
||||
@@ -122,6 +137,7 @@ object GLShaders {
|
||||
uniform float u_grayscaleFactor;
|
||||
uniform float u_adaptiveBrightnessFactor;
|
||||
varying vec2 v_texCoord;
|
||||
varying vec2 v_imageCoord;
|
||||
|
||||
void main() {
|
||||
vec4 color = texture2D(u_texture, v_texCoord);
|
||||
@@ -129,15 +145,18 @@ object GLShaders {
|
||||
// 1. Apply darken (branchless - when factor is 0, multiplier is 1.0)
|
||||
color.rgb *= (1.0 - u_darkenFactor);
|
||||
|
||||
// 2. Apply vignette (branchless using mix)
|
||||
// When vignetteFactor is 0, the vignette calculation still runs but
|
||||
// the smoothstep result approaches 1.0 everywhere, so color is unchanged
|
||||
vec2 center = v_texCoord - 0.5;
|
||||
float dist = length(center);
|
||||
float vignette = 1.0 - smoothstep(0.3, 0.9, dist * (1.0 + u_vignetteFactor * 2.0));
|
||||
// Mix between original (1.0) and vignette based on factor
|
||||
float vignetteMultiplier = mix(1.0, vignette, u_vignetteFactor);
|
||||
color.rgb *= vignetteMultiplier;
|
||||
// 2. Apply vignette — matches CPU vignetteBitmap gradient stops:
|
||||
// [0% dark at center] → [10% dark at 70% of radius] → [80% dark at edge]
|
||||
// radius is normalized to 0.5 UV (image edge along shorter axis)
|
||||
vec2 vignetteCenter = v_imageCoord - 0.5;
|
||||
float dist = length(vignetteCenter);
|
||||
float t = clamp(dist / 0.5, 0.0, 1.0);
|
||||
// Inner segment: 0% → 10% over [0, 0.7]
|
||||
float innerDark = smoothstep(0.0, 0.7, t) * 0.1;
|
||||
// Outer segment: 10% → 80% over [0.7, 1.0]
|
||||
float outerDark = smoothstep(0.7, 1.0, t) * 0.7;
|
||||
float darkAmount = innerDark + outerDark;
|
||||
color.rgb *= (1.0 - darkAmount * u_vignetteFactor);
|
||||
|
||||
// 3. Apply grayscale (branchless - mix handles factor 0 correctly)
|
||||
// ITU-R BT.709 standard luminance calculation
|
||||
|
||||
@@ -5,9 +5,10 @@ import android.graphics.Bitmap
|
||||
import android.graphics.ImageDecoder
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import androidx.compose.ui.util.fastRoundToInt
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Sealed interface for loading images from different sources.
|
||||
@@ -41,10 +42,12 @@ object EmptyImageLoader : ImageLoader {
|
||||
*
|
||||
* @property contentResolver Content resolver for URI access
|
||||
* @property uri Content URI to load
|
||||
* @property scalingType How the image will be scaled for display
|
||||
*/
|
||||
class ContentUriImageLoader(
|
||||
private val contentResolver: ContentResolver,
|
||||
private val uri: Uri
|
||||
private val uri: Uri,
|
||||
private val scalingType: ScalingType = ScalingType.FILL
|
||||
) : ImageLoader {
|
||||
|
||||
companion object {
|
||||
@@ -54,38 +57,47 @@ class ContentUriImageLoader(
|
||||
override suspend fun load(targetWidth: Int, targetHeight: Int): Bitmap? {
|
||||
return withContext(Dispatchers.IO) {
|
||||
try {
|
||||
// First verify the URI is accessible
|
||||
val isAccessible = try {
|
||||
contentResolver.openInputStream(uri)?.use { true } ?: false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "URI not accessible: $uri", e)
|
||||
false
|
||||
}
|
||||
|
||||
if (!isAccessible) {
|
||||
Log.w(TAG, "Image not accessible or doesn't exist: $uri")
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
// Get image dimensions without loading pixel data
|
||||
val dimensions = getImageDimensions() ?: return@withContext null
|
||||
|
||||
// Calculate optimal sample size
|
||||
val sampleSize = calculateSampleSize(
|
||||
dimensions.first,
|
||||
dimensions.second,
|
||||
targetWidth,
|
||||
targetHeight
|
||||
)
|
||||
|
||||
Log.d(TAG, "Loading image: ${dimensions.first}x${dimensions.second} -> " +
|
||||
"${dimensions.first / sampleSize}x${dimensions.second / sampleSize} " +
|
||||
"(sample size: $sampleSize)")
|
||||
|
||||
// Load bitmap with sampling
|
||||
// ImageDecoder auto-applies EXIF orientation; info.size returns post-EXIF (display)
|
||||
// dimensions. Computing decodeWidth/decodeHeight inside the lambda from info.size
|
||||
// ensures correct aspect-ratio math regardless of EXIF rotation metadata.
|
||||
val source = ImageDecoder.createSource(contentResolver, uri)
|
||||
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->
|
||||
decoder.setTargetSampleSize(sampleSize)
|
||||
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
|
||||
val srcWidth = info.size.width
|
||||
val srcHeight = info.size.height
|
||||
|
||||
val (decodeWidth, decodeHeight) = when (scalingType) {
|
||||
ScalingType.FILL -> {
|
||||
val scale = maxOf(
|
||||
targetWidth.toFloat() / srcWidth,
|
||||
targetHeight.toFloat() / srcHeight
|
||||
)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
}
|
||||
ScalingType.FIT -> {
|
||||
val scale = minOf(
|
||||
targetWidth.toFloat() / srcWidth,
|
||||
targetHeight.toFloat() / srcHeight
|
||||
)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
}
|
||||
ScalingType.STRETCH -> Pair(targetWidth, targetHeight)
|
||||
ScalingType.NONE -> {
|
||||
// Cap at 2× screen size to prevent OOM on very large source images
|
||||
val maxW = targetWidth * 2
|
||||
val maxH = targetHeight * 2
|
||||
if (srcWidth > maxW || srcHeight > maxH) {
|
||||
val scale = minOf(maxW.toFloat() / srcWidth, maxH.toFloat() / srcHeight)
|
||||
Pair((srcWidth * scale).fastRoundToInt(), (srcHeight * scale).fastRoundToInt())
|
||||
} else {
|
||||
Pair(srcWidth, srcHeight)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "Loading image: ${srcWidth}x${srcHeight} -> ${decodeWidth}x${decodeHeight} " +
|
||||
"(scaling: $scalingType, target: ${targetWidth}x${targetHeight})")
|
||||
|
||||
decoder.setTargetSize(decodeWidth, decodeHeight)
|
||||
decoder.isMutableRequired = false // Immutable for GPU upload
|
||||
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
|
||||
}
|
||||
@@ -108,72 +120,4 @@ class ContentUriImageLoader(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get image dimensions without loading the full bitmap.
|
||||
* Uses BitmapFactory with inJustDecodeBounds to avoid allocating pixel data.
|
||||
*/
|
||||
private fun getImageDimensions(): Pair<Int, Int>? {
|
||||
return try {
|
||||
contentResolver.openInputStream(uri)?.use { inputStream ->
|
||||
val options = android.graphics.BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
android.graphics.BitmapFactory.decodeStream(inputStream, null, options)
|
||||
val width = options.outWidth
|
||||
val height = options.outHeight
|
||||
if (width > 0 && height > 0) Pair(width, height) else null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to get image dimensions for $uri", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the optimal sample size for downsampling.
|
||||
* Returns the largest power-of-2 sample size that still maintains
|
||||
* image dimensions larger than or equal to target dimensions.
|
||||
*
|
||||
* @param width Source image width
|
||||
* @param height Source image height
|
||||
* @param targetWidth Target width
|
||||
* @param targetHeight Target height
|
||||
* @return Sample size (power of 2)
|
||||
*/
|
||||
private fun calculateSampleSize(
|
||||
width: Int,
|
||||
height: Int,
|
||||
targetWidth: Int,
|
||||
targetHeight: Int
|
||||
): Int {
|
||||
// Guard against invalid target dimensions
|
||||
if (targetWidth <= 0 || targetHeight <= 0) {
|
||||
Log.w(TAG, "Invalid target dimensions: ${targetWidth}x${targetHeight}, using original size")
|
||||
return 1
|
||||
}
|
||||
|
||||
// Guard against invalid source dimensions
|
||||
if (width <= 0 || height <= 0) {
|
||||
Log.w(TAG, "Invalid source dimensions: ${width}x${height}")
|
||||
return 1
|
||||
}
|
||||
|
||||
var sampleSize = 1
|
||||
|
||||
if (width > targetWidth || height > targetHeight) {
|
||||
val halfWidth = width / 2
|
||||
val halfHeight = height / 2
|
||||
|
||||
// Calculate the largest sample size that is a power of 2 and keeps both
|
||||
// dimensions larger than the target dimensions
|
||||
while ((halfWidth / sampleSize) >= targetWidth &&
|
||||
(halfHeight / sampleSize) >= targetHeight) {
|
||||
sampleSize *= 2
|
||||
}
|
||||
}
|
||||
|
||||
// Return the calculated sample size (it is already the largest power-of-2
|
||||
// that keeps dimensions larger than or equal to target)
|
||||
return max(1, sampleSize)
|
||||
}
|
||||
}
|
||||
@@ -120,6 +120,10 @@ class PaperizeWallpaperRenderer(
|
||||
// Adaptive brightness (from ScheduleSettings)
|
||||
@Volatile private var adaptiveBrightnessEnabled = false
|
||||
|
||||
// Retain the current source so a fold/unfold or other surface-size change can
|
||||
// decode the same wallpaper again at the new native resolution.
|
||||
@Volatile private var currentImageLoader: ImageLoader? = null
|
||||
|
||||
// Matrices
|
||||
private val mvpMatrix = FloatArray(16)
|
||||
private val projectionMatrix = FloatArray(16)
|
||||
@@ -156,6 +160,10 @@ class PaperizeWallpaperRenderer(
|
||||
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
|
||||
Log.d(TAG, "onSurfaceChanged: ${width}x${height}")
|
||||
|
||||
val sizeChanged =
|
||||
surfaceWidth > 0 &&
|
||||
surfaceHeight > 0 &&
|
||||
(surfaceWidth != width || surfaceHeight != height)
|
||||
surfaceWidth = width
|
||||
surfaceHeight = height
|
||||
|
||||
@@ -163,6 +171,13 @@ class PaperizeWallpaperRenderer(
|
||||
|
||||
// Recreate framebuffers for blur at new resolution
|
||||
createBlurFramebuffers(width, height)
|
||||
|
||||
if (sizeChanged) {
|
||||
currentImageLoader?.let { loader ->
|
||||
Log.d(TAG, "Surface size changed; reloading current wallpaper at ${width}x${height}")
|
||||
queueWallpaper(loader, skipCrossfade = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDrawFrame(gl: GL10) {
|
||||
@@ -190,9 +205,13 @@ class PaperizeWallpaperRenderer(
|
||||
}
|
||||
|
||||
// Draw current picture
|
||||
val crossfadeAlphas = GLGeometry.calculateCrossfadeAlphas(
|
||||
progress = crossfadeProgress,
|
||||
hasNextPicture = next != null
|
||||
)
|
||||
|
||||
current?.let { picture ->
|
||||
val alpha = if (next != null) 1.0f - crossfadeProgress else 1.0f
|
||||
drawPictureWithEffects(picture, alpha, blurRadius)
|
||||
drawPictureWithEffects(picture, crossfadeAlphas.current, blurRadius)
|
||||
}
|
||||
|
||||
// Draw next picture (if crossfading)
|
||||
@@ -203,7 +222,7 @@ class PaperizeWallpaperRenderer(
|
||||
}
|
||||
|
||||
// Draw next picture with its own alpha
|
||||
drawPictureWithEffects(picture, crossfadeProgress, blurRadius)
|
||||
drawPictureWithEffects(picture, crossfadeAlphas.next, blurRadius)
|
||||
|
||||
// Update crossfade progress using time-based calculation
|
||||
// This ensures consistent animation duration regardless of refresh rate (60Hz, 90Hz, 120Hz, etc.)
|
||||
@@ -297,7 +316,7 @@ class PaperizeWallpaperRenderer(
|
||||
uGrayscaleFactorHandle,
|
||||
if (currentEffects.enableGrayscale) currentEffects.grayscalePercentage / Constants.PERCENTAGE_DIVISOR else 0f
|
||||
)
|
||||
GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, picture.brightnessFactor)
|
||||
GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, adaptiveBrightnessFactor(picture))
|
||||
|
||||
// Bind the fully blurred texture as input
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
|
||||
@@ -328,7 +347,7 @@ class PaperizeWallpaperRenderer(
|
||||
uGrayscaleFactorHandle,
|
||||
if (currentEffects.enableGrayscale) currentEffects.grayscalePercentage / Constants.PERCENTAGE_DIVISOR else 0f
|
||||
)
|
||||
GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, picture.brightnessFactor)
|
||||
GLES20.glUniform1f(uAdaptiveBrightnessFactorHandle, adaptiveBrightnessFactor(picture))
|
||||
|
||||
picture.draw(effectsProgram, aPositionHandle, aTexCoordHandle, mvpMatrix, uMvpMatrixHandle)
|
||||
}
|
||||
@@ -347,67 +366,16 @@ class PaperizeWallpaperRenderer(
|
||||
return
|
||||
}
|
||||
|
||||
// 1. Calculate scale based on ScalingType
|
||||
val scaleX = viewWidth / imageWidth
|
||||
val scaleY = viewHeight / imageHeight
|
||||
|
||||
val (finalScaleX, finalScaleY) = when (currentScalingType) {
|
||||
ScalingType.FILL -> {
|
||||
val scale = kotlin.math.max(scaleX, scaleY)
|
||||
Pair(scale, scale)
|
||||
}
|
||||
ScalingType.FIT -> {
|
||||
val scale = kotlin.math.min(scaleX, scaleY)
|
||||
Pair(scale, scale)
|
||||
}
|
||||
ScalingType.STRETCH -> {
|
||||
Pair(scaleX, scaleY)
|
||||
}
|
||||
ScalingType.NONE -> {
|
||||
Pair(1f, 1f)
|
||||
}
|
||||
}
|
||||
|
||||
var effectiveScaleX = finalScaleX
|
||||
var effectiveScaleY = finalScaleY
|
||||
|
||||
val parallaxEnabled = currentEffects.enableParallax && currentEffects.parallaxIntensity > 0
|
||||
val parallaxIntensity = if (parallaxEnabled) currentEffects.parallaxIntensity / 100f else 0f
|
||||
|
||||
// If parallax is enabled, ensure we have enough width to scroll (overscan).
|
||||
// If image fits perfectly, apply artificial zoom based on intensity.
|
||||
if (parallaxEnabled) {
|
||||
val currentWidth = imageWidth * effectiveScaleX
|
||||
// Target at least 20% overscan at max intensity
|
||||
val minExtraWidth = viewWidth * parallaxIntensity * 0.2f
|
||||
|
||||
if ((currentWidth - viewWidth) < minExtraWidth) {
|
||||
// Zoom in to create scrollable area
|
||||
val targetWidth = viewWidth + minExtraWidth
|
||||
// Prevent division by zero
|
||||
if (currentWidth > 0) {
|
||||
val zoomFactor = targetWidth / currentWidth
|
||||
effectiveScaleX *= zoomFactor
|
||||
effectiveScaleY *= zoomFactor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val scaledWidth = imageWidth * effectiveScaleX
|
||||
val scaledHeight = imageHeight * effectiveScaleY
|
||||
|
||||
// 2. Calculate parallax offset
|
||||
// Available scroll range is the difference between scaled image width and screen width
|
||||
val extraWidth = kotlin.math.max(0f, scaledWidth - viewWidth)
|
||||
|
||||
// Calculate offset based on scroll position (0.0 = left, 1.0 = right)
|
||||
// Center (0.5) is 0 offset
|
||||
// Reverting to: `maxParallaxOffset = extraWidth`.
|
||||
// And relying on the "Zoom" logic to create that width if needed.
|
||||
val maxParallaxOffset = extraWidth
|
||||
val parallaxOffset = maxParallaxOffset * (0.5f - normalOffsetX)
|
||||
|
||||
// Verbose logging removed to avoid per-frame log spam
|
||||
val transform = GLGeometry.calculateWallpaperTransform(
|
||||
viewWidth = viewWidth,
|
||||
viewHeight = viewHeight,
|
||||
imageWidth = imageWidth,
|
||||
imageHeight = imageHeight,
|
||||
scalingType = currentScalingType,
|
||||
parallaxEnabled = currentEffects.enableParallax,
|
||||
parallaxIntensity = currentEffects.parallaxIntensity,
|
||||
normalizedOffsetX = normalOffsetX
|
||||
)
|
||||
|
||||
// 3. Construct Matrix
|
||||
// We use an orthographic projection matching the screen dimensions
|
||||
@@ -423,12 +391,18 @@ class PaperizeWallpaperRenderer(
|
||||
|
||||
// Apply Model transformations
|
||||
// Translate for parallax
|
||||
Matrix.translateM(matrix, 0, parallaxOffset, 0f, 0f)
|
||||
Matrix.translateM(matrix, 0, transform.horizontalOffset, 0f, 0f)
|
||||
|
||||
// Scale to match image size * crop scale
|
||||
// The quad is -1 to 1 (size 2), so we need to scale it to match image dimensions
|
||||
// Actually, we want to map the quad (-1..1) to the image size (-w/2..w/2)
|
||||
Matrix.scaleM(matrix, 0, scaledWidth / 2f, scaledHeight / 2f, 1f)
|
||||
Matrix.scaleM(
|
||||
matrix,
|
||||
0,
|
||||
transform.scaledWidth / 2f,
|
||||
transform.scaledHeight / 2f,
|
||||
1f
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -603,17 +577,15 @@ class PaperizeWallpaperRenderer(
|
||||
return@launch
|
||||
}
|
||||
|
||||
// Calculate adaptive brightness if enabled
|
||||
val brightnessFactor = if (adaptiveBrightnessEnabled) {
|
||||
val brightness = com.anthonyla.paperize.core.util.calculateBitmapBrightness(bitmap)
|
||||
com.anthonyla.paperize.core.util.getAdaptiveBrightnessMultiplier(context, brightness)
|
||||
} else {
|
||||
1.0f
|
||||
}
|
||||
// Always retain source luminance. Whether adaptive brightness is enabled
|
||||
// is evaluated at draw time so settings changes are immediate and do not
|
||||
// advance the wallpaper queue.
|
||||
val sourceBrightness =
|
||||
com.anthonyla.paperize.core.util.calculateBitmapBrightness(bitmap)
|
||||
|
||||
// Upload to GPU on GL thread
|
||||
callbacks.queueEventOnGlThread {
|
||||
uploadBitmap(bitmap, brightnessFactor, skipCrossfade)
|
||||
uploadBitmap(bitmap, sourceBrightness, imageLoader, skipCrossfade)
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "Failed to load wallpaper (null bitmap)")
|
||||
@@ -634,7 +606,7 @@ class PaperizeWallpaperRenderer(
|
||||
* @return Pair of (width, height)
|
||||
*/
|
||||
private suspend fun waitForSurfaceDimensions(): Pair<Int, Int> {
|
||||
val maxWaitMs = Constants.FLOW_SUBSCRIPTION_TIMEOUT_MS
|
||||
val maxWaitMs = Constants.SURFACE_WAIT_TIMEOUT_MS
|
||||
val pollIntervalMs = Constants.SURFACE_POLL_INTERVAL_MS
|
||||
var waitedMs = 0L
|
||||
|
||||
@@ -659,10 +631,16 @@ class PaperizeWallpaperRenderer(
|
||||
* Must be called on GL thread.
|
||||
*
|
||||
* @param bitmap The bitmap to upload
|
||||
* @param brightnessFactor The adaptive brightness multiplier for this bitmap
|
||||
* @param sourceBrightness Luminance of the unmodified source bitmap
|
||||
* @param imageLoader Source used to reproduce this bitmap after a surface resize
|
||||
* @param skipCrossfade If true, instantly replace current wallpaper without animation
|
||||
*/
|
||||
private fun uploadBitmap(bitmap: Bitmap, brightnessFactor: Float, skipCrossfade: Boolean = false) {
|
||||
private fun uploadBitmap(
|
||||
bitmap: Bitmap,
|
||||
sourceBrightness: Float,
|
||||
imageLoader: ImageLoader,
|
||||
skipCrossfade: Boolean = false
|
||||
) {
|
||||
// Validate bitmap before processing
|
||||
if (bitmap.isRecycled) {
|
||||
Log.e(TAG, "Cannot upload recycled bitmap")
|
||||
@@ -675,7 +653,8 @@ class PaperizeWallpaperRenderer(
|
||||
}
|
||||
|
||||
try {
|
||||
val picture = GLPicture(bitmap, brightnessFactor)
|
||||
val picture = GLPicture(bitmap, sourceBrightness)
|
||||
currentImageLoader = imageLoader
|
||||
|
||||
// Recycle bitmap (no longer needed after GPU upload)
|
||||
bitmap.recycle()
|
||||
@@ -683,6 +662,7 @@ class PaperizeWallpaperRenderer(
|
||||
if (skipCrossfade) {
|
||||
// Instant swap - no animation (used for screen-off changes)
|
||||
currentPicture?.recycle()
|
||||
nextPicture?.recycle() // Recycle any in-flight crossfade target
|
||||
currentPicture = picture
|
||||
nextPicture = null
|
||||
crossfadeProgress = 0f
|
||||
@@ -690,6 +670,7 @@ class PaperizeWallpaperRenderer(
|
||||
Log.d(TAG, "Wallpaper instantly swapped (no crossfade): $picture")
|
||||
} else {
|
||||
// Start crossfade with time-based animation
|
||||
nextPicture?.recycle() // Recycle interrupted crossfade target if any
|
||||
nextPicture = picture
|
||||
crossfadeProgress = 0f
|
||||
crossfadeStartTimeNanos = System.nanoTime()
|
||||
@@ -732,8 +713,9 @@ class PaperizeWallpaperRenderer(
|
||||
* @param offset Normalized offset (0.0 = left, 1.0 = right)
|
||||
*/
|
||||
fun setNormalOffsetX(offset: Float) {
|
||||
if (normalOffsetX != offset) {
|
||||
normalOffsetX = offset
|
||||
val clampedOffset = offset.coerceIn(0f, 1f)
|
||||
if (normalOffsetX != clampedOffset) {
|
||||
normalOffsetX = clampedOffset
|
||||
callbacks.requestRender()
|
||||
}
|
||||
}
|
||||
@@ -743,10 +725,23 @@ class PaperizeWallpaperRenderer(
|
||||
* Can be called from any thread.
|
||||
*/
|
||||
fun updateAdaptiveBrightness(enabled: Boolean) {
|
||||
adaptiveBrightnessEnabled = enabled
|
||||
Log.d(TAG, "Adaptive brightness updated: $enabled")
|
||||
if (adaptiveBrightnessEnabled != enabled) {
|
||||
adaptiveBrightnessEnabled = enabled
|
||||
Log.d(TAG, "Adaptive brightness updated: $enabled")
|
||||
callbacks.requestRender()
|
||||
}
|
||||
}
|
||||
|
||||
private fun adaptiveBrightnessFactor(picture: GLPicture): Float =
|
||||
if (adaptiveBrightnessEnabled) {
|
||||
com.anthonyla.paperize.core.util.getAdaptiveBrightnessMultiplier(
|
||||
context,
|
||||
picture.sourceBrightness
|
||||
)
|
||||
} else {
|
||||
1f
|
||||
}
|
||||
|
||||
/**
|
||||
* Update scaling type.
|
||||
* Can be called from any thread.
|
||||
@@ -772,6 +767,7 @@ class PaperizeWallpaperRenderer(
|
||||
|
||||
nextPicture?.recycle()
|
||||
nextPicture = null
|
||||
currentImageLoader = null
|
||||
|
||||
GLUtil.deleteProgram(simpleProgram)
|
||||
GLUtil.deleteProgram(blurHorizontalProgram)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.anthonyla.paperize.service.shortcut
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import com.anthonyla.paperize.service.wallpaper.WallpaperChangeService
|
||||
|
||||
/**
|
||||
* Invisible launcher-shortcut entry point that changes the configured wallpaper target.
|
||||
*/
|
||||
class WallpaperShortcutActivity : Activity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
startForegroundService(
|
||||
Intent(this, WallpaperChangeService::class.java).apply {
|
||||
action = WallpaperChangeService.ACTION_CHANGE_WALLPAPER_AUTO
|
||||
}
|
||||
)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
@@ -12,65 +12,51 @@ import android.os.IBinder
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.Result as PaperizeResult
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.setBitmapChecked
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
|
||||
import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase
|
||||
import com.anthonyla.paperize.presentation.MainActivity
|
||||
import com.anthonyla.paperize.service.WallpaperChangeLock
|
||||
import dagger.hilt.android.AndroidEntryPoint
|
||||
import javax.inject.Inject
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Foreground service for changing wallpapers
|
||||
*
|
||||
* Actions:
|
||||
* - CHANGE_WALLPAPER: Change wallpaper immediately
|
||||
* Foreground service for immediate wallpaper changes and effect reapplication.
|
||||
*/
|
||||
@AndroidEntryPoint
|
||||
class WallpaperChangeService : Service() {
|
||||
|
||||
@Inject
|
||||
lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase
|
||||
|
||||
@Inject
|
||||
lateinit var settingsRepository: SettingsRepository
|
||||
@Inject lateinit var changeWallpaperUseCase: ChangeWallpaperUseCase
|
||||
@Inject lateinit var reapplyEffectsUseCase: ReapplyEffectsUseCase
|
||||
@Inject lateinit var settingsRepository: SettingsRepository
|
||||
@Inject lateinit var wallpaperChangeLock: WallpaperChangeLock
|
||||
|
||||
private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
|
||||
private lateinit var wallpaperManager: WallpaperManager
|
||||
private lateinit var notificationManager: NotificationManager
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WallpaperChangeService"
|
||||
const val ACTION_CHANGE_WALLPAPER = Constants.ACTION_CHANGE_WALLPAPER
|
||||
const val EXTRA_SCREEN_TYPE = Constants.EXTRA_SCREEN_TYPE
|
||||
private const val ERROR_NOTIFICATION_ID = Constants.NOTIFICATION_ID + 1
|
||||
|
||||
/**
|
||||
* Mutex to prevent concurrent wallpaper changes
|
||||
* Multiple service instances can be started simultaneously from different triggers
|
||||
* (alarms, manual changes, etc.). This mutex ensures only one wallpaper change
|
||||
* operation runs at a time, preventing race conditions.
|
||||
*/
|
||||
private val wallpaperChangeMutex = Mutex()
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
wallpaperManager = WallpaperManager.getInstance(this)
|
||||
notificationManager = getSystemService(NotificationManager::class.java)
|
||||
?: throw IllegalStateException("NotificationManager not available")
|
||||
?: error("NotificationManager not available")
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
// Start foreground service. Android 14+ requires specifying the service type.
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
startForeground(
|
||||
Constants.NOTIFICATION_ID,
|
||||
@@ -81,252 +67,363 @@ class WallpaperChangeService : Service() {
|
||||
startForeground(Constants.NOTIFICATION_ID, createNotification())
|
||||
}
|
||||
|
||||
val screenType = intent?.getStringExtra(EXTRA_SCREEN_TYPE)
|
||||
?.let(ScreenType::fromString)
|
||||
?: ScreenType.BOTH
|
||||
when (intent?.action) {
|
||||
ACTION_CHANGE_WALLPAPER -> {
|
||||
val screenType = intent.getStringExtra(EXTRA_SCREEN_TYPE)?.let {
|
||||
ScreenType.fromString(it)
|
||||
} ?: ScreenType.BOTH
|
||||
handleChangeWallpaper(screenType, startId)
|
||||
ACTION_CHANGE_WALLPAPER -> handleChangeWallpaper(screenType, startId)
|
||||
ACTION_CHANGE_WALLPAPER_AUTO ->
|
||||
handleChangeWallpaper(screenType, startId, respectWallpaperMode = true)
|
||||
ACTION_REAPPLY_EFFECTS -> handleReapplyEffects(screenType, startId)
|
||||
else -> {
|
||||
Log.w(TAG, "Unknown action: ${intent?.action}")
|
||||
stopSelf(startId)
|
||||
}
|
||||
}
|
||||
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun handleChangeWallpaper(screenType: ScreenType, startId: Int) {
|
||||
private fun handleChangeWallpaper(
|
||||
screenType: ScreenType,
|
||||
startId: Int,
|
||||
respectWallpaperMode: Boolean = false
|
||||
) {
|
||||
serviceScope.launch {
|
||||
// Use mutex to prevent concurrent wallpaper changes
|
||||
wallpaperChangeMutex.withLock {
|
||||
wallpaperChangeLock.mutex.withLock {
|
||||
try {
|
||||
// Get schedule settings to determine which albums to use
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
|
||||
when (screenType) {
|
||||
ScreenType.LIVE -> {
|
||||
// Live wallpaper changes are handled by the live wallpaper service
|
||||
Log.d(TAG, "Live wallpaper - no action needed in service")
|
||||
}
|
||||
ScreenType.HOME -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId)
|
||||
val effectiveScreenType =
|
||||
if (
|
||||
respectWallpaperMode &&
|
||||
settingsRepository.getWallpaperMode() == WallpaperMode.LIVE
|
||||
) {
|
||||
ScreenType.LIVE
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected")
|
||||
screenType
|
||||
}
|
||||
}
|
||||
ScreenType.LOCK -> {
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
}
|
||||
ScreenType.BOTH -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
|
||||
// If same album and not separately scheduled, use same wallpaper
|
||||
if (homeAlbumId != null && lockAlbumId != null &&
|
||||
homeAlbumId == lockAlbumId && !settings.separateSchedules) {
|
||||
// Get one wallpaper and set for both screens
|
||||
val result = changeWallpaperUseCase(homeAlbumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
// Set for home screen
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
// Set for lock screen
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
|
||||
// Recycle bitmap after setting to free memory
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Same wallpaper set for both screens")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting wallpaper for both screens", e)
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error.message?.contains("No wallpapers available in album") == true) {
|
||||
handleEmptyAlbumError()
|
||||
} else {
|
||||
Log.e(TAG, "Error getting wallpaper bitmap", error)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Different albums or separately scheduled - change independently
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected")
|
||||
}
|
||||
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stopSelf(startId)
|
||||
changeWallpaper(
|
||||
effectiveScreenType,
|
||||
settingsRepository.getScheduleSettings()
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error changing wallpaper", e)
|
||||
showErrorNotification(
|
||||
getString(R.string.app_name),
|
||||
e.localizedMessage
|
||||
?: getString(R.string.error_no_valid_wallpaper_after_retries)
|
||||
)
|
||||
} finally {
|
||||
stopSelf(startId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeHomeWallpaper(albumId: String) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
private suspend fun changeWallpaper(
|
||||
screenType: ScreenType,
|
||||
settings: ScheduleSettings
|
||||
) {
|
||||
when (screenType) {
|
||||
ScreenType.LIVE -> {
|
||||
sendBroadcast(
|
||||
Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(packageName)
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting home wallpaper", e)
|
||||
} finally {
|
||||
// Always recycle bitmap to prevent memory leaks
|
||||
bitmap.recycle()
|
||||
Log.d(TAG, "Requested immediate live wallpaper reload")
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error.message?.contains("No wallpapers available in album") == true) {
|
||||
handleEmptyAlbumError()
|
||||
} else {
|
||||
Log.e(TAG, "Error getting home wallpaper bitmap", error)
|
||||
|
||||
ScreenType.HOME -> settings.homeAlbumId?.let {
|
||||
changeSingle(it, ScreenType.HOME)
|
||||
} ?: Log.w(TAG, "No home album selected")
|
||||
|
||||
ScreenType.LOCK -> settings.lockAlbumId?.let {
|
||||
changeSingle(it, ScreenType.LOCK)
|
||||
} ?: Log.w(TAG, "No lock album selected")
|
||||
|
||||
ScreenType.BOTH -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (
|
||||
homeAlbumId != null &&
|
||||
homeAlbumId == lockAlbumId &&
|
||||
!settings.separateSchedules
|
||||
) {
|
||||
changeSynchronized(homeAlbumId, settings)
|
||||
} else {
|
||||
homeAlbumId?.let { changeSingle(it, ScreenType.HOME) }
|
||||
?: Log.w(TAG, "No home album selected")
|
||||
lockAlbumId?.let { changeSingle(it, ScreenType.LOCK) }
|
||||
?: Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeLockWallpaper(albumId: String) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.LOCK)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
private suspend fun changeSynchronized(
|
||||
albumId: String,
|
||||
settings: ScheduleSettings
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, ScreenType.HOME)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val prepared = result.data
|
||||
val samePresentation =
|
||||
settings.homeEffects == settings.lockEffects &&
|
||||
settings.homeScalingType == settings.lockScalingType
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
Log.d(TAG, "Lock wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper", e)
|
||||
} finally {
|
||||
// Always recycle bitmap to prevent memory leaks
|
||||
bitmap.recycle()
|
||||
if (samePresentation) {
|
||||
applyPrepared(
|
||||
prepared,
|
||||
WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK,
|
||||
listOf(ScreenType.HOME, ScreenType.LOCK)
|
||||
)
|
||||
Log.d(TAG, "Home and lock wallpaper set atomically")
|
||||
} else {
|
||||
applyPrepared(
|
||||
prepared,
|
||||
WallpaperManager.FLAG_SYSTEM,
|
||||
listOf(ScreenType.HOME)
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper set in BOTH mode")
|
||||
|
||||
when (
|
||||
val lockResult = reapplyEffectsUseCase(
|
||||
albumId,
|
||||
ScreenType.LOCK,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
) {
|
||||
is PaperizeResult.Success -> {
|
||||
val lockBitmap = lockResult.data
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(
|
||||
lockBitmap,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
changeWallpaperUseCase.complete(prepared, ScreenType.LOCK)
|
||||
Log.d(TAG, "Lock wallpaper set separately in BOTH mode")
|
||||
} finally {
|
||||
lockBitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> throw asException(lockResult.exception)
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
}
|
||||
}.onError { error ->
|
||||
if (error.message?.contains("No wallpapers available in album") == true) {
|
||||
handleEmptyAlbumError()
|
||||
} else {
|
||||
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(ScreenType.BOTH)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeSingle(
|
||||
albumId: String,
|
||||
screenType: ScreenType
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, screenType)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val which = when (screenType) {
|
||||
ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM
|
||||
ScreenType.LOCK -> WallpaperManager.FLAG_LOCK
|
||||
else -> error("Unsupported static screen: $screenType")
|
||||
}
|
||||
applyPrepared(result.data, which, listOf(screenType))
|
||||
Log.d(TAG, "$screenType wallpaper changed successfully")
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
handleEmptyAlbumError(screenType)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyPrepared(
|
||||
prepared: PreparedWallpaper,
|
||||
which: Int,
|
||||
completedScreens: List<ScreenType>
|
||||
) {
|
||||
var platformAccepted = false
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(prepared.bitmap, which)
|
||||
platformAccepted = true
|
||||
completedScreens.forEach { screen ->
|
||||
changeWallpaperUseCase.complete(prepared, screen)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (!platformAccepted) {
|
||||
changeWallpaperUseCase.restore(prepared)
|
||||
}
|
||||
throw e
|
||||
} finally {
|
||||
prepared.bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleReapplyEffects(screenType: ScreenType, startId: Int) {
|
||||
serviceScope.launch {
|
||||
wallpaperChangeLock.mutex.withLock {
|
||||
try {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
when (screenType) {
|
||||
ScreenType.HOME -> settings.homeAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.HOME)
|
||||
}
|
||||
|
||||
ScreenType.LOCK -> settings.lockAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.LOCK)
|
||||
}
|
||||
|
||||
ScreenType.BOTH -> {
|
||||
settings.homeAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.HOME)
|
||||
}
|
||||
settings.lockAlbumId?.let {
|
||||
reapplySingle(it, ScreenType.LOCK)
|
||||
}
|
||||
}
|
||||
|
||||
ScreenType.LIVE -> Unit
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error reapplying effects", e)
|
||||
showErrorNotification(
|
||||
getString(R.string.app_name),
|
||||
e.localizedMessage
|
||||
?: getString(R.string.error_no_valid_wallpaper_after_retries)
|
||||
)
|
||||
} finally {
|
||||
stopSelf(startId)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createNotification(): Notification {
|
||||
val intent = Intent(this, MainActivity::class.java)
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
private suspend fun reapplySingle(
|
||||
albumId: String,
|
||||
screenType: ScreenType
|
||||
) {
|
||||
when (val result = reapplyEffectsUseCase(albumId, screenType)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val bitmap = result.data
|
||||
try {
|
||||
val which = if (screenType == ScreenType.HOME) {
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
} else {
|
||||
WallpaperManager.FLAG_LOCK
|
||||
}
|
||||
wallpaperManager.setBitmapChecked(bitmap, which)
|
||||
Log.d(TAG, "$screenType effects reapplied successfully")
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
return NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(getString(R.string.changing_wallpaper))
|
||||
.setSmallIcon(R.drawable.ic_launcher_foreground)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
is PaperizeResult.Error -> {
|
||||
Log.w(TAG, "Reapply failed for $screenType; advancing queue", result.exception)
|
||||
changeSingle(albumId, screenType)
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show an error notification to the user
|
||||
*/
|
||||
private fun showErrorNotification(title: String, message: String) {
|
||||
val intent = Intent(this, MainActivity::class.java)
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(title)
|
||||
.setContentText(message)
|
||||
.setSmallIcon(R.drawable.ic_launcher_foreground)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(ERROR_NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle empty album error by showing notification and disabling wallpaper changer
|
||||
*/
|
||||
private suspend fun handleEmptyAlbumError() {
|
||||
Log.w(TAG, "Album is empty, disabling wallpaper changer")
|
||||
|
||||
// Disable wallpaper changer
|
||||
private suspend fun handleEmptyAlbumError(screenType: ScreenType) {
|
||||
val settings = settingsRepository.getScheduleSettings()
|
||||
settingsRepository.updateScheduleSettings(settings.copy(enableChanger = false))
|
||||
val updated = when (screenType) {
|
||||
ScreenType.HOME -> {
|
||||
val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
enableChanger = lockStillActive && settings.enableChanger
|
||||
)
|
||||
}
|
||||
|
||||
// Show notification to user
|
||||
ScreenType.LOCK -> {
|
||||
val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
settings.copy(
|
||||
lockAlbumId = null,
|
||||
enableChanger = homeStillActive && settings.enableChanger
|
||||
)
|
||||
}
|
||||
|
||||
ScreenType.BOTH -> settings.copy(
|
||||
homeAlbumId = null,
|
||||
lockAlbumId = null,
|
||||
enableChanger = false
|
||||
)
|
||||
|
||||
ScreenType.LIVE -> settings.copy(enableChanger = false)
|
||||
}
|
||||
settingsRepository.updateScheduleSettings(updated)
|
||||
showErrorNotification(
|
||||
getString(R.string.no_wallpapers_in_album),
|
||||
getString(R.string.wallpaper_changer_disabled_empty_album)
|
||||
)
|
||||
}
|
||||
|
||||
private fun createNotification(): Notification {
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent().setClassName(packageName, MainActivity::class.java.name),
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
return NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(getString(R.string.app_name))
|
||||
.setContentText(getString(R.string.changing_wallpaper))
|
||||
.setSmallIcon(R.drawable.ic_launcher_monochrome)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun showErrorNotification(title: String, message: String) {
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent().setClassName(packageName, MainActivity::class.java.name),
|
||||
PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
val notification = NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle(title)
|
||||
.setContentText(message)
|
||||
.setSmallIcon(R.drawable.ic_launcher_monochrome)
|
||||
.setContentIntent(pendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.build()
|
||||
notificationManager.notify(ERROR_NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
private fun asException(throwable: Throwable): Exception =
|
||||
throwable as? Exception ?: RuntimeException(throwable)
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceScope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WallpaperChangeService"
|
||||
const val ACTION_CHANGE_WALLPAPER = Constants.ACTION_CHANGE_WALLPAPER
|
||||
const val ACTION_CHANGE_WALLPAPER_AUTO =
|
||||
"com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER_AUTO"
|
||||
const val ACTION_REAPPLY_EFFECTS = Constants.ACTION_REAPPLY_EFFECTS
|
||||
const val EXTRA_SCREEN_TYPE = Constants.EXTRA_SCREEN_TYPE
|
||||
private const val ERROR_NOTIFICATION_ID = Constants.NOTIFICATION_ID + 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.anthonyla.paperize.service.worker
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
|
||||
/**
|
||||
* Schedules a folder rescan whenever Paperize enters the foreground.
|
||||
*
|
||||
* Unique work with [ExistingWorkPolicy.KEEP] coalesces rapid foreground transitions and avoids
|
||||
* running a second scan while an existing one is still active.
|
||||
*/
|
||||
object AlbumRefreshScheduler {
|
||||
internal const val UNIQUE_WORK_NAME = "album_refresh_on_foreground"
|
||||
internal const val WORK_TAG = "foreground_album_refresh"
|
||||
|
||||
fun enqueue(context: Context) {
|
||||
val request = OneTimeWorkRequestBuilder<AlbumRefreshWorker>()
|
||||
.addTag(WORK_TAG)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
UNIQUE_WORK_NAME,
|
||||
ExistingWorkPolicy.KEEP,
|
||||
request
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import dagger.assisted.AssistedInject
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.first
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Background worker that validates and refreshes all albums daily
|
||||
@@ -45,12 +47,12 @@ class AlbumRefreshWorker @AssistedInject constructor(
|
||||
}
|
||||
|
||||
var totalRemoved = 0
|
||||
var totalAdded = 0
|
||||
var failedCount = 0
|
||||
val totalAdded = AtomicInteger(0)
|
||||
val failedCount = AtomicInteger(0)
|
||||
|
||||
// Refresh each album
|
||||
albums.forEach { album ->
|
||||
var albumHasNewWallpapers = false
|
||||
val albumHasNewWallpapers = AtomicBoolean(false)
|
||||
|
||||
// Step 1: Validate and remove invalid URIs
|
||||
when (val result = refreshAlbumUseCase(album.id)) {
|
||||
@@ -63,7 +65,7 @@ class AlbumRefreshWorker @AssistedInject constructor(
|
||||
}
|
||||
is CoreResult.Error -> {
|
||||
Log.e(TAG, "Error validating album '${album.name}'", result.exception)
|
||||
failedCount++
|
||||
failedCount.incrementAndGet()
|
||||
}
|
||||
is CoreResult.Loading -> {
|
||||
/* Loading state not used */
|
||||
@@ -74,27 +76,29 @@ class AlbumRefreshWorker @AssistedInject constructor(
|
||||
coroutineScope {
|
||||
album.folders.map { folder ->
|
||||
async {
|
||||
// Load existing URIs for this folder once — avoids one DB query per scanned wallpaper
|
||||
val existingUris = wallpaperRepository.getExistingWallpaperUris(album.id, folder.id)
|
||||
|
||||
when (val scanResult = wallpaperRepository.scanFolderForWallpapers(android.net.Uri.parse(folder.uri))) {
|
||||
is CoreResult.Success -> {
|
||||
val scannedWallpapers = scanResult.data
|
||||
|
||||
// Find and add new wallpapers not already in album
|
||||
scannedWallpapers.forEach { wallpaper ->
|
||||
// Memory-efficient check: check database for existing URI in this album
|
||||
if (!wallpaperRepository.isWallpaperInAlbum(album.id, wallpaper.uri)) {
|
||||
if (wallpaper.uri !in existingUris) {
|
||||
val wallpaperToAdd = wallpaper.copy(
|
||||
albumId = album.id,
|
||||
folderId = folder.id
|
||||
)
|
||||
|
||||
|
||||
when (wallpaperRepository.addWallpaper(wallpaperToAdd)) {
|
||||
is CoreResult.Success -> {
|
||||
totalAdded++
|
||||
albumHasNewWallpapers = true
|
||||
totalAdded.incrementAndGet()
|
||||
albumHasNewWallpapers.set(true)
|
||||
}
|
||||
is CoreResult.Error -> {
|
||||
Log.e(TAG, "Error adding wallpaper to album '${album.name}'")
|
||||
failedCount++
|
||||
failedCount.incrementAndGet()
|
||||
}
|
||||
is CoreResult.Loading -> { /* Not used */ }
|
||||
}
|
||||
@@ -110,8 +114,10 @@ class AlbumRefreshWorker @AssistedInject constructor(
|
||||
}.forEach { it.await() }
|
||||
}
|
||||
|
||||
// Step 3: Refresh folder covers if new wallpapers were added
|
||||
if (albumHasNewWallpapers) {
|
||||
// Step 3: Clear and rebuild queues and refresh covers if new wallpapers were added
|
||||
if (albumHasNewWallpapers.get()) {
|
||||
// Clear queues so they are rebuilt on next change, including new wallpapers
|
||||
wallpaperRepository.clearQueuesForAlbum(album.id)
|
||||
when (albumRepository.refreshFolderCovers(album.id)) {
|
||||
is CoreResult.Success -> {
|
||||
Log.d(TAG, "Album '${album.name}': folder covers refreshed")
|
||||
@@ -126,7 +132,7 @@ class AlbumRefreshWorker @AssistedInject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
Log.d(TAG, "Daily album refresh completed: removed $totalRemoved items, added $totalAdded new wallpapers across ${albums.size} albums ($failedCount failures)")
|
||||
Log.d(TAG, "Daily album refresh completed: removed $totalRemoved items, added ${totalAdded.get()} new wallpapers across ${albums.size} albums (${failedCount.get()} failures)")
|
||||
|
||||
// Return success even if some albums failed (partial success)
|
||||
androidx.work.ListenableWorker.Result.success()
|
||||
|
||||
@@ -2,60 +2,53 @@ package com.anthonyla.paperize.service.worker
|
||||
|
||||
import android.app.WallpaperManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.hilt.work.HiltWorker
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.anthonyla.paperize.core.EmptyAlbumException
|
||||
import com.anthonyla.paperize.core.Result as PaperizeResult
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.util.setBitmapChecked
|
||||
import com.anthonyla.paperize.domain.model.PreparedWallpaper
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
|
||||
import com.anthonyla.paperize.domain.usecase.ReapplyEffectsUseCase
|
||||
import com.anthonyla.paperize.service.WallpaperChangeLock
|
||||
import dagger.assisted.Assisted
|
||||
import dagger.assisted.AssistedInject
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/**
|
||||
* WorkManager worker for changing wallpapers
|
||||
*
|
||||
* Handles periodic wallpaper changes for home screen, lock screen, or both.
|
||||
* Uses CoroutineWorker for suspend function support and Hilt for dependency injection.
|
||||
* WorkManager worker for scheduled wallpaper changes.
|
||||
*/
|
||||
@HiltWorker
|
||||
class WallpaperChangeWorker @AssistedInject constructor(
|
||||
@Assisted private val context: Context,
|
||||
@Assisted workerParams: WorkerParameters,
|
||||
private val changeWallpaperUseCase: ChangeWallpaperUseCase,
|
||||
private val settingsRepository: SettingsRepository
|
||||
private val reapplyEffectsUseCase: ReapplyEffectsUseCase,
|
||||
private val settingsRepository: SettingsRepository,
|
||||
private val wallpaperChangeLock: WallpaperChangeLock
|
||||
) : CoroutineWorker(context, workerParams) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "WallpaperChangeWorker"
|
||||
|
||||
/**
|
||||
* Mutex to prevent concurrent wallpaper changes
|
||||
* Ensures only one wallpaper change operation runs at a time
|
||||
*/
|
||||
private val wallpaperChangeMutex = Mutex()
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
return try {
|
||||
val screenTypeString = inputData.getString(Constants.EXTRA_SCREEN_TYPE)
|
||||
val screenType = screenTypeString?.let { ScreenType.fromString(it) } ?: ScreenType.HOME
|
||||
val screenType = inputData.getString(Constants.EXTRA_SCREEN_TYPE)
|
||||
?.let(ScreenType::fromString)
|
||||
?: ScreenType.HOME
|
||||
|
||||
Log.d(TAG, "Starting wallpaper change for $screenType")
|
||||
|
||||
// Use mutex to prevent concurrent wallpaper changes
|
||||
wallpaperChangeMutex.withLock {
|
||||
wallpaperChangeLock.mutex.withLock {
|
||||
changeWallpaper(screenType)
|
||||
}
|
||||
|
||||
Log.d(TAG, "Wallpaper change completed successfully for $screenType")
|
||||
Result.success()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error changing wallpaper", e)
|
||||
// Retry on failure (WorkManager will handle backoff)
|
||||
if (runAttemptCount < Constants.MAX_WORK_RETRY_ATTEMPTS) {
|
||||
Result.retry()
|
||||
} else {
|
||||
@@ -70,147 +63,207 @@ class WallpaperChangeWorker @AssistedInject constructor(
|
||||
|
||||
when (screenType) {
|
||||
ScreenType.LIVE -> {
|
||||
// Send broadcast to trigger live wallpaper reload
|
||||
val intent = android.content.Intent(Constants.ACTION_RELOAD_WALLPAPER)
|
||||
intent.setPackage(context.packageName)
|
||||
context.sendBroadcast(intent)
|
||||
context.sendBroadcast(
|
||||
Intent(Constants.ACTION_RELOAD_WALLPAPER).setPackage(context.packageName)
|
||||
)
|
||||
Log.d(TAG, "Sent reload broadcast to live wallpaper service")
|
||||
}
|
||||
|
||||
ScreenType.HOME -> {
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
if (homeAlbumId != null) {
|
||||
changeHomeWallpaper(homeAlbumId, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No home album selected")
|
||||
}
|
||||
settings.homeAlbumId?.let {
|
||||
changeSingle(it, ScreenType.HOME, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No home album selected")
|
||||
}
|
||||
|
||||
ScreenType.LOCK -> {
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (lockAlbumId != null) {
|
||||
changeLockWallpaper(lockAlbumId, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
settings.lockAlbumId?.let {
|
||||
changeSingle(it, ScreenType.LOCK, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No lock album selected")
|
||||
}
|
||||
|
||||
ScreenType.BOTH -> {
|
||||
// Synchronized mode: set both screens to the same wallpaper
|
||||
// This ensures both HOME and LOCK show identical wallpapers
|
||||
// Use home album, fallback to lock album (they should be the same when synced)
|
||||
val albumId = settings.homeAlbumId ?: settings.lockAlbumId
|
||||
|
||||
if (albumId != null) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
Log.d(TAG, "Setting both screens - size: ${bitmap.width}x${bitmap.height}, config: ${bitmap.config}")
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Both screens wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting wallpaper for both screens", e)
|
||||
throw e
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.e(TAG, "Error getting wallpaper bitmap for both screens", error)
|
||||
throw error
|
||||
}
|
||||
val homeAlbumId = settings.homeAlbumId
|
||||
val lockAlbumId = settings.lockAlbumId
|
||||
if (
|
||||
homeAlbumId != null &&
|
||||
homeAlbumId == lockAlbumId &&
|
||||
!settings.separateSchedules
|
||||
) {
|
||||
changeSynchronized(homeAlbumId, settings, wallpaperManager)
|
||||
} else {
|
||||
Log.w(TAG, "No album selected for synchronized mode")
|
||||
homeAlbumId?.let {
|
||||
changeSingle(it, ScreenType.HOME, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No home album selected for BOTH mode")
|
||||
lockAlbumId?.let {
|
||||
changeSingle(it, ScreenType.LOCK, settings, wallpaperManager)
|
||||
} ?: Log.w(TAG, "No lock album selected for BOTH mode")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeHomeWallpaper(albumId: String, wallpaperManager: WallpaperManager) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.HOME)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
private suspend fun changeSynchronized(
|
||||
albumId: String,
|
||||
settings: ScheduleSettings,
|
||||
wallpaperManager: WallpaperManager
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, ScreenType.HOME)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val prepared = result.data
|
||||
val samePresentation =
|
||||
settings.homeEffects == settings.lockEffects &&
|
||||
settings.homeScalingType == settings.lockScalingType
|
||||
|
||||
if (samePresentation) {
|
||||
applyPrepared(
|
||||
prepared = prepared,
|
||||
wallpaperManager = wallpaperManager,
|
||||
which = WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK,
|
||||
completedScreens = listOf(ScreenType.HOME, ScreenType.LOCK)
|
||||
)
|
||||
Log.d(TAG, "Home and lock wallpaper set atomically")
|
||||
} else {
|
||||
// Distinct effects require two platform writes. Each screen is committed only
|
||||
// after its own write succeeds.
|
||||
applyPrepared(
|
||||
prepared = prepared,
|
||||
wallpaperManager = wallpaperManager,
|
||||
which = WallpaperManager.FLAG_SYSTEM,
|
||||
completedScreens = listOf(ScreenType.HOME)
|
||||
)
|
||||
Log.d(TAG, "Home wallpaper set in BOTH mode")
|
||||
|
||||
when (
|
||||
val lockResult = reapplyEffectsUseCase(
|
||||
albumId,
|
||||
ScreenType.LOCK,
|
||||
prepared.wallpaperId
|
||||
)
|
||||
) {
|
||||
is PaperizeResult.Success -> {
|
||||
val lockBitmap = lockResult.data
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(
|
||||
lockBitmap,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
changeWallpaperUseCase.complete(prepared, ScreenType.LOCK)
|
||||
Log.d(TAG, "Lock wallpaper set separately in BOTH mode")
|
||||
} finally {
|
||||
lockBitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
is PaperizeResult.Error -> throw asException(lockResult.exception)
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
Log.d(TAG, "Setting home wallpaper - size: ${bitmap.width}x${bitmap.height}, config: ${bitmap.config}")
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_SYSTEM
|
||||
)
|
||||
|
||||
// Recycle bitmap after setting to free memory
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Home wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting home wallpaper", e)
|
||||
throw e
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.e(TAG, "Error getting home wallpaper bitmap", error)
|
||||
throw error
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
Log.w(TAG, "Album is empty for BOTH screens; disabling changer")
|
||||
settingsRepository.updateScheduleSettings(
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
lockAlbumId = null,
|
||||
enableChanger = false
|
||||
)
|
||||
)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun changeLockWallpaper(albumId: String, wallpaperManager: WallpaperManager) {
|
||||
val result = changeWallpaperUseCase(albumId, ScreenType.LOCK)
|
||||
result.onSuccess { bitmap ->
|
||||
try {
|
||||
// Validate bitmap before setting
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0) {
|
||||
throw IllegalStateException("Invalid bitmap dimensions: ${bitmap.width}x${bitmap.height}")
|
||||
private suspend fun changeSingle(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
settings: ScheduleSettings,
|
||||
wallpaperManager: WallpaperManager
|
||||
) {
|
||||
when (val result = changeWallpaperUseCase(albumId, screenType)) {
|
||||
is PaperizeResult.Success -> {
|
||||
val flag = when (screenType) {
|
||||
ScreenType.HOME -> WallpaperManager.FLAG_SYSTEM
|
||||
ScreenType.LOCK -> WallpaperManager.FLAG_LOCK
|
||||
else -> error("Unsupported static screen: $screenType")
|
||||
}
|
||||
if (bitmap.isRecycled) {
|
||||
throw IllegalStateException("Bitmap has been recycled")
|
||||
}
|
||||
|
||||
Log.d(TAG, "Setting lock wallpaper - size: ${bitmap.width}x${bitmap.height}, config: ${bitmap.config}")
|
||||
|
||||
wallpaperManager.setBitmap(
|
||||
bitmap,
|
||||
null,
|
||||
true,
|
||||
WallpaperManager.FLAG_LOCK
|
||||
)
|
||||
|
||||
// Recycle bitmap after setting to free memory
|
||||
bitmap.recycle()
|
||||
|
||||
Log.d(TAG, "Lock wallpaper changed successfully")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error setting lock wallpaper", e)
|
||||
throw e
|
||||
applyPrepared(result.data, wallpaperManager, flag, listOf(screenType))
|
||||
Log.d(TAG, "$screenType wallpaper changed successfully")
|
||||
}
|
||||
}.onError { error ->
|
||||
Log.e(TAG, "Error getting lock wallpaper bitmap", error)
|
||||
throw error
|
||||
|
||||
is PaperizeResult.Error -> {
|
||||
if (result.exception is EmptyAlbumException) {
|
||||
disableEmptyScreen(screenType, settings)
|
||||
} else {
|
||||
throw asException(result.exception)
|
||||
}
|
||||
}
|
||||
|
||||
PaperizeResult.Loading -> error("Unexpected loading result")
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun applyPrepared(
|
||||
prepared: PreparedWallpaper,
|
||||
wallpaperManager: WallpaperManager,
|
||||
which: Int,
|
||||
completedScreens: List<ScreenType>
|
||||
) {
|
||||
var platformAccepted = false
|
||||
try {
|
||||
wallpaperManager.setBitmapChecked(prepared.bitmap, which)
|
||||
platformAccepted = true
|
||||
completedScreens.forEach { screen ->
|
||||
changeWallpaperUseCase.complete(prepared, screen)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
if (!platformAccepted) {
|
||||
changeWallpaperUseCase.restore(prepared)
|
||||
}
|
||||
throw e
|
||||
} finally {
|
||||
prepared.bitmap.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun disableEmptyScreen(
|
||||
screenType: ScreenType,
|
||||
settings: ScheduleSettings
|
||||
) {
|
||||
when (screenType) {
|
||||
ScreenType.HOME -> {
|
||||
val lockStillActive = settings.lockEnabled && settings.lockAlbumId != null
|
||||
settingsRepository.updateScheduleSettings(
|
||||
settings.copy(
|
||||
homeAlbumId = null,
|
||||
enableChanger = lockStillActive && settings.enableChanger
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
ScreenType.LOCK -> {
|
||||
val homeStillActive = settings.homeEnabled && settings.homeAlbumId != null
|
||||
settingsRepository.updateScheduleSettings(
|
||||
settings.copy(
|
||||
lockAlbumId = null,
|
||||
enableChanger = homeStillActive && settings.enableChanger
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
|
||||
private fun asException(throwable: Throwable): Exception =
|
||||
throwable as? Exception ?: RuntimeException(throwable)
|
||||
|
||||
private companion object {
|
||||
const val TAG = "WallpaperChangeWorker"
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,6 @@ import kotlinx.coroutines.flow.first
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import java.util.Calendar
|
||||
@@ -38,7 +34,6 @@ class WallpaperScheduler @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context
|
||||
) {
|
||||
private val workManager = WorkManager.getInstance(context)
|
||||
private val schedulerScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
private val mutex = Mutex()
|
||||
|
||||
companion object {
|
||||
@@ -107,7 +102,7 @@ class WallpaperScheduler @Inject constructor(
|
||||
* @param requireCharging Whether device must be charging
|
||||
* @param onlyIfNotScheduled If true, only schedule if work is not already scheduled (for app startup)
|
||||
*/
|
||||
fun scheduleWallpaperChanges(
|
||||
suspend fun scheduleWallpaperChanges(
|
||||
homeIntervalMinutes: Int,
|
||||
lockIntervalMinutes: Int,
|
||||
synchronized: Boolean = false,
|
||||
@@ -115,8 +110,7 @@ class WallpaperScheduler @Inject constructor(
|
||||
requireCharging: Boolean = false,
|
||||
onlyIfNotScheduled: Boolean = false
|
||||
) {
|
||||
schedulerScope.launch {
|
||||
mutex.withLock {
|
||||
mutex.withLock {
|
||||
// Don't cancel all first - let UPDATE policy handle existing work
|
||||
// This prevents immediate wallpaper change when just updating intervals
|
||||
|
||||
@@ -193,7 +187,6 @@ class WallpaperScheduler @Inject constructor(
|
||||
} else {
|
||||
Log.d(TAG, "Skipped scheduling album refresh - already scheduled")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#ffd9e2"
|
||||
android:pathData="M0,0h108v108h-108z"/>
|
||||
</vector>
|
||||
@@ -1,14 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z"/>
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF"/>
|
||||
<group
|
||||
android:translateX="18"
|
||||
android:translateY="18"
|
||||
android:scaleX="0.144"
|
||||
android:scaleY="0.144">
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m119.78,143.16c0.12,1.91 -0.53,3.18 -2.81,3.34c-1.62,0.11 -2.54,1.03 -2.45,2.63c0.1,1.67 1.43,2.12 2.88,2.32c4.09,0.56 8.09,0 11.98,-1.17c7.29,-2.18 14.89,-3.1 22.24,-5.03c2.05,-0.54 4.8,-0.58 5.29,-3.02c0.45,-2.23 -1.28,-3.84 -3.26,-5.01c-0.34,-0.2 -0.48,-0.69 -0.95,-1.39c4.72,-1.86 9.53,-2.2 14.26,-2.73c19.58,-2.2 39.27,-3.56 58.75,-6.61c2.58,-0.4 5.05,-1.48 7.95,-0.84c-7.1,4.43 -14.25,8.73 -22.21,12.06c2.62,-0.31 5.24,-0.56 7.85,-0.96c2.62,-0.39 5.2,-0.98 7.82,-1.39c33.55,-5.25 63.84,-18.76 93.72,-33.33c8.64,-4.21 17.58,-7.82 26.9,-10.52c5.24,-1.51 10.08,-1.2 15.03,1.23c11.07,5.43 18.44,14.04 23.99,24.32c0.32,0.6 0.51,1.23 0.12,2.1c-1.81,0.33 -3.92,1.24 -3.68,-2.1c0.06,-0.82 -0.26,-1.66 -0.98,-2.01c-5.57,-2.69 -10.39,-7.45 -17.79,-4.33c-5.12,2.16 -10.84,2.99 -15.94,5.61c1.14,2.08 2.8,2.53 4.95,2.04c0.89,-0.2 1.83,-0.23 2.75,-0.24c2.05,-0.02 3.26,0.97 3.57,2.88c0.34,2.08 -1.22,2.64 -2.87,3.03c-5.94,1.41 -11.89,2.78 -17.83,4.18c-14.14,3.33 -27.79,8.26 -41.88,11.74c-20.22,4.99 -40.48,9.92 -61.53,10.75c-3.07,0.12 -6.12,0.55 -9.2,1.13c4.59,1.02 8.86,3.02 13.93,2.04c4.15,-0.8 8.5,-0.73 12.77,-0.97c13.55,-0.74 26.82,-2.89 39.79,-6.72c1.65,-0.49 3.27,-1.03 4.91,-1.54c0.08,-0.02 0.2,0.08 0.82,0.33c-3.22,3.6 -7.67,5.28 -12.49,7.77c3.43,0.96 5.74,0.12 7.99,-0.28c17.61,-3.14 34.68,-8.36 52.08,-12.33c14.88,-3.4 29.85,-5.74 45.24,-5.16c3.96,0.15 7.81,0.73 11.63,1.56c2.18,0.47 3.96,1.57 5.49,3.22c7.93,8.58 11.69,18.79 13.31,29.89c0.36,2.48 0.73,4.96 1.23,8.44c-5.63,-2.32 -10.62,-4.38 -15.77,-6.51c1.08,-1.21 2.18,-0.7 3.14,-0.84c1.4,-0.21 3.46,0.41 3.7,-1.52c0.2,-1.62 -0.67,-3.34 -2.48,-4c-2.8,-1.02 -5.63,-2.03 -8.53,-2.69c-16.73,-3.79 -33.46,-2.92 -50.17,0.21c-10.65,2 -21.23,4.28 -31.56,7.52c-0.66,0.21 -1.33,0.38 -1.96,0.66c-1.42,0.64 -2.77,1.53 -2.31,3.23c0.49,1.82 2.23,1.33 3.49,1.11c6.14,-1.05 12.24,-2.28 18.15,-4.22c0.93,-0.31 1.86,-0.91 3.36,-0.32c-4.43,4.37 -10.54,6.29 -15.64,11c7.71,-1.24 14.47,-2.3 21.23,-3.41c17.82,-2.91 35.73,-3.53 53.23,1.12c22.09,5.87 31.92,18.19 32.70,38.85c0.37,9.87 -1.36,19.46 -5.12,28.68c-0.35,0.85 -0.25,2.03 -1.52,2.36c-0.75,-0.28 -0.67,-0.9 -0.57,-1.39c2.78,-13.87 -7.33,-28.84 -20.86,-35.19c-11.66,-5.47 -24.11,-6.5 -36.83,-5.95c-2.56,0.11 -4.96,1.06 -6.84,2.87c-0.79,0.76 -2,1.37 -1.49,2.71c0.56,1.46 1.9,1.8 3.38,1.8c4.86,0.01 9.7,0.22 14.55,0.58c5.19,0.38 10.29,1.3 15.41,2.04c2.61,0.38 3.83,1.69 4.39,4.18c3,13.2 3.62,26.49 2.35,39.92c-1.92,20.28 -7.86,39.43 -18.09,57.28c-13.79,24.06 -32.62,43.8 -56.81,58.92c-23.72,14.82 -49.84,23.01 -77.92,25.22c-16.94,1.34 -33.94,0.55 -50.58,-3.6c-2.77,-0.69 -4,-1.68 -3.99,-4.62c0.1,-30.78 0.09,-61.55 -0.01,-92.33c-0.01,-3.16 1.31,-3.88 4.34,-3.87c16.66,0.09 33.31,0.13 49.97,0.01c17.16,-0.13 33.88,-2.74 49.34,-10.1c16.47,-7.83 27.72,-20.13 31.81,-37.42c4.22,-17.87 -0.51,-33.71 -13.68,-47.17c-13.19,-13.47 -29.98,-20.97 -48.14,-26.23c-15.3,-4.43 -31.01,-6.68 -46.82,-8.6c-23.37,-2.84 -46.84,-2.06 -70.3,-2.05c-3.26,0 -4.15,1.18 -4.15,4.09c0.05,33.74 0.02,67.49 -0.01,101.23c-0.03,49.35 -0.07,98.7 -0.1,148.05c0,3.59 0,7.18 0,10.6c-1.48,0.35 -1.94,-0.22 -2.38,-0.69c-5.01,-5.32 -9.99,-10.68 -15,-16c-1.55,-1.64 -2.19,-3.47 -2.18,-5.7c0.04,-16.8 -0.02,-33.59 -0.01,-50.39c0.01,-60.22 0.03,-120.45 0.04,-180.67c0,-3.53 -1.9,-5.11 -7.31,-6.17c-1.1,1.22 -0.64,2.71 -0.64,4.07c-0.05,68.37 -0.07,136.73 -0.1,205.1c0,1.43 0.01,2.87 -0.22,4.27c-0.2,1.21 0.02,2.97 -1.92,3.04c-1.8,0.07 -3.44,-0.65 -4.25,-2.33c-0.9,-1.85 -0.82,-3.85 -0.82,-5.83c0,-46.49 -0.02,-92.99 -0.03,-139.48c0,-21.87 -0.16,-43.75 0.12,-65.62c0.06,-4.44 -1.17,-7.31 -5.39,-9.06c-0.93,-0.38 -1.56,-1.33 -2.83,-1.36c-1.86,1.03 -1.24,2.85 -1.24,4.38c-0.03,39.46 -0.02,78.92 0,118.38c0.01,21.98 0.04,43.97 0.05,65.95c0,0.86 -0.11,1.73 -0.17,2.65c-0.47,0 -0.92,0.13 -1.09,-0.02c-5.41,-4.82 -10.25,-10.15 -14.95,-15.57c-1.54,-1.77 -1.46,-4.23 -1.29,-6.35c0.83,-10 -1.7,-19 -6.22,-28.14c-6.92,-13.99 -9.7,-29.17 -10.86,-44.64c-1.48,-19.74 0.59,-39.01 7.04,-57.82c1.36,-3.95 3.25,-7.74 5.04,-11.55c0.72,-1.53 1.3,-3.21 3.73,-3.4c1.76,-0.14 1.13,-1.94 1.14,-3.01c0.09,-9.01 0.67,-18.07 -0.05,-27.03c-0.92,-11.47 3.6,-19.73 13.1,-26.55c11.91,-8.54 24.8,-15.29 38.25,-21.23c23.28,-10.28 48.05,-16.26 72.66,-22.69c22.92,-5.99 45.3,-13.22 65.4,-25.68c0.77,-0.48 1.66,-0.87 2.28,-1.49c3.93,-3.96 8.51,-3.63 13.42,-2.14c3.92,1.19 7.9,2.17 11.76,4.23c-0.5,0.61 -0.69,1.05 -1.03,1.23c-17.7,9.51 -34.97,19.8 -54.03,26.85c-16.64,6.15 -33.83,10.39 -51.24,13.95c-23.31,4.77 -46.36,10.38 -67.27,21.86c-6.11,3.35 -12.21,6.77 -16.74,12.11c-2.16,2.54 -3.7,5.25 -1.91,8.79c3.89,-1.06 7.2,-3.03 11.3,-3.42c0.27,-0.02 0.25,-0.03 0.25,-0.03z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m229.85,206.59c7,0.72 13.53,1.94 19.74,4.5c15.36,6.33 21.74,22.48 13.76,35.4c-4.75,7.69 -12.74,10.65 -21.48,11.59c-15.07,1.62 -30.23,0.41 -45.34,0.76c-3.12,0.07 -3.27,-1.76 -3.27,-3.86c-0.01,-8.45 0,-16.9 0,-25.35c0,-6.7 0.09,-13.39 -0.08,-20.08c-0.07,-2.75 1.05,-3.7 3.82,-3.71c10.85,-0.02 21.7,0.09 32.85,0.76z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m282.21,100.35c-15.38,7.15 -30.52,14.23 -46.94,18.36c-12.3,3.09 -24.78,5.08 -37.45,6.3c-24.56,2.37 -49.15,4.7 -72.88,11.77c-3.49,1.04 -6.89,2.38 -10.72,3.72c0.46,-1.7 1.81,-1.96 2.74,-2.58c16.23,-10.84 34.72,-16.69 53.51,-21.95c17.5,-4.91 35.46,-8 53.06,-12.51c20.3,-5.2 39.49,-12.88 57.9,-22.48c9.71,-5.06 19.36,-10.32 30.28,-12.85c2.75,-0.64 5.44,-0.68 8.19,0.11c7.84,2.25 15.04,5.56 21.2,10.8c2.07,1.76 2.04,2.97 -0.61,4.03c-2.13,0.85 -4.24,1.75 -6.29,2.77c-2.3,1.15 -4.22,2.35 -6.31,-0.65c-1.08,-1.55 -3.48,-1.19 -5.5,-0.63c-13.93,3.84 -27.19,9.18 -40.18,15.81z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m303.24,101.85c-12.25,6.44 -24.42,12.47 -37.93,15.78c11.59,-7.31 23.12,-14.65 34.36,-22.68c1.64,2.75 -1.87,3.45 -1.32,5.57c9.97,-2.78 17.58,-10.55 28.22,-11.64c-7.15,5.21 -15.54,8.37 -23.32,12.98z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m372.48,118.37c2.83,-0.1 5.42,-0.73 8.77,-0.08c-3.06,1.8 -5.64,2.71 -8.53,2.47c-2.39,-0.21 -2.29,-1.15 -0.24,-2.38z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m366.29,165.61c2.44,0.09 4.4,-2.02 6.76,-0.38c-4.13,0.53 -7.54,3.68 -12.75,2.84c1.93,-1.77 3.94,-1.86 5.98,-2.46z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m119.8,143.18c2.81,-1.52 5.24,-2.16 8.2,-1.99c-2.16,2.94 -5.15,1.59 -7.9,1.97c-0.31,0 -0.3,0.02 -0.3,0.02z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<group
|
||||
android:translateX="18"
|
||||
android:translateY="18"
|
||||
android:scaleX="0.144"
|
||||
android:scaleY="0.144">
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m119.78,143.16c0.12,1.91 -0.53,3.18 -2.81,3.34c-1.62,0.11 -2.54,1.03 -2.45,2.63c0.1,1.67 1.43,2.12 2.88,2.32c4.09,0.56 8.09,0 11.98,-1.17c7.29,-2.18 14.89,-3.1 22.24,-5.03c2.05,-0.54 4.8,-0.58 5.29,-3.02c0.45,-2.23 -1.28,-3.84 -3.26,-5.01c-0.34,-0.2 -0.48,-0.69 -0.95,-1.39c4.72,-1.86 9.53,-2.2 14.26,-2.73c19.58,-2.2 39.27,-3.56 58.75,-6.61c2.58,-0.4 5.05,-1.48 7.95,-0.84c-7.1,4.43 -14.25,8.73 -22.21,12.06c2.62,-0.31 5.24,-0.56 7.85,-0.96c2.62,-0.39 5.2,-0.98 7.82,-1.39c33.55,-5.25 63.84,-18.76 93.72,-33.33c8.64,-4.21 17.58,-7.82 26.9,-10.52c5.24,-1.51 10.08,-1.2 15.03,1.23c11.07,5.43 18.44,14.04 23.99,24.32c0.32,0.6 0.51,1.23 0.12,2.1c-1.81,0.33 -3.92,1.24 -3.68,-2.1c0.06,-0.82 -0.26,-1.66 -0.98,-2.01c-5.57,-2.69 -10.39,-7.45 -17.79,-4.33c-5.12,2.16 -10.84,2.99 -15.94,5.61c1.14,2.08 2.8,2.53 4.95,2.04c0.89,-0.2 1.83,-0.23 2.75,-0.24c2.05,-0.02 3.26,0.97 3.57,2.88c0.34,2.08 -1.22,2.64 -2.87,3.03c-5.94,1.41 -11.89,2.78 -17.83,4.18c-14.14,3.33 -27.79,8.26 -41.88,11.74c-20.22,4.99 -40.48,9.92 -61.53,10.75c-3.07,0.12 -6.12,0.55 -9.2,1.13c4.59,1.02 8.86,3.02 13.93,2.04c4.15,-0.8 8.5,-0.73 12.77,-0.97c13.55,-0.74 26.82,-2.89 39.79,-6.72c1.65,-0.49 3.27,-1.03 4.91,-1.54c0.08,-0.02 0.2,0.08 0.82,0.33c-3.22,3.6 -7.67,5.28 -12.49,7.77c3.43,0.96 5.74,0.12 7.99,-0.28c17.61,-3.14 34.68,-8.36 52.08,-12.33c14.88,-3.4 29.85,-5.74 45.24,-5.16c3.96,0.15 7.81,0.73 11.63,1.56c2.18,0.47 3.96,1.57 5.49,3.22c7.93,8.58 11.69,18.79 13.31,29.89c0.36,2.48 0.73,4.96 1.23,8.44c-5.63,-2.32 -10.62,-4.38 -15.77,-6.51c1.08,-1.21 2.18,-0.7 3.14,-0.84c1.4,-0.21 3.46,0.41 3.7,-1.52c0.2,-1.62 -0.67,-3.34 -2.48,-4c-2.8,-1.02 -5.63,-2.03 -8.53,-2.69c-16.73,-3.79 -33.46,-2.92 -50.17,0.21c-10.65,2 -21.23,4.28 -31.56,7.52c-0.66,0.21 -1.33,0.38 -1.96,0.66c-1.42,0.64 -2.77,1.53 -2.31,3.23c0.49,1.82 2.23,1.33 3.49,1.11c6.14,-1.05 12.24,-2.28 18.15,-4.22c0.93,-0.31 1.86,-0.91 3.36,-0.32c-4.43,4.37 -10.54,6.29 -15.64,11c7.71,-1.24 14.47,-2.3 21.23,-3.41c17.82,-2.91 35.73,-3.53 53.23,1.12c22.09,5.87 31.92,18.19 32.70,38.85c0.37,9.87 -1.36,19.46 -5.12,28.68c-0.35,0.85 -0.25,2.03 -1.52,2.36c-0.75,-0.28 -0.67,-0.9 -0.57,-1.39c2.78,-13.87 -7.33,-28.84 -20.86,-35.19c-11.66,-5.47 -24.11,-6.5 -36.83,-5.95c-2.56,0.11 -4.96,1.06 -6.84,2.87c-0.79,0.76 -2,1.37 -1.49,2.71c0.56,1.46 1.9,1.8 3.38,1.8c4.86,0.01 9.7,0.22 14.55,0.58c5.19,0.38 10.29,1.3 15.41,2.04c2.61,0.38 3.83,1.69 4.39,4.18c3,13.2 3.62,26.49 2.35,39.92c-1.92,20.28 -7.86,39.43 -18.09,57.28c-13.79,24.06 -32.62,43.8 -56.81,58.92c-23.72,14.82 -49.84,23.01 -77.92,25.22c-16.94,1.34 -33.94,0.55 -50.58,-3.6c-2.77,-0.69 -4,-1.68 -3.99,-4.62c0.1,-30.78 0.09,-61.55 -0.01,-92.33c-0.01,-3.16 1.31,-3.88 4.34,-3.87c16.66,0.09 33.31,0.13 49.97,0.01c17.16,-0.13 33.88,-2.74 49.34,-10.1c16.47,-7.83 27.72,-20.13 31.81,-37.42c4.22,-17.87 -0.51,-33.71 -13.68,-47.17c-13.19,-13.47 -29.98,-20.97 -48.14,-26.23c-15.3,-4.43 -31.01,-6.68 -46.82,-8.6c-23.37,-2.84 -46.84,-2.06 -70.3,-2.05c-3.26,0 -4.15,1.18 -4.15,4.09c0.05,33.74 0.02,67.49 -0.01,101.23c-0.03,49.35 -0.07,98.7 -0.1,148.05c0,3.59 0,7.18 0,10.6c-1.48,0.35 -1.94,-0.22 -2.38,-0.69c-5.01,-5.32 -9.99,-10.68 -15,-16c-1.55,-1.64 -2.19,-3.47 -2.18,-5.7c0.04,-16.8 -0.02,-33.59 -0.01,-50.39c0.01,-60.22 0.03,-120.45 0.04,-180.67c0,-3.53 -1.9,-5.11 -7.31,-6.17c-1.1,1.22 -0.64,2.71 -0.64,4.07c-0.05,68.37 -0.07,136.73 -0.1,205.1c0,1.43 0.01,2.87 -0.22,4.27c-0.2,1.21 0.02,2.97 -1.92,3.04c-1.8,0.07 -3.44,-0.65 -4.25,-2.33c-0.9,-1.85 -0.82,-3.85 -0.82,-5.83c0,-46.49 -0.02,-92.99 -0.03,-139.48c0,-21.87 -0.16,-43.75 0.12,-65.62c0.06,-4.44 -1.17,-7.31 -5.39,-9.06c-0.93,-0.38 -1.56,-1.33 -2.83,-1.36c-1.86,1.03 -1.24,2.85 -1.24,4.38c-0.03,39.46 -0.02,78.92 0,118.38c0.01,21.98 0.04,43.97 0.05,65.95c0,0.86 -0.11,1.73 -0.17,2.65c-0.47,0 -0.92,0.13 -1.09,-0.02c-5.41,-4.82 -10.25,-10.15 -14.95,-15.57c-1.54,-1.77 -1.46,-4.23 -1.29,-6.35c0.83,-10 -1.7,-19 -6.22,-28.14c-6.92,-13.99 -9.7,-29.17 -10.86,-44.64c-1.48,-19.74 0.59,-39.01 7.04,-57.82c1.36,-3.95 3.25,-7.74 5.04,-11.55c0.72,-1.53 1.3,-3.21 3.73,-3.4c1.76,-0.14 1.13,-1.94 1.14,-3.01c0.09,-9.01 0.67,-18.07 -0.05,-27.03c-0.92,-11.47 3.6,-19.73 13.1,-26.55c11.91,-8.54 24.8,-15.29 38.25,-21.23c23.28,-10.28 48.05,-16.26 72.66,-22.69c22.92,-5.99 45.3,-13.22 65.4,-25.68c0.77,-0.48 1.66,-0.87 2.28,-1.49c3.93,-3.96 8.51,-3.63 13.42,-2.14c3.92,1.19 7.9,2.17 11.76,4.23c-0.5,0.61 -0.69,1.05 -1.03,1.23c-17.7,9.51 -34.97,19.8 -54.03,26.85c-16.64,6.15 -33.83,10.39 -51.24,13.95c-23.31,4.77 -46.36,10.38 -67.27,21.86c-6.11,3.35 -12.21,6.77 -16.74,12.11c-2.16,2.54 -3.7,5.25 -1.91,8.79c3.89,-1.06 7.2,-3.03 11.3,-3.42c0.27,-0.02 0.25,-0.03 0.25,-0.03z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m229.85,206.59c7,0.72 13.53,1.94 19.74,4.5c15.36,6.33 21.74,22.48 13.76,35.4c-4.75,7.69 -12.74,10.65 -21.48,11.59c-15.07,1.62 -30.23,0.41 -45.34,0.76c-3.12,0.07 -3.27,-1.76 -3.27,-3.86c-0.01,-8.45 0,-16.9 0,-25.35c0,-6.7 0.09,-13.39 -0.08,-20.08c-0.07,-2.75 1.05,-3.7 3.82,-3.71c10.85,-0.02 21.7,0.09 32.85,0.76z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m282.21,100.35c-15.38,7.15 -30.52,14.23 -46.94,18.36c-12.3,3.09 -24.78,5.08 -37.45,6.3c-24.56,2.37 -49.15,4.7 -72.88,11.77c-3.49,1.04 -6.89,2.38 -10.72,3.72c0.46,-1.7 1.81,-1.96 2.74,-2.58c16.23,-10.84 34.72,-16.69 53.51,-21.95c17.5,-4.91 35.46,-8 53.06,-12.51c20.3,-5.2 39.49,-12.88 57.9,-22.48c9.71,-5.06 19.36,-10.32 30.28,-12.85c2.75,-0.64 5.44,-0.68 8.19,0.11c7.84,2.25 15.04,5.56 21.2,10.8c2.07,1.76 2.04,2.97 -0.61,4.03c-2.13,0.85 -4.24,1.75 -6.29,2.77c-2.3,1.15 -4.22,2.35 -6.31,-0.65c-1.08,-1.55 -3.48,-1.19 -5.5,-0.63c-13.93,3.84 -27.19,9.18 -40.18,15.81z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m303.24,101.85c-12.25,6.44 -24.42,12.47 -37.93,15.78c11.59,-7.31 23.12,-14.65 34.36,-22.68c1.64,2.75 -1.87,3.45 -1.32,5.57c9.97,-2.78 17.58,-10.55 28.22,-11.64c-7.15,5.21 -15.54,8.37 -23.32,12.98z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m372.48,118.37c2.83,-0.1 5.42,-0.73 8.77,-0.08c-3.06,1.8 -5.64,2.71 -8.53,2.47c-2.39,-0.21 -2.29,-1.15 -0.24,-2.38z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m366.29,165.61c2.44,0.09 4.4,-2.02 6.76,-0.38c-4.13,0.53 -7.54,3.68 -12.75,2.84c1.93,-1.77 3.94,-1.86 5.98,-2.46z"/>
|
||||
<path
|
||||
android:fillColor="#000000"
|
||||
android:pathData="m119.8,143.18c2.81,-1.52 5.24,-2.16 8.2,-1.99c-2.16,2.94 -5.15,1.59 -7.9,1.97c-0.31,0 -0.3,0.02 -0.3,0.02z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background"/>
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
|
||||
<monochrome android:drawable="@drawable/ic_launcher_monochrome"/>
|
||||
</adaptive-icon>
|
||||
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 3.4 KiB |
@@ -1,13 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Paperize</string>
|
||||
<string name="import_adding_folder">Adding folder…</string>
|
||||
<string name="import_adding_wallpapers">Adding wallpapers…</string>
|
||||
<string name="import_scanning">Scanning… %1$d found</string>
|
||||
<string name="import_saving">Saving %1$d / %2$d</string>
|
||||
<string name="home">Home</string>
|
||||
<string name="settings_screen">Settings</string>
|
||||
<string name="wallpaper">Wallpaper</string>
|
||||
<string name="library">Library</string>
|
||||
<string name="back">Back</string>
|
||||
<string name="add_images">Add images</string>
|
||||
<string name="add_folder">Add folder</string>
|
||||
<string name="add_folder">Add folder</string>
|
||||
<string name="add_album">Add album</string>
|
||||
<string name="enter_the_name_of_the_album">Enter the name of the album</string>
|
||||
<string name="album_name">Album Name</string>
|
||||
@@ -19,33 +22,17 @@
|
||||
<string name="currently_selected_album">Currently selected album</string>
|
||||
<string name="agree">Agree</string>
|
||||
<string name="welcome">Welcome</string>
|
||||
<string name="notifications">Notifications</string>
|
||||
<string name="continue_button">I\'m In</string>
|
||||
<string name="continue_button">I\'m In</string>
|
||||
<string name="allow">Allow</string>
|
||||
<string name="privacy_policy">Privacy Policy</string>
|
||||
<string name="privacy_screen">Privacy Screen</string>
|
||||
<string name="reset_to_default">Reset to default</string>
|
||||
<string name="reset_all_data">Reset all data</string>
|
||||
<string name="are_you_sure_you_want_to_reset_all_settings_and_data_to_default">Are you sure you want to reset all settings and data to default?</string>
|
||||
<string name="confirm">Confirm</string>
|
||||
<plurals name="minutes" comment="minutes [one] [other]">
|
||||
<item quantity="one">%d minute</item>
|
||||
<item quantity="other">%d minutes</item>
|
||||
</plurals>
|
||||
<plurals name="hours" comment="hours [one] [other]">
|
||||
<item quantity="one">%d hour</item>
|
||||
<item quantity="other">%d hours</item>
|
||||
</plurals>
|
||||
<plurals name="days" comment="days [one] [other]">
|
||||
<item quantity="one">%d day</item>
|
||||
<item quantity="other">%d days</item>
|
||||
</plurals>
|
||||
<string name="selected_count">%1$s selected</string>
|
||||
<string name="selected_count">%1$s selected</string>
|
||||
<string name="please_read_and_agree_to_the_following_privacy_notice_to_use_the_app">Please read and agree to the following privacy notice to use the app.</string>
|
||||
<string name="privacy_notice">Privacy Notice</string>
|
||||
<string name="delete_these">Delete these?</string>
|
||||
<string name="are_you_sure_you_want_to_delete_these_wallpapers">Are you sure you want to delete these wallpapers?</string>
|
||||
<string name="are_you_sure_you_want_to_delete_this">Are you sure you want to delete this?</string>
|
||||
<string name="are_you_sure_you_want_to_delete_this">Are you sure you want to delete this?</string>
|
||||
<string name="delete_album_question">Delete album?</string>
|
||||
<string name="animation">Animation</string>
|
||||
<string name="increase_visual_appeal">Increase visual appeal</string>
|
||||
@@ -56,8 +43,7 @@
|
||||
<string name="click_here_to_view_our_privacy_policy">Click here to view our privacy policy</string>
|
||||
<string name="appearance">Appearance</string>
|
||||
<string name="about">About</string>
|
||||
<string name="wallpapers">wallpapers</string>
|
||||
<plurals name="wallpaper_count" comment="wallpaper_count [one] [other]">
|
||||
<plurals name="wallpaper_count" comment="wallpaper_count [one] [other]">
|
||||
<item quantity="one">%d wallpaper</item>
|
||||
<item quantity="other">%d wallpapers</item>
|
||||
</plurals>
|
||||
@@ -73,8 +59,7 @@
|
||||
<string name="empty_album">Empty Album</string>
|
||||
<string name="empty_album_message">This album has no wallpapers. Please add wallpapers to the album before selecting it.</string>
|
||||
<string name="ok">OK</string>
|
||||
<string name="percentage">%1$s%%</string>
|
||||
<string name="fill">Fill</string>
|
||||
<string name="fill">Fill</string>
|
||||
<string name="fit">Fit</string>
|
||||
<string name="stretch">Stretch</string>
|
||||
<string name="change_brightness">Brightness Effect</string>
|
||||
@@ -84,12 +69,7 @@
|
||||
<string name="show_interval_sliders">Show interval sliders</string>
|
||||
<string name="interval_text">Time Interval</string>
|
||||
<string name="change_blur">Blur Effect</string>
|
||||
<string name="paperize_is_running">Paperize is running</string>
|
||||
<string name="next_wallpaper_change">Next wallpaper change: %1$s</string>
|
||||
<string name="theme">Theme</string>
|
||||
<string name="wallpaper_changer">Wallpaper Changer</string>
|
||||
<string name="enable_wallpaper_changer">Enable Wallpaper Changer</string>
|
||||
<string name="lock">Lock</string>
|
||||
<string name="lock">Lock</string>
|
||||
<string name="change_vignette">Vignette Effect</string>
|
||||
<string name="none">None</string>
|
||||
<string name="gray_filter">Gray Filter</string>
|
||||
@@ -99,8 +79,7 @@
|
||||
<string name="shuffle">Shuffle</string>
|
||||
<string name="days_txt">Days</string>
|
||||
<string name="hours_txt">Hours</string>
|
||||
<string name="minutes_txt">Minutes</string>
|
||||
<string name="change_the_image_brightness">Change the image brightness</string>
|
||||
<string name="change_the_image_brightness">Change the image brightness</string>
|
||||
<string name="add_blur_to_the_image">Add blur to the image</string>
|
||||
<string name="darken_the_edges_of_the_image">Darken the edges of the image</string>
|
||||
<string name="make_the_colors_grayscale">Make the colors grayscale</string>
|
||||
@@ -109,11 +88,10 @@
|
||||
<string name="change_on_screen_off">Change on Screen Off</string>
|
||||
<string name="change_wallpaper_when_screen_turns_off">Change wallpaper when screen turns off</string>
|
||||
<string name="parallax_effect">Parallax Effect</string>
|
||||
<string name="wallpaper_moves_with_screen_scroll">Wallpaper moves with screen scroll</string>
|
||||
<string name="wallpaper_moves_with_screen_scroll">Swipe between home-screen pages to move the wallpaper (launcher support required)</string>
|
||||
<string name="live_wallpaper_name">Paperize Live Wallpaper</string>
|
||||
<string name="live_wallpaper_description">Dynamic wallpapers with effects and interactive features</string>
|
||||
<string name="visual_effects_note_live_mode">Note: Visual effects (blur, darken, vignette, grayscale) apply to all wallpapers in live mode.</string>
|
||||
<string name="adaptive_brightness">Adaptive Brightness</string>
|
||||
<string name="adaptive_brightness">Adaptive Brightness</string>
|
||||
<string name="adjust_brightness_based_on_mode">Adjust brightness based on dark/light mode</string>
|
||||
<string name="randomly_shuffle_the_wallpapers">Randomly shuffle the wallpapers</string>
|
||||
<string name="changing_wallpaper">Changing wallpaper…</string>
|
||||
@@ -124,10 +102,6 @@
|
||||
<string name="notification_permission_description">Allow Paperize to send notifications about wallpaper changes and when the app is running in the background. You can change this anytime in settings.</string>
|
||||
<string name="skip">Skip</string>
|
||||
<string name="permission_granted">Permission Granted</string>
|
||||
<string name="storage_permission_title">Storage Access (Optional)</string>
|
||||
<string name="storage_permission_description">Allow Paperize to access storage to preview your current wallpaper in the app.</string>
|
||||
<string name="storage_permission_optional">This permission is optional. Paperize can still function normally without it, but you won\'t be able to see wallpaper previews.</string>
|
||||
<string name="continue_without_storage">Continue Without Storage Access</string>
|
||||
|
||||
<!-- Content Descriptions for Accessibility -->
|
||||
<string name="content_desc_clear_selection">Clear selection</string>
|
||||
@@ -171,10 +145,8 @@
|
||||
<string name="mins">Mins</string>
|
||||
<string name="total_interval">Total: </string>
|
||||
<string name="time_unit_min">min</string>
|
||||
<string name="time_unit_hour">hour</string>
|
||||
<string name="time_unit_day">day</string>
|
||||
|
||||
<!-- Notification Service -->
|
||||
<!-- Notification Service -->
|
||||
<string name="notification_channel_description">Wallpaper change notifications</string>
|
||||
<string name="no_wallpapers_in_album">No wallpapers in album</string>
|
||||
<string name="wallpaper_changer_disabled_empty_album">Wallpaper changer has been disabled because the album is empty.</string>
|
||||
@@ -182,17 +154,12 @@
|
||||
<!-- Error Messages -->
|
||||
<string name="error_failed_to_build_queue">Failed to build wallpaper queue</string>
|
||||
<string name="error_no_valid_wallpaper_after_retries">Could not find a valid wallpaper after retries</string>
|
||||
<string name="error_failed_to_load_bitmap">Failed to load wallpaper image</string>
|
||||
|
||||
<!-- OEM Compatibility Warnings -->
|
||||
<!-- OEM Compatibility Warnings -->
|
||||
<string name="parallax_may_not_work">Parallax effect may not work with your OEM or launcher.</string>
|
||||
|
||||
<!-- Plurals -->
|
||||
<plurals name="items_count">
|
||||
<item quantity="one">%d item</item>
|
||||
<item quantity="other">%d items</item>
|
||||
</plurals>
|
||||
<plurals name="time_unit_hours">
|
||||
<plurals name="time_unit_hours">
|
||||
<item quantity="one">hour</item>
|
||||
<item quantity="other">hours</item>
|
||||
</plurals>
|
||||
@@ -217,8 +184,7 @@
|
||||
<!-- Live Wallpaper Selection Dialog -->
|
||||
<string name="select_live_wallpaper">Select Live Wallpaper</string>
|
||||
<string name="select_live_wallpaper_instruction">To use Paperize in Live Wallpaper mode, you need to select it as your live wallpaper from the system settings.</string>
|
||||
<string name="open_wallpaper_picker_instruction">\nTap \'Open Wallpaper Picker\' below to select Paperize from the list of available live wallpapers.</string>
|
||||
<string name="open_wallpaper_picker">Open Wallpaper Picker</string>
|
||||
<string name="open_wallpaper_picker">Open Wallpaper Picker</string>
|
||||
<string name="later">Later</string>
|
||||
|
||||
<!-- Settings Mode Switcher -->
|
||||
@@ -240,5 +206,7 @@
|
||||
<string name="ignoring">Ignoring (Recommended)</string>
|
||||
<string name="optimizing">Optimizing (May delay changes)</string>
|
||||
<string name="reliability">Reliability</string>
|
||||
<string name="change_wallpaper_now">Change wallpaper now</string>
|
||||
<string name="change_next_wallpaper_shortcut">Change to the next configured wallpaper</string>
|
||||
|
||||
</resources>
|
||||
@@ -18,4 +18,10 @@
|
||||
<item name="android:windowLightStatusBar">true</item>
|
||||
<item name="android:navigationBarColor">@android:color/transparent</item>
|
||||
</style>
|
||||
|
||||
<!-- Splash Screen Theme -->
|
||||
<style name="Theme.App.Starting" parent="Theme.SplashScreen">
|
||||
<item name="windowSplashScreenAnimatedIcon">@mipmap/ic_launcher</item>
|
||||
<item name="postSplashScreenTheme">@style/Theme.Paperize</item>
|
||||
</style>
|
||||
</resources>
|
||||