Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7cc0454102 | ||
|
|
6bb05ea13b | ||
|
|
e30b51e5e4 | ||
|
|
3fc9facf32 | ||
|
|
dbd80fe3fa | ||
|
|
d1ad40b213 | ||
|
|
2adcf1a318 | ||
|
|
80c70f82ee | ||
|
|
faf40edf30 | ||
|
|
29be20ca10 | ||
|
|
8d3701bc6a | ||
|
|
76cb388199 | ||
|
|
e4b0eab824 | ||
|
|
c9bdce1484 | ||
|
|
db01ecab9c | ||
|
|
229c54258c | ||
|
|
2d6b905c07 | ||
|
|
48562bf01c | ||
|
|
d51e0920d0 | ||
|
|
d2fb14dcd0 | ||
|
|
82e5fbd5e9 | ||
|
|
da506a4df7 | ||
|
|
6b682980b9 | ||
|
|
15769d2fe2 | ||
|
|
dd46dfc9d4 | ||
|
|
06738a4485 | ||
|
|
d0cad6f45c | ||
|
|
49ba1aafaf | ||
|
|
1a2c6eecd1 | ||
|
|
8634a59ee8 | ||
|
|
bc6bc2c405 | ||
|
|
707df3a25d | ||
|
|
e9cd2c388f | ||
|
|
50f6677c95 | ||
|
|
740175fb10 | ||
|
|
d94e1be668 | ||
|
|
6270d1c2be | ||
|
|
073df232f2 | ||
|
|
16f5a1682b | ||
|
|
e7c6c5b850 | ||
|
|
548bc9b32a | ||
|
|
cb6e7b83be | ||
|
|
b506ac179f | ||
|
|
8eb3d501cd | ||
|
|
47aa0a6f25 | ||
|
|
0f988dd1a7 | ||
|
|
39dc628de6 | ||
|
|
12c3d67fc2 | ||
|
|
2be0653c37 | ||
|
|
20f3254016 | ||
|
|
78df576bf8 | ||
|
|
96181409e9 | ||
|
|
36141d0ac7 | ||
|
|
c198f26a86 | ||
|
|
ac6a04b0f4 | ||
|
|
51a67a709d | ||
|
|
007740d626 | ||
|
|
98ada25d02 | ||
|
|
4a7f22bbc6 | ||
|
|
99c79daa0c | ||
|
|
2b9cb6def2 | ||
|
|
9fdd5bb3fd | ||
|
|
7140c970e1 | ||
|
|
f4d6e995b3 | ||
|
|
a5788dac33 | ||
|
|
3cc8a4230d | ||
|
|
2a6db2fad7 | ||
|
|
f8b96084c6 | ||
|
|
1b8505d7e4 | ||
|
|
5902af44c7 | ||
|
|
b9c2ab868f | ||
|
|
a34726a506 | ||
|
|
9a13e3ba09 | ||
|
|
de4442cfe5 | ||
|
|
e58830610a | ||
|
|
a4386df20c | ||
|
|
c36ca574d5 | ||
|
|
bd679b9d79 | ||
|
|
83e69d2503 | ||
|
|
c20f266ecf | ||
|
|
a30504d633 | ||
|
|
91823ba76b | ||
|
|
393cf3f56b | ||
|
|
d42d01ea8c | ||
|
|
bddab1e116 | ||
|
|
b76a941e87 | ||
|
|
65bc22f1eb | ||
|
|
6703329696 | ||
|
|
d1de5f1194 | ||
|
|
2888fd3d7f | ||
|
|
7cabc6ff75 | ||
|
|
641596f58d | ||
|
|
d75a8af634 | ||
|
|
20757e2d1d | ||
|
|
e521f26903 | ||
|
|
185994b962 | ||
|
|
374a078007 | ||
|
|
7fb2843b48 | ||
|
|
8bae038508 | ||
|
|
cef26f42f8 | ||
|
|
063e5dcc28 | ||
|
|
df5985f3d6 | ||
|
|
e4e19faa24 | ||
|
|
e41920b65f | ||
|
|
c21f9d11df | ||
|
|
d2ffa9745b | ||
|
|
d6bd404add | ||
|
|
b3c2264bd3 | ||
|
|
11724d99d3 | ||
|
|
4e05b62d6e | ||
|
|
2044748e20 | ||
|
|
97dc38bbfb | ||
|
|
d169b84430 | ||
|
|
f153eebc71 | ||
|
|
66766c7926 | ||
|
|
3b85cdb822 | ||
|
|
7dc1171678 | ||
|
|
a84bfabbed | ||
|
|
fb1c8a22f2 | ||
|
|
ddc7c8e5ca | ||
|
|
1810f8cc9e | ||
|
|
ca28dcd3ca | ||
|
|
1ba3d10aa7 | ||
|
|
f8fa13d487 | ||
|
|
7e942a2c83 | ||
|
|
80468834fc | ||
|
|
426bfd1763 | ||
|
|
2dc2790eba | ||
|
|
3bd03c87d4 | ||
|
|
d28d343c8f | ||
|
|
fdc9dc2591 | ||
|
|
e00c356ac2 | ||
|
|
174f5b17e6 | ||
|
|
e18f3eceb9 | ||
|
|
22cc66687e | ||
|
|
fc90aeaa78 | ||
|
|
7fb0f8e824 | ||
|
|
3fccae4273 | ||
|
|
65a2f66344 | ||
|
|
93af870235 | ||
|
|
51f4ac310a | ||
|
|
e651cdc248 | ||
|
|
4175b09196 | ||
|
|
1edfcfd837 | ||
|
|
15c9b47131 | ||
|
|
87a69e748f | ||
|
|
3b746ad354 | ||
|
|
797a407f3c | ||
|
|
145899d9a6 | ||
|
|
af72b78a7b | ||
|
|
13367165e6 | ||
|
|
b5f4b52f60 | ||
|
|
434830cfdd | ||
|
|
7c426d5d63 | ||
|
|
d940d9e112 |
No files matched your search
@@ -0,0 +1,3 @@
|
||||
* text=auto eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
@@ -0,0 +1,69 @@
|
||||
name: Paperize Android Debug CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["dev-LFA"]
|
||||
pull_request:
|
||||
branches: ["dev-LFA"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-and-lint:
|
||||
name: Run unit tests and lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out source code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
|
||||
- name: Set up Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Install Android SDK 37
|
||||
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
|
||||
|
||||
- name: Run unit tests and lint
|
||||
run: ./gradlew testDebugUnitTest lintDebug
|
||||
|
||||
build:
|
||||
name: Build debug APK
|
||||
if: github.event_name == 'push'
|
||||
needs: test-and-lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out source code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
|
||||
- name: Set up Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Install Android SDK 37
|
||||
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
|
||||
|
||||
- name: Build debug APK
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Upload debug APK
|
||||
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
|
||||
with:
|
||||
name: paperize-debug-apk
|
||||
path: app/build/outputs/apk/debug/app-debug.apk
|
||||
if-no-files-found: error
|
||||
@@ -0,0 +1,80 @@
|
||||
name: Paperize Android Release CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main-LFA"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test-and-lint:
|
||||
name: Run unit tests and lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out source code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
|
||||
- name: Set up Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Install Android SDK 37
|
||||
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
|
||||
|
||||
- name: Run unit tests and lint
|
||||
run: ./gradlew testDebugUnitTest lintDebug
|
||||
|
||||
build:
|
||||
name: Build release APK
|
||||
needs: test-and-lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out source code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
|
||||
- name: Set up Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
with:
|
||||
packages: platform-tools
|
||||
|
||||
- name: Install Android SDK 37
|
||||
run: sdkmanager --install "platforms;android-37.0" "build-tools;37.0.0"
|
||||
|
||||
- name: Build signed release APK
|
||||
env:
|
||||
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
|
||||
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
||||
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
||||
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
: "${SIGNING_KEYSTORE_BASE64:?Missing SIGNING_KEYSTORE_BASE64 secret}"
|
||||
: "${SIGNING_KEY_ALIAS:?Missing SIGNING_KEY_ALIAS secret}"
|
||||
: "${SIGNING_STORE_PASSWORD:?Missing SIGNING_STORE_PASSWORD secret}"
|
||||
: "${SIGNING_KEY_PASSWORD:?Missing SIGNING_KEY_PASSWORD secret}"
|
||||
export SIGNING_KEYSTORE_PATH="$(mktemp "${RUNNER_TEMP}/paperize-keystore.XXXXXX")"
|
||||
trap 'rm -f "$SIGNING_KEYSTORE_PATH"' EXIT
|
||||
printf '%s' "$SIGNING_KEYSTORE_BASE64" | base64 --decode > "$SIGNING_KEYSTORE_PATH"
|
||||
./gradlew assembleRelease
|
||||
|
||||
- name: Upload release APK
|
||||
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
|
||||
with:
|
||||
name: paperize-release-apk
|
||||
path: app/build/outputs/apk/release/app-release.apk
|
||||
if-no-files-found: error
|
||||
@@ -1,14 +1 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: Anthonyy232
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -1,32 +0,0 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: "[Bug] <BUG_NAME>"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Smartphone (please complete the following information):**
|
||||
- Device: [e.g. Pixel 32 Pro]
|
||||
- OS: [e.g. OneUI 21]
|
||||
- Version [e.g. v2.1.0]
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here.
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Bug report
|
||||
description: Something in Paperize doesn't work as it should
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: textarea
|
||||
id: what
|
||||
attributes:
|
||||
label: What happened
|
||||
description: What you did, what you expected and what you got. Screenshots help.
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Paperize version
|
||||
placeholder: 4.2.2 from F-Droid
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: device
|
||||
attributes:
|
||||
label: Device and Android version
|
||||
placeholder: Pixel 9, Android 16
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: mode
|
||||
attributes:
|
||||
label: Wallpaper mode
|
||||
options:
|
||||
- Static
|
||||
- Live
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
@@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Feature idea
|
||||
url: https://github.com/Anthonyy232/Paperize/discussions/categories/ideas
|
||||
about: Suggest a feature or improvement in Discussions
|
||||
- name: Question
|
||||
url: https://github.com/Anthonyy232/Paperize/discussions/categories/q-a
|
||||
about: Ask how something works
|
||||
@@ -1,20 +0,0 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: "[Feature request] <FEATURE_NAME>"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,39 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: gradle
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
cooldown:
|
||||
default-days: 5
|
||||
groups:
|
||||
# F-Droid rebuilds each release and compares it with ours: toolchain updates are merged by hand
|
||||
toolchain:
|
||||
patterns:
|
||||
- gradle-wrapper
|
||||
- com.android.application*
|
||||
- com.android.tools.build*
|
||||
- org.jetbrains.kotlin*
|
||||
- com.google.devtools.ksp*
|
||||
# "*" ranks below toolchain's patterns; without patterns these groups would outrank it
|
||||
minor-patch:
|
||||
patterns: ["*"]
|
||||
update-types: [minor, patch]
|
||||
major:
|
||||
patterns: ["*"]
|
||||
update-types: [major]
|
||||
commit-message:
|
||||
prefix: chore(deps)
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: monthly
|
||||
cooldown:
|
||||
default-days: 5
|
||||
groups:
|
||||
minor-patch:
|
||||
update-types: [minor, patch]
|
||||
major:
|
||||
update-types: [major]
|
||||
commit-message:
|
||||
prefix: chore(deps)
|
||||
@@ -0,0 +1,7 @@
|
||||
## What
|
||||
|
||||
## Why
|
||||
|
||||
## Checked
|
||||
|
||||
<!-- e.g. ./gradlew testDebugUnitTest lintDebug, and what you saw on a device or emulator -->
|
||||
|
After Width: | Height: | Size: 249 KiB |
|
After Width: | Height: | Size: 234 KiB |
|
After Width: | Height: | Size: 234 KiB |
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 263 KiB |
|
After Width: | Height: | Size: 253 KiB |
|
After Width: | Height: | Size: 272 KiB |
|
After Width: | Height: | Size: 237 KiB |
@@ -0,0 +1,110 @@
|
||||
name: Paperize CI/CD Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
tags: [ 'v*' ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Run Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Run unit tests and lint
|
||||
run: ./gradlew testDebugUnitTest lintDebug
|
||||
|
||||
build:
|
||||
name: Build Signed APK
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
if: github.event_name == 'push'
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Decode Base64 Keystore
|
||||
env:
|
||||
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
echo $SIGNING_KEYSTORE_BASE64 | base64 --decode > ${{ github.workspace }}/keystore.jks
|
||||
|
||||
- name: Build Release APK
|
||||
env:
|
||||
SIGNING_KEYSTORE_PATH: ${{ github.workspace }}/keystore.jks
|
||||
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
||||
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
||||
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Get Version Name
|
||||
id: get_version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ $GITHUB_REF == refs/tags/v* ]]; then
|
||||
VERSION_NAME=${GITHUB_REF_NAME}
|
||||
else
|
||||
RAW_VERSION=$(grep "versionName =" app/build.gradle.kts | awk -F'"' '{print $2}')
|
||||
VERSION_NAME="v${RAW_VERSION}"
|
||||
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
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
|
||||
with:
|
||||
name: paperize-${{ steps.get_version.outputs.VERSION_NAME }}
|
||||
path: app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
name: Create GitHub Release
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Download signed APK artifact
|
||||
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8
|
||||
with:
|
||||
pattern: paperize-v*
|
||||
path: ./apk-artifact
|
||||
merge-multiple: true
|
||||
|
||||
- name: Create Draft Release
|
||||
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3
|
||||
with:
|
||||
files: ./apk-artifact/paperize-v*.apk
|
||||
draft: true
|
||||
@@ -0,0 +1,60 @@
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
schedule:
|
||||
- cron: "24 6 * * 3"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
analyze-actions:
|
||||
name: Analyze GitHub Actions
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
|
||||
with:
|
||||
languages: actions
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
|
||||
|
||||
analyze-java-kotlin:
|
||||
name: Analyze Java and Kotlin
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6
|
||||
with:
|
||||
java-version: "17"
|
||||
distribution: temurin
|
||||
cache: gradle
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
|
||||
with:
|
||||
languages: java-kotlin
|
||||
build-mode: manual
|
||||
|
||||
- name: Build application for analysis
|
||||
run: ./gradlew assembleDebug
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
|
||||
@@ -0,0 +1,107 @@
|
||||
name: Crowdin Sync
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
paths:
|
||||
- app/src/main/res/values/strings.xml
|
||||
- crowdin.yml
|
||||
- .github/workflows/crowdin.yml
|
||||
schedule:
|
||||
- cron: "0 8 * * 1"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
upload_translations:
|
||||
description: Send the translations in the repository to Crowdin as approved first
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
concurrency:
|
||||
group: crowdin-sync
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
BRANCH: crowdin-translations
|
||||
|
||||
jobs:
|
||||
synchronize-with-crowdin:
|
||||
name: Synchronize with Crowdin
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Upload sources and download approved translations
|
||||
uses: crowdin/github-action@d651c77756acbe11a31d77a6fb79d8a239e1e05a # v3
|
||||
with:
|
||||
crowdin_branch_name: main
|
||||
upload_sources: true
|
||||
upload_translations: ${{ inputs.upload_translations || false }}
|
||||
auto_approve_imported: true
|
||||
download_translations: false
|
||||
download_bundle: 15
|
||||
push_translations: false
|
||||
create_pull_request: false
|
||||
env:
|
||||
CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID }}
|
||||
CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_PERSONAL_TOKEN }}
|
||||
|
||||
# Keeps every string the repository already ships, drops strings English no longer has,
|
||||
# and only adds a new locale once it covers 90% of the English strings.
|
||||
- name: Merge into the shipped translations
|
||||
shell: python
|
||||
run: |
|
||||
import os, re, shutil, subprocess
|
||||
from pathlib import Path
|
||||
|
||||
res = Path("app/src/main/res")
|
||||
entry = re.compile(r'<(string|plurals|string-array)\b[^>]*?\bname="([^"]+)"[^>]*>.*?</\1>', re.S)
|
||||
|
||||
# Crowdin adds the string's context as a comment attribute.
|
||||
def entries(text):
|
||||
return {m.group(2): re.sub(r' comment="[^"]*"', "", m.group(0), count=1) for m in entry.finditer(text)}
|
||||
|
||||
def shipped(path):
|
||||
out = subprocess.run(["git", "show", f"HEAD:{path.as_posix()}"], capture_output=True, text=True)
|
||||
return out.stdout if out.returncode == 0 else None
|
||||
|
||||
subprocess.run(["sudo", "chown", "-R", str(os.getuid()), str(res)], check=True)
|
||||
source = [k for k, v in entries((res / "values/strings.xml").read_text("utf-8")).items()
|
||||
if 'translatable="false"' not in v.split(">", 1)[0]]
|
||||
for path in sorted(res.glob("values-*/strings.xml")):
|
||||
old_text = shipped(path)
|
||||
new, old = entries(path.read_text("utf-8")), entries(old_text or "")
|
||||
merged = [new.get(k) or old[k] for k in source if k in new or k in old]
|
||||
if old_text is None and len(merged) < 0.9 * len(source):
|
||||
shutil.rmtree(path.parent)
|
||||
continue
|
||||
if merged == [old[k] for k in source if k in old]:
|
||||
subprocess.run(["git", "checkout", "--", str(path)], check=True)
|
||||
continue
|
||||
body = "".join(f" {e}\n" for e in merged)
|
||||
path.write_text(f'<?xml version="1.0" encoding="utf-8"?>\n<resources>\n{body}</resources>\n', "utf-8")
|
||||
|
||||
# Pull requests opened with GITHUB_TOKEN start no workflows, so the checks are dispatched.
|
||||
- name: Open the translations pull request
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
if [ -z "$(git status --porcelain app/src/main/res)" ]; then
|
||||
echo "No translation changes"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git switch -C "$BRANCH"
|
||||
git add app/src/main/res
|
||||
git commit -m "chore: update translations"
|
||||
git push --force origin "$BRANCH"
|
||||
if [ -z "$(gh pr list --head "$BRANCH" --state open --json number --jq '.[].number')" ]; then
|
||||
gh pr create --base master --head "$BRANCH" --title "chore: update translations" \
|
||||
--body "Approved translations from [Crowdin](https://crowdin.com/project/paperize)."
|
||||
fi
|
||||
gh workflow run android-release.yml --ref "$BRANCH"
|
||||
@@ -0,0 +1,21 @@
|
||||
name: Dependabot auto-merge
|
||||
|
||||
on: pull_request
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
auto-merge:
|
||||
if: github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- id: meta
|
||||
uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3
|
||||
# Waits for the ruleset's required checks
|
||||
- if: steps.meta.outputs.dependency-group == 'minor-patch' && contains(fromJSON('["version-update:semver-minor", "version-update:semver-patch"]'), steps.meta.outputs.update-type)
|
||||
run: gh pr merge --auto --squash "$PR_URL"
|
||||
env:
|
||||
PR_URL: ${{ github.event.pull_request.html_url }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
paths:
|
||||
- "site/**"
|
||||
- ".github/workflows/pages.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy site
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- name: Upload site
|
||||
uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5
|
||||
with:
|
||||
path: site
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5
|
||||
@@ -1,159 +0,0 @@
|
||||
# ===================================================================
|
||||
# Paperize CI/CD Pipeline
|
||||
#
|
||||
# Automates the testing, building and release process for the Paperize Android application.
|
||||
#
|
||||
# Workflow Architecture:
|
||||
# 1. Test: Runs unit tests to ensure code quality.
|
||||
# 2. Build: Compiles and signs the release APK (depends on test passing).
|
||||
# 3. Release: Publishes the APK to a draft GitHub Release, but only for version tags.
|
||||
#
|
||||
# Triggering Conditions:
|
||||
# - On push to `master`:
|
||||
# - Executes the `test` and `build` jobs.
|
||||
# - Produces a versioned build artifact for testing and internal distribution.
|
||||
# - On push of a tag (e.g., `v1.2.3`):
|
||||
# - Executes all jobs: `test`, `build` and `release`.
|
||||
# - Creates a formal, versioned draft release on GitHub with the signed APK attached.
|
||||
# - On pull requests to `master`:
|
||||
# - Executes only the `test` job to validate changes before merge.
|
||||
# ===================================================================
|
||||
name: Paperize CI/CD Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
tags: [ 'v*' ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
# ===================================================================
|
||||
# JOB: test
|
||||
#
|
||||
# Runs unit tests to ensure code quality before building.
|
||||
# ===================================================================
|
||||
test:
|
||||
name: Run Unit Tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Run unit tests
|
||||
run: ./gradlew clean test
|
||||
|
||||
# ===================================================================
|
||||
# JOB: build
|
||||
#
|
||||
# Compiles, signs, and packages the release APK. This job produces a
|
||||
# versioned artifact that is used for both internal testing and the final release.
|
||||
# Only runs after tests pass.
|
||||
# ===================================================================
|
||||
build:
|
||||
name: Build Signed APK
|
||||
runs-on: ubuntu-latest
|
||||
needs: test
|
||||
if: github.event_name == 'push'
|
||||
steps:
|
||||
- name: Checkout repository source code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up JDK 17
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
distribution: 'temurin'
|
||||
cache: gradle
|
||||
|
||||
- name: Grant execute permission for gradlew
|
||||
# The gradlew wrapper requires execute permissions to run on the Linux-based runner.
|
||||
run: chmod +x gradlew
|
||||
|
||||
- name: Decode Base64 Keystore
|
||||
# Reconstructs the binary .jks keystore file from the Base64 encoded secret.
|
||||
env:
|
||||
SIGNING_KEYSTORE_BASE64: ${{ secrets.SIGNING_KEYSTORE_BASE64 }}
|
||||
run: |
|
||||
echo $SIGNING_KEYSTORE_BASE64 | base64 --decode > ${{ github.workspace }}/keystore.jks
|
||||
|
||||
- name: Build Release APK
|
||||
env:
|
||||
SIGNING_KEYSTORE_PATH: ${{ github.workspace }}/keystore.jks
|
||||
SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
|
||||
SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
|
||||
SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
|
||||
run: ./gradlew assembleRelease
|
||||
|
||||
- name: Get Version Name
|
||||
# Determines the application version for artifact naming.
|
||||
# - For tag pushes (e.g., 'v1.2.3'), it uses the tag name directly.
|
||||
# - For master branch pushes, it parses the `versionName` from the app's build.gradle.kts file.
|
||||
id: get_version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ $GITHUB_REF == refs/tags/v* ]]; then
|
||||
VERSION_NAME=${GITHUB_REF_NAME}
|
||||
else
|
||||
RAW_VERSION=$(grep "versionName =" app/build.gradle.kts | awk -F'"' '{print $2}')
|
||||
VERSION_NAME="v${RAW_VERSION}"
|
||||
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
|
||||
with:
|
||||
name: paperize-${{ steps.get_version.outputs.VERSION_NAME }}
|
||||
path: app/build/outputs/apk/release/paperize-${{ steps.get_version.outputs.VERSION_NAME }}.apk
|
||||
if-no-files-found: error
|
||||
|
||||
# ===================================================================
|
||||
# JOB: release
|
||||
#
|
||||
# Creates a draft GitHub Release and attaches the signed APK. This job is
|
||||
# conditional and will only execute for pushes that include a version tag.
|
||||
# ===================================================================
|
||||
release:
|
||||
name: Create GitHub Release
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- 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
|
||||
with:
|
||||
pattern: paperize-v*
|
||||
path: ./apk-artifact
|
||||
merge-multiple: true
|
||||
|
||||
- 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@v3
|
||||
with:
|
||||
files: ./apk-artifact/paperize-v*.apk
|
||||
draft: true
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -16,6 +16,6 @@
|
||||
local.properties
|
||||
/app/build
|
||||
/app/release
|
||||
/app/schemas
|
||||
.kotlin
|
||||
/.kotlin/sessions
|
||||
/.kotlin/sessions
|
||||
*.jks
|
||||
@@ -0,0 +1,81 @@
|
||||
# Working on Paperize
|
||||
|
||||
An Android app that changes the home and lock screen wallpaper on a schedule: Kotlin, Jetpack Compose, Material 3, Hilt, Room. Users get it from GitHub releases, F-Droid and IzzyOnDroid.
|
||||
|
||||
## Code
|
||||
|
||||
- Simple and direct. No speculative abstractions, options or extension points.
|
||||
- Stay in scope; suggest extras instead of adding them.
|
||||
- Use what the platform, framework, dependencies and this repo already provide before writing a helper.
|
||||
- Validate only at real boundaries (user input, storage, network, other processes). No checks, fallbacks or try/catch for cases that can't happen.
|
||||
- One source of truth for each value or rule.
|
||||
- Delete dead code you find or create.
|
||||
- Match the surrounding code.
|
||||
- Fix root causes, and fix the same pattern everywhere it occurs.
|
||||
|
||||
## Comments
|
||||
|
||||
- Only where the reason isn't clear from the code: a quirk, a race, a non-obvious decision.
|
||||
- Short fragments, not sentences. Never restate code, narrate, or label sections.
|
||||
- Delete comments that no longer match.
|
||||
|
||||
## Tests
|
||||
|
||||
- Behaviour and the edges that can break. No trivial, duplicate, obvious or low-signal tests.
|
||||
- A regression test fails without its fix.
|
||||
- Deterministic: fake time and observable events, no sleeps.
|
||||
- A failing test is a bug until shown otherwise.
|
||||
|
||||
## Paperize
|
||||
|
||||
- The UI can only be seen on an emulator or device. Run `./gradlew connectedDebugAndroidTest` there for anything touching rendering, scheduling, storage or imports.
|
||||
- Dynamic colour swaps the brand palette for the system one, so a design must work with it on and off.
|
||||
- English is the source language. Translations come through Crowdin: the sync workflow uploads `values/strings.xml` and opens its own pull request with approved translations only, adding a locale once most of it is approved. Add or reword strings in English only, and remove deleted strings from every locale. A locale file fixed by hand must also be sent to Crowdin with the sync workflow's upload option, or a later sync can replace the fix.
|
||||
- A database schema change needs a migration that keeps user data, never a destructive fallback. Commit the exported schema.
|
||||
- `metadata/en-US` is the F-Droid and IzzyOnDroid store listing: keep its text and screenshots true to the app.
|
||||
- F-Droid rebuilds every release from source and compares it with the GitHub APK, so the build must stay reproducible. Its recipe deletes the `foojay` line from `settings.gradle.kts` with `sed`: keep that plugin on one line, and keep `dependenciesInfo` off.
|
||||
- F-Droid pins the commit of every version: never rewrite a released commit or move a tag. `crowdin-translations` and `media` are live branches, not stale ones.
|
||||
- `app/lint-baseline.xml` holds only deliberate exceptions; fix new warnings instead of adding them to it.
|
||||
|
||||
## Done means
|
||||
|
||||
- Diff reviewed against this file.
|
||||
- `./gradlew testDebugUnitTest lintDebug` passes with zero warnings.
|
||||
- UI changes seen in the running app, light and dark. Docs and metadata changes need no end-to-end run.
|
||||
- README updated for anything users will notice; behaviour changes called out.
|
||||
|
||||
## Docs
|
||||
|
||||
- README is for users: what it does, how to get it, how to use it. No internals, no agent instructions.
|
||||
- This file is for agents: only what can't be found quickly in the code.
|
||||
- No meta docs in the repo (notes, audits, plans, reports).
|
||||
- Generated images are built from the orphan `media` branch; its README has the steps.
|
||||
|
||||
## Git
|
||||
|
||||
- `type: summary` or `type(scope): summary`: lowercase, imperative, no full stop, about 70 characters at most. Types: `feat` `fix` `refactor` `perf` `test` `docs` `style` `build` `ci` `chore`.
|
||||
- Body only to say why. `Fixes #123` closes an issue.
|
||||
- One logical change per commit. Squash fix-ups before merging.
|
||||
- Branch off `master`. A single commit fast-forwards; several merge with `merge: <summary>`.
|
||||
- No AI attribution in commits, branches, PRs or releases.
|
||||
- One maintainer: amending and force-pushing to tidy history is fine. Keep contributors as authors. Delete stale branches.
|
||||
|
||||
## Pull requests
|
||||
|
||||
- Title in commit format. Body: what changed, why, how it was checked. Short.
|
||||
|
||||
## Releases
|
||||
|
||||
- Bump commit `chore: release vX.Y.Z`; tag `vX.Y.Z`.
|
||||
- A pushed `v*` tag is the store submission: F-Droid builds it straight away and compares the result with the release APK. CI attaches the signed APK to the tag's draft release (reusing a draft that already has notes), but a draft's APK isn't public: publish the draft as soon as CI has attached it, or the F-Droid comparison fails. Never rename a tag or asset.
|
||||
- Title `Paperize X.Y.Z`.
|
||||
- Notes: banner image first, then `### New`, `### Improved`, `### Fixed` (only those that apply). One line per change, written for users; no internals, dependency lists or test counts. End with the install links (APK, F-Droid, IzzyOnDroid) and the full changelog link.
|
||||
- Banner: built and hosted on the `media` branch; reference its raw URL.
|
||||
- The site in `site/` hosts the privacy policy the store listing links to at `#privacy`; keep that anchor.
|
||||
|
||||
## Agents
|
||||
|
||||
- Pushing, amending and force-pushing are allowed. Ask before publishing a release or submitting to a store.
|
||||
- Leave changes you didn't make alone. Clean up scratch files, processes and emulators.
|
||||
- Say what was checked and how, and what wasn't.
|
||||
- Short replies; one recommendation, not a list of options.
|
||||
@@ -1,44 +0,0 @@
|
||||
# Changelog
|
||||
|
||||
## 4.0.0
|
||||
|
||||
Paperize 4 is a ground-up Android 12+ rewrite focused on reliable local wallpaper
|
||||
rotation, a modern Compose interface, and a hardware-accelerated live wallpaper mode.
|
||||
|
||||
### Highlights
|
||||
|
||||
- Added static and live wallpaper modes with independent home/lock configuration.
|
||||
- Added scaling, blur, darken, vignette, grayscale, adaptive brightness, parallax,
|
||||
double-tap, shuffle, and interval controls.
|
||||
- Added an in-app **Change wallpaper now** action and Quick Settings support.
|
||||
- Added current-wallpaper previews that do not require restricted wallpaper access.
|
||||
- Removed the obsolete all-files storage permission; selected images and folders use
|
||||
Android's scoped document access.
|
||||
- Added live progress while importing folders or individual wallpapers.
|
||||
- Reworked folder scanning around the Storage Access Framework and refreshes linked
|
||||
folders whenever Paperize starts.
|
||||
|
||||
### Fixes and reliability
|
||||
|
||||
- Sets matching home and lock wallpapers atomically when their presentation settings
|
||||
match, preventing one screen from diverging or reverting to the system default.
|
||||
- Renders against the largest built-in panel on foldables, even when changed while
|
||||
the device is folded.
|
||||
- Correctly handles EXIF-rotated images without applying orientation twice.
|
||||
- Preserves distinct FIT, FILL, STRETCH, and NONE behavior on scrolling launchers.
|
||||
- Reduces bitmap memory pressure and fixes several bitmap, texture, queue, scheduling,
|
||||
and transient-storage failure paths.
|
||||
- Speeds up large folder imports and queue/album refresh operations.
|
||||
- Repairs the release workflow so signed APKs are published with a versioned filename.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Updated the stable Jetpack Compose platform, Navigation, Kotlin serialization, and
|
||||
reorderable components.
|
||||
- Updated the GitHub release action and made Renovate updates safer and less noisy.
|
||||
|
||||
### Upgrade note
|
||||
|
||||
Upgrading from Paperize 3 performs a one-time local database/settings reset because
|
||||
Paperize 4 uses a new storage model. Albums and schedules must be configured again.
|
||||
Users of the 4.0.0 alpha have already completed this migration and are not reset again.
|
||||
@@ -1,116 +1,105 @@
|
||||
<div align="center">
|
||||
<img style="display: block" src="https://github.com/user-attachments/assets/e8fb14f5-ec8e-440e-a2ac-8065322b0e28" alt="">
|
||||
<h1>Paperize</h1>
|
||||
<p><strong>A dynamic wallpaper changer that keeps your device's aesthetic fresh and exciting</strong></p>
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/hero-dark.png">
|
||||
<img src=".github/readme/hero-light.png" alt="Paperize: a fresh wallpaper, right on time. Three phones show the wallpaper tab, the album library and the effects.">
|
||||
</picture>
|
||||
|
||||
[](https://github.com/Anthonyy232/Paperize/releases)
|
||||
[](https://github.com/Anthonyy232/Paperize/releases/latest)
|
||||
[](LICENSE)
|
||||
[](https://f-droid.org/en/packages/com.anthonyla.paperize/)
|
||||
|
||||
[](https://crowdin.com/project/paperize)
|
||||
</div>
|
||||
<p align="center">
|
||||
<a href="https://github.com/Anthonyy232/Paperize/releases/latest"><b>Download the APK</b></a>
|
||||
·
|
||||
<a href="https://f-droid.org/en/packages/com.anthonyla.paperize/"><b>F-Droid</b></a>
|
||||
·
|
||||
<a href="https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize"><b>IzzyOnDroid</b></a>
|
||||
·
|
||||
<a href="https://anthonyy232.github.io/Paperize/"><b>Website</b></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
Paperize is an Android app that changes your home and lock screen wallpaper on a schedule, from albums you build out of your own images and folders. It works offline, has no internet permission, and needs Android 12 or newer.
|
||||
|
||||
## Features
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-albums-dark.png">
|
||||
<img src=".github/readme/feature-albums-light.png" alt="01. Albums, on rotation. The library with two albums, and an album open showing its wallpapers.">
|
||||
</picture>
|
||||
|
||||
- **Dynamic Wallpaper Changer** — Set your wallpaper to change at specific time intervals
|
||||
- **Static & Live Wallpapers** — Choose between traditional static wallpapers or smooth live wallpaper transitions
|
||||
- **Multiple Image Formats** — Supports JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF, TIFF, and SVG
|
||||
- **Folder Support** — Organize wallpapers into folders for auto-updating
|
||||
- **Dual Screen Support** — Choose the same or separate albums for home and lock screen
|
||||
- **Wallpaper Effects** — Apply various effects including brightness, blur, scaling, vignette, and more
|
||||
- **On-Device Storage** — All wallpapers and settings stored locally on your device
|
||||
An album holds single images, whole folders, or both. Paperize rescans folders each time you open the app, and every hour while a schedule is running, so new files join the rotation and deleted ones leave it by themselves; **Refresh folder** rescans one straight away. Open an album's options menu to rename or delete it, filter it (encrypted albums), or rescan all its folders. Removing something from an album never touches the file on your device.
|
||||
|
||||
---
|
||||
When creating an album, you can mark it encrypted; this choice is permanent and imports only `.jpg_enc` files made by wallpaper_changer. Set the same passphrase in **Settings → Encrypted albums**. **Filter wallpapers** in the album menu takes a regular expression matched (ignoring case) against each line of the folder's `naming_table.enc` (`name;encrypted file;hash`), as wallpaper_changer does; every image is imported but only matching ones are picked as wallpaper, and images in folders without a naming table never match. It is protected by Android Keystore and remains available for scheduled changes. Encrypted previews are off by default; enabling them decrypts images in memory without caching them to disk. Turning previews off removes them from the app's display. Android may still retain the applied wallpaper, and wallpaper_changer's encryption format does not authenticate its contents.
|
||||
|
||||
## Download
|
||||
Supported formats: JPG, PNG, WEBP, AVIF, HEIC/HEIF, BMP, GIF and TIFF.
|
||||
|
||||
[<img src="https://github.com/Anthonyy232/Paperize/assets/60626873/1c034414-21cd-4a0a-838d-89fe7bd56910" alt="Download from GitHub" height="60">](https://github.com/Anthonyy232/Paperize/releases)
|
||||
[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="60">](https://f-droid.org/en/packages/com.anthonyla.paperize/)
|
||||
[<img src="https://gitlab.com/IzzyOnDroid/repo/-/raw/master/assets/IzzyOnDroid.png" alt="Get it on IzzyOnDroid" height="60">](https://apt.izzysoft.de/fdroid/index/apk/com.anthonyla.paperize)
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-schedule-dark.png">
|
||||
<img src=".github/readme/feature-schedule-light.png" alt="02. Home and lock, your call. The wallpaper tab with the current lock and home wallpapers, an album for each, and the time interval.">
|
||||
</picture>
|
||||
|
||||
---
|
||||
Turn on **Lock**, **Home** or both and pick an album for each. One interval covers both screens, from 15 minutes to 30 days; **Individual Scheduling** gives each screen its own. Wallpapers go in order unless **Shuffle** is on. Tired of the one on screen? Tap the bin under it in **Current Wallpapers** to take it out of its album and move on to the next. An image removed from a folder stays out when the folder is rescanned, and tapping it under **Removed** in that folder puts it back.
|
||||
|
||||
## Localization
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset=".github/readme/feature-effects-dark.png">
|
||||
<img src=".github/readme/feature-effects-light.png" alt="03. Effects, to taste. Brightness, blur and vignette, each with a switch for home and lock and a strength slider.">
|
||||
</picture>
|
||||
|
||||
Help translate Paperize into your language! Currently, most translations are provided using machine translation — contributions from native speakers are greatly appreciated.
|
||||
Brightness, blur, vignette and a gray filter each have a strength slider and separate switches for home and lock. **Adaptive Brightness** adjusts the wallpaper to the system's light or dark mode. Scaling is Fill, Fit, Stretch or None. **Blurred background** fills the space around a Fit wallpaper with a blurred copy of it instead of black, and **Horizontal scrolling** lets a wide Fill wallpaper move between home-screen pages.
|
||||
|
||||
**[Contribute on Crowdin →](https://crowdin.com/project/paperize/invite?h=d8d7a7513d2beb0c96ba9b2a5f85473e2084922)**
|
||||
## How it works
|
||||
|
||||
---
|
||||
1. On first launch, choose **Static Mode** or **Live Wallpaper Mode**.
|
||||
2. In **Library**, tap **+** to create an album, then add images or a folder to it.
|
||||
3. In **Wallpaper**, choose the screens and their albums, and set the time interval.
|
||||
4. Leave the rest to Paperize. **Wallpaper changing** pauses and resumes the schedule without clearing your albums.
|
||||
|
||||
## Tech Stack
|
||||
To skip ahead, use **Change wallpaper now** in the app, the Quick Settings tile, or the shortcut you get by long-pressing the app icon. In static mode you can also open any image in an album and set it as the wallpaper yourself. Tick **Continue rotation from here** to have the rotation carry on from that image; it is off by default and hidden while **Shuffle** is on.
|
||||
|
||||
| Category | Technology |
|
||||
|----------|------------|
|
||||
| **Language** | [Kotlin](https://kotlinlang.org/) |
|
||||
| **UI Framework** | [Jetpack Compose](https://developer.android.com/develop/ui/compose) |
|
||||
| **Design System** | [Material 3](https://m3.material.io/) |
|
||||
| **Dependency Injection** | [Dagger Hilt](https://dagger.dev/hilt/) |
|
||||
| **Database** | [Room](https://developer.android.com/training/data-storage/room) |
|
||||
| **Image Loading** | [Coil](https://coil-kt.github.io/coil/) |
|
||||
| **Animations** | [Lottie](https://github.com/airbnb/lottie) |
|
||||
## Static and live modes
|
||||
|
||||
<details>
|
||||
<summary><b>View all dependencies</b></summary>
|
||||
**Static mode** sets ordinary wallpapers through the system, which is simple and light on the battery.
|
||||
|
||||
- [Zoomable](https://github.com/usuiat/Zoomable) — Zoomable and pannable views
|
||||
- [DocumentFileCompat](https://github.com/ItzNotABug/DocumentFileCompat) — Efficient DocumentFile wrapper
|
||||
- [LazyColumnScrollbar](https://github.com/nanihadesuka/LazyColumnScrollbar) — Compose scrollbar library
|
||||
- [compose-collapsing-toolbar](https://github.com/onebone/compose-collapsing-toolbar) — Collapsing toolbar for Compose
|
||||
**Live wallpaper mode** runs Paperize as a live wallpaper showing one album on both screens, and adds:
|
||||
|
||||
</details>
|
||||
- a crossfade between wallpapers
|
||||
- **Double-Tap to Change**
|
||||
- **Change on Screen Off**
|
||||
- **Parallax Effect**, which moves the wallpaper as you swipe between home-screen pages (your launcher has to support it)
|
||||
- intervals down to 1 minute; intervals under 15 minutes only run while the wallpaper is visible
|
||||
|
||||
---
|
||||
Switching modes in Settings resets your albums, wallpapers and settings.
|
||||
|
||||
## Building from Source
|
||||
## Settings
|
||||
|
||||
### Prerequisites
|
||||
- **Wallpaper Mode**: switch between static and live.
|
||||
- **Dark Mode**, **Dynamic Theming** (Material You colours from your system) and **Animation**.
|
||||
- **Battery Optimization**: Android may delay scheduled changes for apps it optimizes. Exempting Paperize keeps them on time.
|
||||
- **Reset all data**: clears every album and setting.
|
||||
|
||||
| Requirement | Version |
|
||||
|-------------|---------|
|
||||
| Java | 17 |
|
||||
| Android Gradle Plugin | 9.1.0 |
|
||||
| Gradle | 9.4.1 |
|
||||
| Minimum SDK | 31 (Android 12) |
|
||||
| Target SDK | 36 |
|
||||
## Privacy
|
||||
|
||||
### Build Steps
|
||||
Albums and settings stay on your device, and Paperize has no internet permission. Read the [privacy policy](https://anthonyy232.github.io/Paperize/#privacy).
|
||||
|
||||
1. **Clone the repository**
|
||||
```bash
|
||||
git clone https://github.com/Anthonyy232/Paperize.git
|
||||
cd Paperize
|
||||
```
|
||||
## Translations
|
||||
|
||||
2. **Open in Android Studio**
|
||||
- Launch Android Studio
|
||||
- Select `File > Open` and navigate to the cloned repository
|
||||
Paperize ships in more than 35 languages. To add or improve a language, translate it on [Crowdin](https://crowdin.com/project/paperize). Translations are reviewed there before they reach the app, and a new language is added once 90% of it has been reviewed.
|
||||
|
||||
3. **Build and Run**
|
||||
- Click `▶ Run` to build and install on a connected device, or
|
||||
- Select `Build > Generate Signed Bundle / APK` to create a signed release
|
||||
## Building from source
|
||||
|
||||
---
|
||||
You need Java 17 and the Android SDK (`ANDROID_HOME`, or `sdk.dir` in `local.properties`). Paperize compiles against SDK 37 and runs on Android 12 (SDK 31) and newer.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Anthonyy232/Paperize.git
|
||||
cd Paperize
|
||||
./gradlew assembleDebug
|
||||
```
|
||||
|
||||
The APK lands in `app/build/outputs/apk/debug`. Or open the folder in Android Studio and press Run.
|
||||
|
||||
For the development setup with an emulator on `lucas@quiethost`, `./build_and_install.sh` builds locally, installs the debug app and test APK remotely, copies test images, and runs the tests. The Android tests can cancel wallpaper schedules in the installed app.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are welcome! Feel free to:
|
||||
Contributions are welcome. Report bugs in [issues](https://github.com/Anthonyy232/Paperize/issues), suggest features in [Discussions](https://github.com/Anthonyy232/Paperize/discussions), and read [AGENTS.md](AGENTS.md) before opening a pull request.
|
||||
|
||||
- Report bugs by opening an issue
|
||||
- Suggest features or improvements
|
||||
- Submit pull requests
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
If you find Paperize useful, consider supporting development through [GitHub Sponsors](https://github.com/sponsors/Anthonyy232) (one-time or monthly). Thank you!
|
||||
|
||||
---
|
||||
If Paperize is useful to you, you can support it through [GitHub Sponsors](https://github.com/sponsors/Anthonyy232).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the **GNU General Public License v3.0** — see the [LICENSE](LICENSE) file for details.
|
||||
Copyright (c) 2023-2026 Anthony La.
|
||||
|
||||
Paperize is free software, licensed under the [GNU General Public License v3.0](LICENSE) only, and comes with no warranty.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Security
|
||||
|
||||
Please report vulnerabilities privately through the repository's [Report a vulnerability](https://github.com/Anthonyy232/Paperize/security/advisories/new) form on GitHub, not in a public issue.
|
||||
@@ -14,7 +14,9 @@ ksp {
|
||||
|
||||
android {
|
||||
namespace = "com.anthonyla.paperize"
|
||||
compileSdk = 36
|
||||
compileSdk {
|
||||
version = release(37) { minorApiLevel = 2 }
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
@@ -28,12 +30,17 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets.getByName("androidTest").assets.directories.add("$projectDir/schemas")
|
||||
listOf("test", "androidTest").forEach {
|
||||
sourceSets.getByName(it).kotlin.directories.add("$projectDir/src/sharedTest/java")
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.anthonyla.paperize"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = 51
|
||||
versionName = "4.0.0"
|
||||
targetSdk = 37
|
||||
versionCode = 61
|
||||
versionName = "4.3.1"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
@@ -60,7 +67,6 @@ android {
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
viewBinding = true
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
@@ -69,6 +75,17 @@ android {
|
||||
generateLocaleConfig = true
|
||||
}
|
||||
|
||||
lint {
|
||||
baseline = file("lint-baseline.xml")
|
||||
// Crowdin exports no "many" form for Romance languages; Android falls back to "other".
|
||||
disable += "MissingQuantity"
|
||||
// App screens, not a library: a modifier no caller passes is dead weight.
|
||||
disable += "ComposeModifierMissing"
|
||||
// Dependabot handles updates; these fail the build whenever anything upstream releases.
|
||||
disable += listOf("AndroidGradlePluginVersion", "GradleDependency", "NewerVersionAvailable")
|
||||
warningsAsErrors = true
|
||||
}
|
||||
|
||||
dependenciesInfo {
|
||||
includeInApk = false
|
||||
includeInBundle = false
|
||||
@@ -78,50 +95,43 @@ android {
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
allWarningsAsErrors = true
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
implementation(libs.androidx.ui.graphics)
|
||||
implementation(libs.androidx.ui.tooling.preview)
|
||||
implementation(libs.androidx.material3)
|
||||
implementation(libs.google.material)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.androidx.material)
|
||||
implementation(libs.coil.compose)
|
||||
implementation(libs.coil.network.okhttp)
|
||||
implementation(libs.coil.gif)
|
||||
implementation(libs.coil.svg)
|
||||
implementation(libs.androidx.datastore)
|
||||
implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.material.icons.extended)
|
||||
implementation(libs.androidx.hilt.navigation.compose)
|
||||
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)
|
||||
implementation(libs.androidx.work.runtime.ktx)
|
||||
implementation(libs.androidx.hilt.work)
|
||||
implementation(libs.lottie.compose)
|
||||
implementation(libs.accompanist.permissions)
|
||||
implementation(libs.androidx.foundation)
|
||||
implementation(libs.lazycolumnscrollbar)
|
||||
implementation(libs.androidx.profileinstaller)
|
||||
implementation(libs.reorderable)
|
||||
lintChecks(libs.compose.lint.checks)
|
||||
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.exifinterface)
|
||||
androidTestImplementation(libs.androidx.ui.test.junit4)
|
||||
debugImplementation(platform(libs.androidx.compose.bom))
|
||||
debugImplementation(libs.androidx.ui.tooling)
|
||||
@@ -132,7 +142,5 @@ 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)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<issues format="6" by="lint 9.5.1" type="baseline" client="gradle" dependencies="false" name="AGP (9.5.1)" variant="all" version="9.5.1">
|
||||
|
||||
<issue
|
||||
id="BatteryLife"
|
||||
message="Use of `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` violates the Play Store Content Policy regarding acceptable use cases, as described in https://developer.android.com/training/monitoring-device-state/doze-standby.html"
|
||||
errorLine1=" val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {"
|
||||
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
|
||||
<location
|
||||
file="src/main/java/com/anthonyla/paperize/core/util/BatteryOptimizationUtil.kt"
|
||||
line="20"
|
||||
column="42"/>
|
||||
</issue>
|
||||
|
||||
</issues>
|
||||
@@ -1,64 +1,8 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
# Library consumer rules preserve their runtime entry points. Keep release crash locations.
|
||||
-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# 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.*.** {*;}
|
||||
|
||||
# Keep domain models for serialization
|
||||
-keepclassmembers class com.anthonyla.paperize.domain.model.Album {
|
||||
!transient <fields>;
|
||||
# Strip debug and verbose logging from release builds.
|
||||
-assumenosideeffects class android.util.Log {
|
||||
public static int d(...);
|
||||
public static int v(...);
|
||||
}
|
||||
-keepclassmembers class com.anthonyla.paperize.domain.model.Wallpaper {
|
||||
!transient <fields>;
|
||||
}
|
||||
-keepclassmembers class com.anthonyla.paperize.domain.model.Folder {
|
||||
!transient <fields>;
|
||||
}
|
||||
|
||||
# Keep database entities
|
||||
-keep class com.anthonyla.paperize.data.database.entities.** { *; }
|
||||
|
||||
# Keep wallpaper service
|
||||
-keep class com.anthonyla.paperize.service.wallpaper.WallpaperChangeService { *; }
|
||||
-keep class com.anthonyla.paperize.service.wallpaper.WallpaperChangeService$* { *; }
|
||||
|
||||
# Keep enums
|
||||
-keep class com.anthonyla.paperize.core.WallpaperSourceType { *; }
|
||||
-keep class com.anthonyla.paperize.core.ScreenType { *; }
|
||||
-keep class com.anthonyla.paperize.core.ScalingType { *; }
|
||||
|
||||
# Keep navigation routes for serialization
|
||||
-keep class com.anthonyla.paperize.presentation.common.navigation.** { *; }
|
||||
|
||||
# Keep Hilt generated classes (more specific to avoid overly broad rules)
|
||||
-keep,allowobfuscation,allowshrinking @dagger.hilt.android.lifecycle.HiltViewModel class *
|
||||
-keep,allowobfuscation,allowshrinking class * extends androidx.lifecycle.ViewModel
|
||||
-keep class dagger.hilt.android.** { *; }
|
||||
-keep class dagger.hilt.internal.** { *; }
|
||||
-keep class javax.inject.** { *; }
|
||||
|
||||
# Keep Room database
|
||||
-keep class * extends androidx.room.RoomDatabase
|
||||
-keep @androidx.room.Entity class *
|
||||
-dontwarn androidx.room.paging.**
|
||||
@@ -0,0 +1,444 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 4,
|
||||
"identityHash": "d071c2eda238d0ca9c8f55b5bf591395",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "albums",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "createdAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "modifiedAt",
|
||||
"columnName": "modifiedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sourceType",
|
||||
"columnName": "sourceType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "mediaType",
|
||||
"columnName": "mediaType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpapers_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_folderId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"folderId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "folders",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_folders_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_queue",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "queuePosition",
|
||||
"columnName": "queuePosition",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_queue_albumId_screenType",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_queuePosition",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"queuePosition"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_current",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "appliedAt",
|
||||
"columnName": "appliedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_current_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'd071c2eda238d0ca9c8f55b5bf591395')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 5,
|
||||
"identityHash": "2457e5712f12294d683a5788349b5f84",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "albums",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "createdAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "modifiedAt",
|
||||
"columnName": "modifiedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sourceType",
|
||||
"columnName": "sourceType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "mediaType",
|
||||
"columnName": "mediaType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpapers_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_folderId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"folderId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "folders",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_folders_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_queue",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "queuePosition",
|
||||
"columnName": "queuePosition",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_queue_albumId_screenType",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_queuePosition",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"queuePosition"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_current",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "appliedAt",
|
||||
"columnName": "appliedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_current_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "excluded_wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"folderId",
|
||||
"uri"
|
||||
]
|
||||
},
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2457e5712f12294d683a5788349b5f84')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 6,
|
||||
"identityHash": "126e2fefe2b0a0804b9ce27d880edf8f",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "albums",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, `isEncrypted` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "createdAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "modifiedAt",
|
||||
"columnName": "modifiedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isEncrypted",
|
||||
"columnName": "isEncrypted",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "0"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sourceType",
|
||||
"columnName": "sourceType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "mediaType",
|
||||
"columnName": "mediaType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpapers_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_folderId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"folderId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "folders",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_folders_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_queue",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "queuePosition",
|
||||
"columnName": "queuePosition",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_queue_albumId_screenType",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_queuePosition",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"queuePosition"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_current",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "appliedAt",
|
||||
"columnName": "appliedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_current_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "excluded_wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"folderId",
|
||||
"uri"
|
||||
]
|
||||
},
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '126e2fefe2b0a0804b9ce27d880edf8f')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 7,
|
||||
"identityHash": "dd85d0b5892ec87e1bc8906b1f42a004",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "albums",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, `coverUri` TEXT, `createdAt` INTEGER NOT NULL, `modifiedAt` INTEGER NOT NULL, `isEncrypted` INTEGER NOT NULL DEFAULT 0, `filter` TEXT, PRIMARY KEY(`id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "createdAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "modifiedAt",
|
||||
"columnName": "modifiedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "isEncrypted",
|
||||
"columnName": "isEncrypted",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "0"
|
||||
},
|
||||
{
|
||||
"fieldPath": "filter",
|
||||
"columnName": "filter",
|
||||
"affinity": "TEXT"
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"tableName": "wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sourceType",
|
||||
"columnName": "sourceType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "mediaType",
|
||||
"columnName": "mediaType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpapers_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_folderId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"folderId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `${TABLE_NAME}` (`folderId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpapers_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "folders",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `name` TEXT NOT NULL, `uri` TEXT NOT NULL, `coverUri` TEXT, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "coverUri",
|
||||
"columnName": "coverUri",
|
||||
"affinity": "TEXT"
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_folders_albumId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_albumId` ON `${TABLE_NAME}` (`albumId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_uri",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_queue",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "queuePosition",
|
||||
"columnName": "queuePosition",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_queue_albumId_screenType",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `${TABLE_NAME}` (`albumId`, `screenType`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
},
|
||||
{
|
||||
"name": "index_wallpaper_queue_queuePosition",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"queuePosition"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `${TABLE_NAME}` (`queuePosition`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "wallpaper_current",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "albumId",
|
||||
"columnName": "albumId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "screenType",
|
||||
"columnName": "screenType",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "wallpaperId",
|
||||
"columnName": "wallpaperId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "appliedAt",
|
||||
"columnName": "appliedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"albumId",
|
||||
"screenType"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_wallpaper_current_wallpaperId",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `${TABLE_NAME}` (`wallpaperId`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "albums",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"albumId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
{
|
||||
"table": "wallpapers",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"wallpaperId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "excluded_wallpapers",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "folderId",
|
||||
"columnName": "folderId",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "fileName",
|
||||
"columnName": "fileName",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "dateModified",
|
||||
"columnName": "dateModified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "displayOrder",
|
||||
"columnName": "displayOrder",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "addedAt",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"folderId",
|
||||
"uri"
|
||||
]
|
||||
},
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "folders",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"folderId"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'dd85d0b5892ec87e1bc8906b1f42a004')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentResolver
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.database.Cursor
|
||||
import android.database.MatrixCursor
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.CancellationSignal
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.source.isDocumentMissing
|
||||
import com.anthonyla.paperize.data.source.scanFolderImages
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class DocumentAccessInstrumentedTest {
|
||||
private val appContext = ApplicationProvider.getApplicationContext<Context>()
|
||||
private val provider = TestProvider()
|
||||
private val resolver = ContentResolver.wrap(provider)
|
||||
private val context = object : ContextWrapper(appContext) {
|
||||
override fun getContentResolver(): ContentResolver = resolver
|
||||
}
|
||||
private val documentUri = Uri.parse("content://test/document/image")
|
||||
private val treeUri = Uri.parse("content://test/tree/root")
|
||||
|
||||
@Test fun missingRequiresACompleteSuccessfulQuery() {
|
||||
provider.answer = { MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME)) }
|
||||
assertTrue(documentUri.isDocumentMissing(resolver))
|
||||
provider.answer = { MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME)).apply { addRow(arrayOf<Any>("photo")) } }
|
||||
assertFalse(documentUri.isDocumentMissing(resolver))
|
||||
provider.answer = { null }
|
||||
assertFalse(documentUri.isDocumentMissing(resolver))
|
||||
provider.answer = { throw SecurityException("Permission revoked") }
|
||||
assertFalse(documentUri.isDocumentMissing(resolver))
|
||||
provider.answer = { throw IllegalStateException("Offline") }
|
||||
assertFalse(documentUri.isDocumentMissing(resolver))
|
||||
}
|
||||
|
||||
@Test fun loadingAndErrorResponsesDoNotProveDeletion() {
|
||||
for (metadata in listOf(
|
||||
Bundle().apply { putBoolean(DocumentsContract.EXTRA_LOADING, true) },
|
||||
Bundle().apply { putString(DocumentsContract.EXTRA_ERROR, "Offline") }
|
||||
)) {
|
||||
provider.answer = {
|
||||
MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME)).apply { extras = metadata }
|
||||
}
|
||||
assertFalse(documentUri.isDocumentMissing(resolver))
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun scanRejectsPartialResultsAndClosesItsCursor() = runBlocking {
|
||||
val cursor = directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("image", "photo.png", "image/png", 1L))
|
||||
extras = Bundle().apply { putBoolean(DocumentsContract.EXTRA_LOADING, true) }
|
||||
}
|
||||
provider.answer = { cursor }
|
||||
try {
|
||||
treeUri.scanFolderImages(context, false)
|
||||
fail("Expected incomplete scan failure")
|
||||
} catch (_: java.io.IOException) { }
|
||||
assertTrue(cursor.isClosed)
|
||||
}
|
||||
|
||||
@Test fun scanDetectsCyclesAndKeepsMetadata() = runBlocking {
|
||||
provider.answer = { uri ->
|
||||
when (DocumentsContract.getDocumentId(uri)) {
|
||||
"root" -> directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("child", "Child", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
|
||||
addRow(arrayOf<Any>("image", "photo.PNG", "image/png", 42L))
|
||||
}
|
||||
else -> directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("root", "Root", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
|
||||
addRow(arrayOf<Any>("image", "photo.PNG", "image/png", 42L))
|
||||
}
|
||||
}
|
||||
}
|
||||
val found = treeUri.scanFolderImages(context, false)
|
||||
assertEquals(1, found.size)
|
||||
assertEquals("photo.PNG", found.single().name)
|
||||
assertEquals(42L, found.single().modifiedAt)
|
||||
assertEquals(2, provider.queries)
|
||||
}
|
||||
|
||||
@Test fun scansOnlyFilesForTheAlbumModeIncludingNestedDirectories() = runBlocking {
|
||||
provider.answer = { uri ->
|
||||
when (DocumentsContract.getDocumentId(uri)) {
|
||||
"root" -> directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("child", "Child", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
|
||||
addRow(arrayOf<Any>("plain", "photo.JPG", "image/jpeg", 1L))
|
||||
addRow(arrayOf<Any>("encrypted", "photo.JPG_ENC", "application/octet-stream", 2L))
|
||||
addRow(arrayOf<Any>("other", "photo.png_enc", "application/octet-stream", 3L))
|
||||
}
|
||||
else -> directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("nested", "nested.jpg_enc", "application/octet-stream", 4L))
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(setOf("photo.JPG"), treeUri.scanFolderImages(context, false).map { it.name }.toSet())
|
||||
assertEquals(setOf("photo.JPG_ENC", "nested.jpg_enc"), treeUri.scanFolderImages(context, true).map { it.name }.toSet())
|
||||
}
|
||||
|
||||
@Test fun scanSkipsTrashedFilesButKeepsImagesInHiddenFolders() = runBlocking {
|
||||
provider.answer = { uri ->
|
||||
when (DocumentsContract.getDocumentId(uri)) {
|
||||
"root" -> directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("trashed", ".trashed54970.jpg", "image/jpeg", 1L))
|
||||
addRow(arrayOf<Any>("trash", ".Trash-123.png", "image/png", 2L))
|
||||
addRow(arrayOf<Any>("primary:Pictures/.trashed-1797497267-old.jpg", "old.jpg", "image/jpeg", 5L))
|
||||
addRow(arrayOf<Any>("primary:.trashed-1797497267-top.jpg", "top.jpg", "image/jpeg", 6L))
|
||||
addRow(arrayOf<Any>("primary:Pictures/.walls", ".walls", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
|
||||
addRow(arrayOf<Any>("plain", "photo.jpg", "image/jpeg", 3L))
|
||||
}
|
||||
"primary:Pictures/.walls" -> directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("primary:Pictures/.walls/wall.png", "wall.png", "image/png", 4L))
|
||||
}
|
||||
else -> directoryCursor()
|
||||
}
|
||||
}
|
||||
val found = treeUri.scanFolderImages(context, false)
|
||||
assertEquals(setOf("photo.jpg", "wall.png"), found.map { it.name }.toSet())
|
||||
}
|
||||
|
||||
@Test fun failureInChildFolderDoesNotReturnPartialImport() = runBlocking {
|
||||
provider.answer = { uri ->
|
||||
if (DocumentsContract.getDocumentId(uri) == "root") directoryCursor().apply {
|
||||
addRow(arrayOf<Any>("image", "photo.png", "image/png", 42L))
|
||||
addRow(arrayOf<Any>("child", "Child", DocumentsContract.Document.MIME_TYPE_DIR, 0L))
|
||||
} else null
|
||||
}
|
||||
try {
|
||||
treeUri.scanFolderImages(context, false)
|
||||
fail("Expected child folder failure")
|
||||
} catch (_: java.io.IOException) { }
|
||||
}
|
||||
|
||||
@Test fun cancellingAnActiveScanCancelsTheProviderQuery() = runBlocking {
|
||||
val started = CountDownLatch(1)
|
||||
val cancelled = CountDownLatch(1)
|
||||
provider.onQuery = { signal ->
|
||||
signal?.setOnCancelListener { cancelled.countDown() }
|
||||
started.countDown()
|
||||
check(cancelled.await(5, TimeUnit.SECONDS)) { "Provider query was not cancelled" }
|
||||
signal?.throwIfCanceled()
|
||||
}
|
||||
val scan = launch(Dispatchers.IO) { treeUri.scanFolderImages(context, false) }
|
||||
assertTrue(started.await(5, TimeUnit.SECONDS))
|
||||
scan.cancel()
|
||||
scan.join()
|
||||
assertEquals(0L, cancelled.count)
|
||||
}
|
||||
|
||||
@Test fun cleanupHandlesDuplicateUrisAndConcurrentReorderingWithoutTouchingOtherAlbums() = runBlocking {
|
||||
val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build()
|
||||
try {
|
||||
db.albumDao().insertAlbum(AlbumEntity("one", "One", documentUri.toString(), 0L, 0L))
|
||||
db.albumDao().insertAlbum(AlbumEntity("two", "Two", null, 0L, 0L))
|
||||
val uri = documentUri.toString()
|
||||
val missing = WallpaperEntity("first", "one", null, uri, "photo.png", 0L)
|
||||
db.wallpaperDao().insertWallpapers((0..504).map { missing.copy(id = "missing-$it") })
|
||||
db.wallpaperDao().insertWallpapers(listOf(missing.copy(id = "other-album", albumId = "two")))
|
||||
provider.answer = {
|
||||
if (provider.queries == 1) {
|
||||
// Move an unread image before the first page while that page is being scanned.
|
||||
db.openHelper.writableDatabase.execSQL("UPDATE wallpapers SET displayOrder = -1 WHERE id = 'missing-99'")
|
||||
}
|
||||
MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME))
|
||||
}
|
||||
val repository = com.anthonyla.paperize.data.repository.AlbumRepositoryImpl(
|
||||
com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
|
||||
assertEquals(505, repository.pruneMissingEntries("one"))
|
||||
assertEquals(0, db.wallpaperDao().getWallpaperIdsByAlbum("one").size)
|
||||
assertNull(db.albumDao().getAlbumById("one")?.coverUri)
|
||||
assertNotNull(db.wallpaperDao().getWallpaperById("other-album"))
|
||||
} finally { db.close() }
|
||||
}
|
||||
|
||||
@Test fun cancelledCleanupDoesNotLeavePartialDeletions() = runBlocking {
|
||||
val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build()
|
||||
try {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", "content://test/document/first"))
|
||||
db.wallpaperDao().insertWallpapers(listOf("first", "second").map {
|
||||
WallpaperEntity(it, "album", null, "content://test/document/$it", "$it.png", 0L)
|
||||
})
|
||||
provider.answer = {
|
||||
if (provider.queries == 2) throw kotlinx.coroutines.CancellationException()
|
||||
MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME))
|
||||
}
|
||||
val repository = com.anthonyla.paperize.data.repository.AlbumRepositoryImpl(
|
||||
com.anthonyla.paperize.data.source.AndroidDocumentSource(context), db)
|
||||
try {
|
||||
repository.pruneMissingEntries("album")
|
||||
fail("Expected cancellation")
|
||||
} catch (_: kotlinx.coroutines.CancellationException) { }
|
||||
assertEquals(2, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
|
||||
assertEquals("content://test/document/first", db.albumDao().getAlbumById("album")?.coverUri)
|
||||
} finally { db.close() }
|
||||
}
|
||||
|
||||
private fun directoryCursor() = MatrixCursor(arrayOf(
|
||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED
|
||||
))
|
||||
|
||||
private class TestProvider : ContentProvider() {
|
||||
var queries = 0
|
||||
var answer: (Uri) -> Cursor? = { null }
|
||||
var onQuery: ((CancellationSignal?) -> Unit)? = null
|
||||
override fun onCreate() = true
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
|
||||
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {
|
||||
queries++
|
||||
return answer(uri)
|
||||
}
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
|
||||
selectionArgs: Array<out String>?, sortOrder: String?, cancellationSignal: CancellationSignal?): Cursor? {
|
||||
onQuery?.invoke(cancellationSignal)
|
||||
return query(uri, projection, selection, selectionArgs, sortOrder)
|
||||
}
|
||||
override fun getType(uri: Uri): String? = null
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?) = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?) = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.net.Uri
|
||||
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.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 narrowImagesRetainAtLeastOnePixelInBothDecodePaths() {
|
||||
val image = createJpeg(width = 1, height = 1000)
|
||||
val uri = Uri.fromFile(image)
|
||||
for (scaling in listOf(ScalingType.FIT, ScalingType.NONE)) {
|
||||
val live = com.anthonyla.paperize.service.livewallpaper.renderer.ContentUriImageLoader(
|
||||
context.contentResolver, uri, scaling
|
||||
).load(20, 20)
|
||||
assertNotNull(live)
|
||||
assertEquals(1, live?.width)
|
||||
assertEquals(if (scaling == ScalingType.FIT) 20 else 40, live?.height)
|
||||
live?.recycle()
|
||||
|
||||
val static = retrieveBitmap(context, uri, 20, 20, scaling)
|
||||
assertNotNull(static)
|
||||
assertEquals(20, static?.width)
|
||||
assertEquals(20, static?.height)
|
||||
static?.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@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.FILL,
|
||||
preserveSourceOverflow = true
|
||||
)
|
||||
|
||||
// Rotated, the 20x40 source covers the canvas at scale 1. Unrotated, the 40x20 source
|
||||
// would need scale 2 to cover the height and come back 80x40.
|
||||
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 everyStaticScalingModeProducesOneExactScreenCanvas() {
|
||||
val image = createJpeg(width = 160, height = 90)
|
||||
|
||||
ScalingType.entries.forEach { scaling ->
|
||||
val result = retrieveBitmap(
|
||||
context = context,
|
||||
wallpaperUri = Uri.fromFile(image),
|
||||
width = 120,
|
||||
height = 200,
|
||||
scaling = scaling,
|
||||
preserveSourceOverflow = false
|
||||
)
|
||||
|
||||
assertNotNull("Expected a bitmap for $scaling", result)
|
||||
assertEquals("Unexpected width for $scaling", 120, result?.width)
|
||||
assertEquals("Unexpected height for $scaling", 200, result?.height)
|
||||
result?.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fallbackBitmapsUseTheRequestedScalingAndCenterCrop() {
|
||||
ScalingType.entries.forEach { scaling ->
|
||||
val source = mutableBitmap(80, 40, Color.RED)
|
||||
for (y in 0 until 40) {
|
||||
for (x in 20 until 60) source.setPixel(x, y, Color.GREEN)
|
||||
}
|
||||
val result = finalizeToCanvas(source, 40, 80, scaling)
|
||||
try {
|
||||
assertTrue(source.isRecycled)
|
||||
assertEquals(40, result.width)
|
||||
assertEquals(80, result.height)
|
||||
assertEquals("Center for $scaling", Color.GREEN, result.getPixel(20, 40))
|
||||
val top = if (scaling == ScalingType.FIT || scaling == ScalingType.NONE) Color.BLACK else Color.GREEN
|
||||
assertEquals("Top for $scaling", top, result.getPixel(20, 0))
|
||||
val side = if (scaling == ScalingType.FIT || scaling == ScalingType.STRETCH) Color.RED else Color.GREEN
|
||||
assertEquals("Side for $scaling", side, result.getPixel(2, 40))
|
||||
} finally {
|
||||
result.recycle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blurredFitBackgroundFillsTheBarsFromTheImage() {
|
||||
val source = mutableBitmap(80, 40, Color.RED)
|
||||
val result = finalizeToCanvas(source, 40, 80, ScalingType.FIT, blurFitBackground = true)
|
||||
try {
|
||||
assertEquals(Color.RED, result.getPixel(20, 0))
|
||||
assertEquals(Color.RED, result.getPixel(20, 40))
|
||||
} finally {
|
||||
result.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blurredBackdropAveragesFineDetailInsteadOfSamplingIt() {
|
||||
val source = Bitmap.createBitmap(512, 256, Bitmap.Config.ARGB_8888)
|
||||
val checker = IntArray(512 * 256) { i -> if ((i % 512 + i / 512) % 2 == 0) Color.WHITE else Color.BLACK }
|
||||
source.setPixels(checker, 0, 512, 0, 0, 512, 256)
|
||||
val backdrop = createBlurredBackdrop(source)
|
||||
try {
|
||||
assertEquals(64, backdrop.width)
|
||||
assertEquals(32, backdrop.height)
|
||||
for (y in 0 until backdrop.height) {
|
||||
for (x in 0 until backdrop.width) {
|
||||
assertTrue("Pixel $x,$y", Color.red(backdrop.getPixel(x, y)) in 100..155)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
source.recycle()
|
||||
backdrop.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.anthonyla.paperize.data.database
|
||||
|
||||
import android.content.Context
|
||||
import android.database.sqlite.SQLiteDatabase
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class LibraryMigrationInstrumentedTest {
|
||||
private val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
|
||||
@Test fun everyLegacyVersionPreservesLibraryAndQueue() = runBlocking {
|
||||
for (version in 1..4) {
|
||||
val name = "migration-test-$version"
|
||||
context.deleteDatabase(name)
|
||||
try {
|
||||
createLegacyDatabase(name, version)
|
||||
val db = Room.databaseBuilder(context, PaperizeDatabase::class.java, name)
|
||||
.addMigrations(*LIBRARY_MIGRATIONS).build()
|
||||
try {
|
||||
assertEquals("My album", db.albumDao().getAlbumById("album")?.name)
|
||||
assertEquals("content://image", db.albumDao().getAlbumById("album")?.coverUri)
|
||||
assertFalse(db.albumDao().getAlbumById("album")!!.isEncrypted)
|
||||
val image = db.wallpaperDao().getWallpaperById("image")!!
|
||||
assertEquals("folder", image.folderId)
|
||||
assertEquals("photo.jpg", image.fileName)
|
||||
assertEquals(7, image.displayOrder)
|
||||
assertEquals(42L, image.addedAt)
|
||||
assertEquals("content://image", db.folderDao().getFolderById("folder")?.coverUri)
|
||||
assertEquals(listOf("image"), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
|
||||
assertEquals(if (version >= 3) "image" else null, db.wallpaperCurrentDao().getCurrentWallpaperFlow("album", ScreenType.HOME).first()?.id)
|
||||
assertTrue(db.excludedWallpaperDao().getUris("folder").isEmpty())
|
||||
db.openHelper.readableDatabase.query("PRAGMA foreign_key_check").use { assertEquals(0, it.count) }
|
||||
db.albumDao().deleteAlbumById("album")
|
||||
assertNull(db.wallpaperDao().getWallpaperById("image"))
|
||||
assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
|
||||
} finally { db.close() }
|
||||
} finally { context.deleteDatabase(name) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun bothVersionFiveSchemasMigrateToTheCombinedSchema() = runBlocking {
|
||||
for (hasEncryptionColumn in listOf(false, true)) {
|
||||
val name = "migration-test-v5-encrypted-$hasEncryptionColumn"
|
||||
context.deleteDatabase(name)
|
||||
try {
|
||||
createVersionFiveDatabase(name, hasEncryptionColumn)
|
||||
val db = Room.databaseBuilder(context, PaperizeDatabase::class.java, name)
|
||||
.addMigrations(*LIBRARY_MIGRATIONS).build()
|
||||
try {
|
||||
assertEquals(hasEncryptionColumn, db.albumDao().getAlbumById("album")!!.isEncrypted)
|
||||
assertEquals(
|
||||
if (hasEncryptionColumn) emptyList<String>() else listOf("content://excluded"),
|
||||
db.excludedWallpaperDao().getUris("folder")
|
||||
)
|
||||
db.openHelper.readableDatabase.query("PRAGMA foreign_key_check").use { assertEquals(0, it.count) }
|
||||
} finally { db.close() }
|
||||
} finally { context.deleteDatabase(name) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun createVersionFiveDatabase(name: String, hasEncryptionColumn: Boolean) {
|
||||
val schema = InstrumentationRegistry.getInstrumentation().context.assets
|
||||
.open("com.anthonyla.paperize.data.database.PaperizeDatabase/4.json")
|
||||
.bufferedReader().use { JSONObject(it.readText()).getJSONObject("database").getJSONArray("entities") }
|
||||
val path = context.getDatabasePath(name)
|
||||
path.parentFile!!.mkdirs()
|
||||
SQLiteDatabase.openOrCreateDatabase(path, null).use { db ->
|
||||
db.setForeignKeyConstraintsEnabled(true)
|
||||
for (index in 0 until schema.length()) {
|
||||
val entity = schema.getJSONObject(index)
|
||||
val table = entity.getString("tableName")
|
||||
if (table == "excluded_wallpapers") continue
|
||||
db.execSQL(entity.getString("createSql").replace("\${TABLE_NAME}", table))
|
||||
val indices = entity.optJSONArray("indices")
|
||||
if (indices != null) for (i in 0 until indices.length()) {
|
||||
db.execSQL(indices.getJSONObject(i).getString("createSql").replace("\${TABLE_NAME}", table))
|
||||
}
|
||||
}
|
||||
if (hasEncryptionColumn) {
|
||||
db.execSQL("ALTER TABLE `albums` ADD COLUMN `isEncrypted` INTEGER NOT NULL DEFAULT 0")
|
||||
} else {
|
||||
db.execSQL("CREATE TABLE IF NOT EXISTS `excluded_wallpapers` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE)")
|
||||
}
|
||||
db.execSQL(
|
||||
"INSERT INTO albums (id, name, coverUri, createdAt, modifiedAt${if (hasEncryptionColumn) ", isEncrypted" else ""}) " +
|
||||
"VALUES ('album', 'My album', 'content://image', 1, 2${if (hasEncryptionColumn) ", 1" else ""})"
|
||||
)
|
||||
db.execSQL("INSERT INTO folders (id, albumId, name, uri, coverUri, dateModified, displayOrder, addedAt) VALUES ('folder', 'album', 'Photos', 'content://tree', 'content://image', 3, 0, 4)")
|
||||
if (!hasEncryptionColumn) {
|
||||
db.execSQL("INSERT INTO excluded_wallpapers VALUES ('folder', 'content://excluded', 'excluded', 'excluded.jpg', 5, 6, 7)")
|
||||
}
|
||||
db.version = 5
|
||||
}
|
||||
}
|
||||
|
||||
private fun createLegacyDatabase(name: String, version: Int) {
|
||||
val schema = InstrumentationRegistry.getInstrumentation().context.assets
|
||||
.open("com.anthonyla.paperize.data.database.PaperizeDatabase/4.json")
|
||||
.bufferedReader().use { JSONObject(it.readText()).getJSONObject("database").getJSONArray("entities") }
|
||||
val path = context.getDatabasePath(name)
|
||||
path.parentFile!!.mkdirs()
|
||||
SQLiteDatabase.openOrCreateDatabase(path, null).use { db ->
|
||||
db.setForeignKeyConstraintsEnabled(true)
|
||||
for (index in 0 until schema.length()) {
|
||||
val entity = schema.getJSONObject(index)
|
||||
val table = entity.getString("tableName")
|
||||
if (table == "wallpaper_current" && version < 3) continue
|
||||
var create = entity.getString("createSql").replace("\${TABLE_NAME}", table)
|
||||
// Verified against the version 1, 2 and 3 entities in Git history.
|
||||
if (table == "wallpapers") create = when (version) {
|
||||
1 -> create.replace("`mediaType` TEXT NOT NULL, ", "")
|
||||
2, 3 -> create.replace("PRIMARY KEY(`id`)", "`cropOffsetX` REAL, `cropOffsetY` REAL, `cropScale` REAL, PRIMARY KEY(`id`)")
|
||||
else -> create
|
||||
}
|
||||
db.execSQL(create)
|
||||
val indices = entity.optJSONArray("indices")
|
||||
if (indices != null) for (i in 0 until indices.length()) {
|
||||
db.execSQL(indices.getJSONObject(i).getString("createSql").replace("\${TABLE_NAME}", table))
|
||||
}
|
||||
}
|
||||
db.execSQL("INSERT INTO albums VALUES ('album', 'My album', 'content://image', 1, 2)")
|
||||
db.execSQL("INSERT INTO folders (id, albumId, name, uri, coverUri, dateModified, displayOrder, addedAt) VALUES ('folder', 'album', 'Photos', 'content://tree', 'content://image', 3, 0, 4)")
|
||||
val mediaColumn = if (version > 1) ", mediaType" else ""
|
||||
val mediaValue = if (version > 1) ", 'IMAGE'" else ""
|
||||
db.execSQL("INSERT INTO wallpapers (id, albumId, folderId, uri, fileName, dateModified, displayOrder, sourceType, addedAt$mediaColumn) VALUES ('image', 'album', 'folder', 'content://image', 'photo.jpg', 5, 7, 'FOLDER', 42$mediaValue)")
|
||||
db.execSQL("INSERT INTO wallpaper_queue VALUES (1, 'album', 'image', 'HOME', 2, 6)")
|
||||
if (version >= 3) db.execSQL("INSERT INTO wallpaper_current VALUES ('album', 'HOME', 'image', 9)")
|
||||
db.version = version
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import com.anthonyla.paperize.testFolder
|
||||
import com.anthonyla.paperize.testWallpaper
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.mapper.toEntity
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.source.WallpaperRenderer
|
||||
import com.anthonyla.paperize.domain.usecase.ChangeWallpaperUseCase
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class AlbumRepositoryInstrumentedTest {
|
||||
private val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
private val db = Room.inMemoryDatabaseBuilder(context, PaperizeDatabase::class.java).build()
|
||||
private val documents = com.anthonyla.paperize.data.source.AndroidDocumentSource(context)
|
||||
private val wallpapers = WallpaperRepositoryImpl(db, documents, com.anthonyla.paperize.data.source.EncryptedImageStore(context))
|
||||
private val albums = AlbumRepositoryImpl(documents, db)
|
||||
|
||||
@After fun close() = db.close()
|
||||
|
||||
@Test fun renamingPreservesAlbumContentsAndRejectsOtherNamesIgnoringCase() = runBlocking {
|
||||
val album = albums.createAlbum("Original", isEncrypted = true)
|
||||
albums.addWallpapersToAlbum(album.id, listOf(testWallpaper("image", album.id)))
|
||||
albums.createAlbum("Other")
|
||||
assertFalse(albums.renameAlbum(album.id, "other"))
|
||||
assertTrue(albums.renameAlbum(album.id, "ORIGINAL"))
|
||||
assertTrue(albums.renameAlbum(album.id, "Renamed"))
|
||||
val saved = albums.getAlbumById(album.id).first()!!
|
||||
assertEquals("Renamed", saved.name)
|
||||
assertTrue(saved.isEncrypted)
|
||||
assertEquals(listOf("image"), saved.wallpapers.map { it.id })
|
||||
}
|
||||
|
||||
@Test fun encryptedAlbumModeSurvivesPersistence() = runBlocking {
|
||||
val album = albums.createAlbum("Encrypted", isEncrypted = true)
|
||||
assertTrue(album.isEncrypted)
|
||||
assertTrue(albums.getAlbumById(album.id).first()!!.isEncrypted)
|
||||
assertFalse(albums.createAlbum("Ordinary").isEncrypted)
|
||||
}
|
||||
|
||||
@Test fun cancellingAChunkedFolderImportRollsBackAllRows() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val folder = testFolder("folder", "album").copy(
|
||||
wallpapers = (0..599).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://image-$it") }
|
||||
)
|
||||
try {
|
||||
albums.addFolderToAlbum("album", folder) { saved, _ ->
|
||||
if (saved >= 500) throw CancellationException("User cancelled")
|
||||
}
|
||||
fail("Expected cancellation")
|
||||
} catch (_: CancellationException) { }
|
||||
assertEquals(0, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
|
||||
assertNull(db.folderDao().getFolderWithWallpapers("folder").first())
|
||||
assertNull(db.albumDao().getAlbumById("album")?.coverUri)
|
||||
}
|
||||
|
||||
@Test fun importingImagesUpdatesCoverAndRotationQueueTogether() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val first = testWallpaper("first", "album").copy(uri = "content://first")
|
||||
db.wallpaperDao().insertWallpapers(listOf(first.toEntity()))
|
||||
db.wallpaperQueueDao().rebuildQueue("album", ScreenType.HOME, listOf("first"))
|
||||
db.folderDao().insertFolder(testFolder("folder", "album").toEntity())
|
||||
val second = first.copy(id = "second", uri = "content://second", folderId = "folder")
|
||||
|
||||
assertEquals(1, albums.addWallpapersToAlbum("album", listOf(second)))
|
||||
assertTrue(db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).isEmpty())
|
||||
assertEquals(2, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
|
||||
assertEquals("content://second", db.folderDao().getFolderById("folder")?.coverUri)
|
||||
}
|
||||
|
||||
@Test fun removingCoverUsesOnlyWallpapersFromThatAlbum() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("one", "One", "content://shared"))
|
||||
db.albumDao().insertAlbum(AlbumEntity("two", "Two", "content://shared"))
|
||||
val cover = testWallpaper("cover", "one").copy(uri = "content://shared")
|
||||
val replacement = cover.copy(id = "replacement", uri = "content://replacement", displayOrder = 1)
|
||||
db.wallpaperDao().insertWallpapers(listOf(cover, replacement, cover.copy(id = "other", albumId = "two")).map { it.toEntity() })
|
||||
|
||||
albums.removeWallpapersFromAlbum("one", listOf("cover", "other"))
|
||||
assertEquals("content://replacement", db.albumDao().getAlbumById("one")?.coverUri)
|
||||
assertEquals("content://shared", db.albumDao().getAlbumById("two")?.coverUri)
|
||||
assertNotNull(db.wallpaperDao().getWallpaperById("other"))
|
||||
}
|
||||
|
||||
@Test fun coverRefreshUsesDisplayOrderAndClearsEmptyFolders() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
db.folderDao().insertFolder(testFolder("folder", "album").toEntity())
|
||||
val later = testWallpaper("later", "album").copy(folderId = "folder", uri = "content://later", displayOrder = 9)
|
||||
val first = later.copy(id = "first", uri = "content://first", displayOrder = 1)
|
||||
val direct = later.copy(id = "direct", folderId = null, uri = "content://direct", displayOrder = 99)
|
||||
db.wallpaperDao().insertWallpapers(listOf(later, first, direct).map { it.toEntity() })
|
||||
|
||||
db.folderDao().refreshFolderCovers("album")
|
||||
assertEquals("content://first", db.folderDao().getFolderById("folder")?.coverUri)
|
||||
assertEquals("content://direct", db.wallpaperDao().getAlbumCoverUri("album"))
|
||||
|
||||
db.wallpaperDao().deleteAlbumWallpapers("album", listOf("later", "first"))
|
||||
db.folderDao().refreshFolderCovers("album")
|
||||
assertNull(db.folderDao().getFolderById("folder")?.coverUri)
|
||||
}
|
||||
|
||||
@Test fun concurrentImportsDeduplicateInsideTheTransaction() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val image = testWallpaper("one", "album").copy(uri = "content://same")
|
||||
val first = async(Dispatchers.IO) { albums.addWallpapersToAlbum("album", listOf(image)) }
|
||||
val second = async(Dispatchers.IO) { albums.addWallpapersToAlbum("album", listOf(image.copy(id = "two"))) }
|
||||
assertEquals(1, first.await() + second.await())
|
||||
assertEquals(1, db.wallpaperDao().getWallpaperIdsByAlbum("album").size)
|
||||
|
||||
db.folderDao().insertFolder(testFolder("folder", "album").toEntity())
|
||||
assertEquals(1, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "folder-image", folderId = "folder"))))
|
||||
db.folderDao().deleteAlbumFolder("album", "folder")
|
||||
assertEquals(0, albums.addWallpapersToAlbum("album", listOf(image.copy(id = "stale", folderId = "folder"))))
|
||||
}
|
||||
|
||||
@Test fun continuingFromAPickedWallpaperFollowsAlbumOrderAndWraps() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
db.wallpaperDao().insertWallpapers((1..5).map {
|
||||
testWallpaper("$it", "album").copy(uri = "content://$it", displayOrder = it).toEntity()
|
||||
})
|
||||
val change = ChangeWallpaperUseCase(wallpapers, SettingsRepositoryImpl(context), object : WallpaperRenderer {
|
||||
override suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings) = null
|
||||
})
|
||||
suspend fun next() = change.dequeueNext("album", ScreenType.HOME, shuffle = false).id
|
||||
|
||||
change.completeSpecific("album", ScreenType.HOME, "3", shuffle = false, startSequenceHere = true)
|
||||
assertEquals(listOf("4", "5", "1"), List(3) { next() })
|
||||
|
||||
change.completeSpecific("album", ScreenType.HOME, "5", shuffle = false, startSequenceHere = true)
|
||||
assertEquals("1", next())
|
||||
}
|
||||
|
||||
@Test fun concurrentQueueCreationKeepsBothScreensInSyncAndDoesNotRefillConsumedItems() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
albums.addWallpapersToAlbum("album", (1..8).map {
|
||||
testWallpaper("image-$it", "album").copy(uri = "content://image-$it")
|
||||
})
|
||||
val home = async(Dispatchers.IO) { wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true) }
|
||||
val lock = async(Dispatchers.IO) { wallpapers.ensureWallpaperQueue("album", ScreenType.LOCK, true) }
|
||||
home.await(); lock.await()
|
||||
val expected = db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId }
|
||||
assertEquals(8, expected.toSet().size)
|
||||
assertEquals(expected, db.wallpaperQueueDao().getQueueItems("album", ScreenType.LOCK).map { it.wallpaperId })
|
||||
wallpapers.getAndDequeueWallpaper("album", ScreenType.HOME)
|
||||
wallpapers.ensureWallpaperQueue("album", ScreenType.HOME, true)
|
||||
assertEquals(expected.drop(1), db.wallpaperQueueDao().getQueueItems("album", ScreenType.HOME).map { it.wallpaperId })
|
||||
}
|
||||
|
||||
@Test fun syncFolderWallpapersRemovesOnlyThatFoldersMissingFilesAndAddsNewOnes() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(
|
||||
wallpapers = (1..5).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
|
||||
))
|
||||
albums.addWallpapersToAlbum("album", listOf(testWallpaper("direct", "album").copy(uri = "content://photo-3")))
|
||||
|
||||
val scanned = listOf(1, 2, 4, 5, 6).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
|
||||
val added = albums.syncFolderWallpapers("album", "folder", scanned)
|
||||
|
||||
assertEquals(1, added)
|
||||
assertEquals(
|
||||
listOf(1, 2, 4, 5, 6).map { "content://photo-$it" }.toSet(),
|
||||
db.wallpaperDao().getUrisInCollection("album", "folder").toSet()
|
||||
)
|
||||
assertEquals(listOf("content://photo-3"), db.wallpaperDao().getUrisInCollection("album", null))
|
||||
}
|
||||
|
||||
@Test fun syncFolderWallpapersKeepsRowsWhenScanIsEmpty() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(
|
||||
wallpapers = listOf(testWallpaper("image-1", "album").copy(folderId = "folder", uri = "content://photo-1"))
|
||||
))
|
||||
|
||||
assertEquals(0, albums.syncFolderWallpapers("album", "folder", emptyList()))
|
||||
assertEquals(1, db.wallpaperDao().getUrisInCollection("album", "folder").size)
|
||||
}
|
||||
|
||||
@Test fun removedFolderImageStaysOutOfRescansUntilRestoredInPlace() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val images = (1..3).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
|
||||
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(wallpapers = images))
|
||||
val removed = albums.removeWallpaper("image-2")!!
|
||||
|
||||
assertEquals(0, albums.syncFolderWallpapers("album", "folder", images))
|
||||
val folder = albums.getFolderById("folder").first()!!
|
||||
assertEquals(setOf("image-1", "image-3"), folder.wallpapers.map { it.id }.toSet())
|
||||
assertEquals(listOf(removed), folder.removedWallpapers)
|
||||
|
||||
albums.restoreWallpaper(removed)
|
||||
assertEquals(listOf("image-1", "image-2", "image-3"), db.wallpaperDao().getOrderedWallpaperIdsByAlbum("album"))
|
||||
assertTrue(albums.getFolderById("folder").first()!!.removedWallpapers.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun rescanForgetsRemovedImagesWhoseFilesAreGone() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val images = (1..2).map { testWallpaper("image-$it", "album").copy(folderId = "folder", uri = "content://photo-$it") }
|
||||
albums.addFolderToAlbum("album", testFolder("folder", "album").copy(wallpapers = images))
|
||||
albums.removeWallpaper("image-1")
|
||||
|
||||
albums.syncFolderWallpapers("album", "folder", images.drop(1))
|
||||
assertTrue(albums.getFolderById("folder").first()!!.removedWallpapers.isEmpty())
|
||||
// The file coming back later is a new image, not a removed one.
|
||||
assertEquals(1, albums.syncFolderWallpapers("album", "folder", images))
|
||||
}
|
||||
|
||||
@Test fun undoingADirectImageImportedAgainAddsNoDuplicate() = runBlocking {
|
||||
db.albumDao().insertAlbum(AlbumEntity("album", "Album", null))
|
||||
val image = testWallpaper("image", "album").copy(uri = "content://photo")
|
||||
albums.addWallpapersToAlbum("album", listOf(image))
|
||||
val removed = albums.removeWallpaper("image")!!
|
||||
albums.addWallpapersToAlbum("album", listOf(image.copy(id = "again")))
|
||||
|
||||
albums.restoreWallpaper(removed)
|
||||
assertEquals(listOf("again"), db.wallpaperDao().getWallpaperIdsByAlbum("album"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.WallpaperEffects
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.launch
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SettingsRepositoryInstrumentedTest {
|
||||
@Test fun encryptedPreviewSettingPersistsAndCanBeDisabled() = runBlocking {
|
||||
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
|
||||
val original = preferences.getAppSettings().encryptedPreviews
|
||||
try {
|
||||
preferences.updateEncryptedPreviews(true)
|
||||
assertTrue(preferences.getAppSettings().encryptedPreviews)
|
||||
preferences.updateEncryptedPreviews(false)
|
||||
assertFalse(preferences.getAppSettings().encryptedPreviews)
|
||||
} finally {
|
||||
preferences.updateEncryptedPreviews(original)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun concurrentScheduleEditsReadTheLatestValueWithoutLosingSelections() = runBlocking {
|
||||
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
|
||||
val previousSettings = preferences.getScheduleSettings()
|
||||
try {
|
||||
val initial = ScheduleSettings(homeAlbumId = "home", homeIntervalMinutes = 30)
|
||||
preferences.updateScheduleSettings(initial)
|
||||
coroutineScope {
|
||||
repeat(20) {
|
||||
launch {
|
||||
preferences.updateScheduleSettings { current ->
|
||||
current.copy(homeIntervalMinutes = current.homeIntervalMinutes + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
launch { preferences.updateAlbumId(ScreenType.HOME, "new-home") }
|
||||
}
|
||||
assertEquals(initial.copy(homeAlbumId = "new-home", homeIntervalMinutes = 50), preferences.getScheduleSettings())
|
||||
} finally {
|
||||
preferences.updateScheduleSettings(previousSettings)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun resettingSchedulesPreservesAppearanceAndWallpaperMode() = runBlocking {
|
||||
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
|
||||
val previousSettings = preferences.getScheduleSettings()
|
||||
val previousMode = preferences.getWallpaperMode()
|
||||
val appearance = preferences.getAppSettings()
|
||||
try {
|
||||
preferences.updateWallpaperMode(WallpaperMode.LIVE)
|
||||
val effects = WallpaperEffects(
|
||||
enableBlur = true, blurPercentage = 30, enableDarken = true, darkenPercentage = 20,
|
||||
enableVignette = true, vignettePercentage = 40, enableGrayscale = true, grayscalePercentage = 50,
|
||||
enableDoubleTap = true, enableChangeOnScreenOff = true, enableParallax = true, parallaxIntensity = 60
|
||||
)
|
||||
// Each screen gets distinct effects so a cross-screen key swap cannot round-trip.
|
||||
val lockEffects = effects.copy(
|
||||
blurPercentage = 31, darkenPercentage = 21, vignettePercentage = 41, grayscalePercentage = 51,
|
||||
enableVignette = false, enableDoubleTap = false, parallaxIntensity = 61
|
||||
)
|
||||
val liveEffects = effects.copy(
|
||||
blurPercentage = 32, darkenPercentage = 22, vignettePercentage = 42, grayscalePercentage = 52,
|
||||
enableGrayscale = false, enableChangeOnScreenOff = false, parallaxIntensity = 62
|
||||
)
|
||||
val full = ScheduleSettings(
|
||||
enableChanger = true, separateSchedules = true, shuffleEnabled = true,
|
||||
homeEnabled = true, lockEnabled = true, homeAlbumId = "home", lockAlbumId = "lock", liveAlbumId = "live",
|
||||
homeIntervalMinutes = 25, lockIntervalMinutes = 35, liveIntervalMinutes = 45,
|
||||
homeScalingType = ScalingType.FIT, lockScalingType = ScalingType.STRETCH, liveScalingType = ScalingType.NONE,
|
||||
homeScrollingEnabled = true, blurFitBackground = true, homeEffects = effects, lockEffects = lockEffects, liveEffects = liveEffects,
|
||||
adaptiveBrightness = true
|
||||
)
|
||||
preferences.updateScheduleSettings(full)
|
||||
assertEquals(full, preferences.getScheduleSettings())
|
||||
preferences.clearScheduleSettings()
|
||||
assertEquals(ScheduleSettings(), preferences.getScheduleSettings())
|
||||
assertEquals(appearance, preferences.getAppSettings())
|
||||
assertEquals(WallpaperMode.LIVE, preferences.getWallpaperMode())
|
||||
} finally {
|
||||
preferences.updateScheduleSettings(previousSettings)
|
||||
preferences.updateWallpaperMode(previousMode)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun clearingAnEmptyAlbumPreservesNewSelectionsAndOtherSettings() = runBlocking {
|
||||
val preferences = SettingsRepositoryImpl(ApplicationProvider.getApplicationContext<Context>())
|
||||
val previousSettings = preferences.getScheduleSettings()
|
||||
val previousMode = preferences.getWallpaperMode()
|
||||
try {
|
||||
preferences.updateWallpaperMode(WallpaperMode.STATIC)
|
||||
val settings = ScheduleSettings(enableChanger = true, homeEnabled = true, lockEnabled = true,
|
||||
homeAlbumId = "new-home", lockAlbumId = "lock", homeIntervalMinutes = 75)
|
||||
preferences.updateScheduleSettings(settings)
|
||||
preferences.clearEmptyAlbumSelection("old-home", ScreenType.HOME)
|
||||
assertEquals(settings, preferences.getScheduleSettings())
|
||||
preferences.clearEmptyAlbumSelection("new-home", ScreenType.HOME)
|
||||
assertEquals(settings.copy(homeAlbumId = null), preferences.getScheduleSettings())
|
||||
preferences.clearEmptyAlbumSelection("lock", ScreenType.LOCK)
|
||||
assertEquals(settings.copy(homeAlbumId = null, lockAlbumId = null, enableChanger = false), preferences.getScheduleSettings())
|
||||
} finally {
|
||||
preferences.updateScheduleSettings(previousSettings)
|
||||
preferences.updateWallpaperMode(previousMode)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentResolver
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EncryptedImageStoreInstrumentedTest {
|
||||
private val app = ApplicationProvider.getApplicationContext<Context>()
|
||||
private val directory = File(app.cacheDir, "encrypted-image-store-test").apply { mkdirs() }
|
||||
private val encryptedFile = File(directory, "image")
|
||||
private val provider = ImageProvider(encryptedFile)
|
||||
private val context = object : ContextWrapper(app) {
|
||||
override fun getNoBackupFilesDir(): File = directory
|
||||
override fun getContentResolver(): ContentResolver = ContentResolver.wrap(provider)
|
||||
}
|
||||
private val uri = Uri.parse("content://test/image")
|
||||
private val encrypted = (
|
||||
"53616c7465645f5f00010203040506075fccfb3397721c83694890dfe23e4516" +
|
||||
"7b69d90d234d801114bb019d584a6f47"
|
||||
).chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
|
||||
@After fun cleanup() {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun persistsEncryptedPassphraseAndDecryptsProviderStream() {
|
||||
encryptedFile.writeBytes(encrypted)
|
||||
val store = EncryptedImageStore(context)
|
||||
assertEquals(0, store.revision.value)
|
||||
assertFalse(store.hasPassphrase())
|
||||
assertThrows(MissingPassphraseException::class.java) { store.decrypt(uri) }
|
||||
store.setPassphrase("päss漢字")
|
||||
assertEquals(1, store.revision.value)
|
||||
|
||||
val stored = File(directory, "encrypted_image_passphrase").readBytes()
|
||||
assertFalse(stored.toString(Charsets.UTF_8).contains("päss漢字"))
|
||||
val reopened = EncryptedImageStore(context)
|
||||
assertTrue(reopened.hasPassphrase())
|
||||
assertArrayEquals(
|
||||
"Paperize test image\u0000".toByteArray() + byteArrayOf(0xff.toByte()),
|
||||
reopened.decrypt(uri)
|
||||
)
|
||||
reopened.setPassphrase("wrong")
|
||||
assertEquals(1, reopened.revision.value)
|
||||
assertThrows(IncorrectPassphraseException::class.java) { reopened.decrypt(uri) }
|
||||
reopened.clearPassphrase()
|
||||
assertEquals(2, reopened.revision.value)
|
||||
assertFalse(store.hasPassphrase())
|
||||
assertThrows(MissingPassphraseException::class.java) { reopened.decrypt(uri) }
|
||||
}
|
||||
|
||||
@Test fun rejectsTamperedStoredPassphrase() {
|
||||
val store = EncryptedImageStore(context)
|
||||
store.setPassphrase("secret")
|
||||
val file = File(directory, "encrypted_image_passphrase")
|
||||
file.writeBytes(file.readBytes().apply { this[lastIndex] = (last().toInt() xor 1).toByte() })
|
||||
assertThrows(PassphraseStorageException::class.java) { store.decrypt(uri) }
|
||||
}
|
||||
|
||||
private class ImageProvider(private val file: File) : ContentProvider() {
|
||||
override fun onCreate() = true
|
||||
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor =
|
||||
ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
|
||||
selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
||||
override fun getType(uri: Uri): String? = null
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?,
|
||||
selectionArgs: Array<out String>?): Int = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.Context
|
||||
import android.content.ContextWrapper
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import android.net.Uri
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.util.getDeviceScreenSize
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.service.livewallpaper.renderer.EncryptedImageLoader
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EncryptedRenderingInstrumentedTest {
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
private val directory = File(instrumentation.targetContext.cacheDir, "encrypted-render-${UUID.randomUUID()}")
|
||||
private val context = object : ContextWrapper(instrumentation.targetContext) {
|
||||
override fun getNoBackupFilesDir(): File = directory
|
||||
}
|
||||
private val encryptedFile = File(directory, "image.jpg_enc")
|
||||
private val uri = Uri.fromFile(encryptedFile)
|
||||
private val store = EncryptedImageStore(context)
|
||||
private val renderer = AndroidWallpaperRenderer(context, store)
|
||||
private val loader = EncryptedImageLoader(store, uri)
|
||||
private val wallpaper = Wallpaper(
|
||||
id = "image", albumId = "album", uri = uri.toString(),
|
||||
fileName = "image.jpg_enc", dateModified = 0
|
||||
)
|
||||
private val passphrase = "päss漢字"
|
||||
private lateinit var wrongPassphrase: String
|
||||
|
||||
@Before fun setup() {
|
||||
check(directory.mkdirs())
|
||||
val image = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)
|
||||
val jpeg = try {
|
||||
image.eraseColor(Color.rgb(220, 30, 40))
|
||||
ByteArrayOutputStream().use { output ->
|
||||
check(image.compress(Bitmap.CompressFormat.JPEG, 100, output))
|
||||
output.toByteArray()
|
||||
}
|
||||
} finally {
|
||||
image.recycle()
|
||||
}
|
||||
val encrypted = encryptTestJpeg(jpeg, passphrase)
|
||||
encryptedFile.writeBytes(encrypted)
|
||||
// CBC has no authentication; choose a wrong key that actually fails padding.
|
||||
wrongPassphrase = (0..100).asSequence().map { "wrong-$it" }.first { candidate ->
|
||||
try {
|
||||
decryptEncryptedImage(encrypted, candidate).fill(0)
|
||||
false
|
||||
} catch (_: IncorrectPassphraseException) {
|
||||
true
|
||||
}
|
||||
}
|
||||
store.setPassphrase(passphrase)
|
||||
}
|
||||
|
||||
@After fun cleanup() {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun rendersDecryptedJpegInStaticAndLivePaths() {
|
||||
val rendered = runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
|
||||
assertNotNull(rendered)
|
||||
checkNotNull(rendered)
|
||||
try {
|
||||
val screen = getDeviceScreenSize(context)
|
||||
assertEquals(screen.width, rendered.width)
|
||||
assertEquals(screen.height, rendered.height)
|
||||
assertRed(rendered)
|
||||
} finally {
|
||||
rendered.recycle()
|
||||
}
|
||||
|
||||
val loaded = loader.load(16, 16)
|
||||
assertNotNull(loaded)
|
||||
checkNotNull(loaded)
|
||||
try {
|
||||
assertEquals(16, loaded.width)
|
||||
assertEquals(16, loaded.height)
|
||||
assertRed(loaded)
|
||||
} finally {
|
||||
loaded.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun wrongOrMissingPassphraseFailsBothPaths() {
|
||||
store.setPassphrase(wrongPassphrase)
|
||||
assertThrows(IncorrectPassphraseException::class.java) {
|
||||
runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
|
||||
}
|
||||
assertNull(loader.load(16, 16))
|
||||
|
||||
store.clearPassphrase()
|
||||
assertThrows(MissingPassphraseException::class.java) {
|
||||
runBlocking { renderer.render(wallpaper, ScreenType.HOME, ScheduleSettings()) }
|
||||
}
|
||||
assertNull(loader.load(16, 16))
|
||||
}
|
||||
|
||||
private fun assertRed(bitmap: Bitmap) {
|
||||
val pixel = bitmap.getPixel(bitmap.width / 2, bitmap.height / 2)
|
||||
assertTrue(Color.red(pixel) > 180)
|
||||
assertTrue(Color.green(pixel) < 70)
|
||||
assertTrue(Color.blue(pixel) < 80)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun encryptTestJpeg(jpeg: ByteArray, passphrase: String): ByteArray {
|
||||
val salt = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7)
|
||||
val spec = PBEKeySpec(passphrase.toCharArray(), salt, 10_000, 384)
|
||||
val material = try {
|
||||
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
return try {
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(material, 0, 32, "AES"), IvParameterSpec(material, 32, 16))
|
||||
"Salted__".toByteArray(Charsets.US_ASCII) + salt + cipher.doFinal(jpeg)
|
||||
} finally {
|
||||
material.fill(0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.anthonyla.paperize.domain.model
|
||||
|
||||
import com.anthonyla.paperize.testFolder
|
||||
import com.anthonyla.paperize.testWallpaper
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class DisplayNameInstrumentedTest {
|
||||
@Test fun documentNamesDecodeEscapesAndPreserveLiteralPlusSigns() {
|
||||
mapOf(
|
||||
"primary%3APictures%2FSummer%20%2B%20Sun.jpg" to "Summer + Sun.jpg",
|
||||
"primary%3APictures" to "Pictures",
|
||||
"Pictures/Summer+Sun.jpg" to "Summer+Sun.jpg",
|
||||
"" to ""
|
||||
).forEach { (stored, displayed) ->
|
||||
assertEquals(displayed, testFolder().copy(name = stored).displayName)
|
||||
assertEquals(displayed, testWallpaper().copy(fileName = stored).displayFileName)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package com.anthonyla.paperize.presentation
|
||||
|
||||
import com.anthonyla.paperize.testAlbumSummary
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Color
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.graphics.toPixelMap
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.presentation.screens.library.components.AlbumItem
|
||||
import java.io.File
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.presentation.screens.wallpaper.components.TimeIntervalPicker
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.anthonyla.paperize.R
|
||||
import com.anthonyla.paperize.presentation.common.theme.PaperizeTheme
|
||||
import com.anthonyla.paperize.presentation.common.components.SortBottomSheet
|
||||
import com.anthonyla.paperize.presentation.common.components.SortOption
|
||||
import com.anthonyla.paperize.presentation.common.components.WallpaperItem
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import com.anthonyla.paperize.presentation.screens.library.LibraryScreen
|
||||
import com.anthonyla.paperize.presentation.screens.album_view.components.AlbumViewTopBar
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import androidx.compose.ui.semantics.SemanticsActions
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.WallpaperEffects
|
||||
import com.anthonyla.paperize.presentation.screens.wallpaper.WallpaperScreen
|
||||
|
||||
class AlbumUiInstrumentedTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
|
||||
@Test fun effectSlidersRouteDraftChangesToEnabledScreensAndLiveMode() {
|
||||
val settings = mutableStateOf(ScheduleSettings(
|
||||
homeEnabled = true, lockEnabled = true,
|
||||
homeEffects = WallpaperEffects(enableBlur = true, blurPercentage = 45),
|
||||
lockEffects = WallpaperEffects(enableBlur = true, blurPercentage = 65),
|
||||
liveEffects = WallpaperEffects(enableBlur = true, blurPercentage = 80)
|
||||
))
|
||||
val mode = mutableStateOf(WallpaperMode.STATIC)
|
||||
var latest = settings.value
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
WallpaperScreen(
|
||||
albums = emptyList(), persistedScheduleSettings = settings.value,
|
||||
animate = true, wallpaperMode = mode.value,
|
||||
onToggleChanger = {}, onSelectAlbum = { _, _ -> },
|
||||
onUpdateScheduleSettings = { latest = it },
|
||||
onUpdateScheduleSettingsDebounced = { latest = it },
|
||||
onChangeWallpaperNow = {}, homeWallpaper = null, lockWallpaper = null, onRemoveWallpaper = {}
|
||||
)
|
||||
}
|
||||
}
|
||||
fun slide(index: Int, percentage: Float) {
|
||||
compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress))[index]
|
||||
.performScrollTo()
|
||||
.performSemanticsAction(SemanticsActions.SetProgress) { it(percentage) }
|
||||
}
|
||||
slide(0, 20f)
|
||||
slide(1, 75f)
|
||||
compose.runOnIdle {
|
||||
assertEquals(20, latest.homeEffects.blurPercentage)
|
||||
assertEquals(75, latest.lockEffects.blurPercentage)
|
||||
settings.value = latest.copy(homeEnabled = false)
|
||||
}
|
||||
slide(0, 55f)
|
||||
compose.runOnIdle {
|
||||
assertEquals(20, latest.homeEffects.blurPercentage)
|
||||
assertEquals(55, latest.lockEffects.blurPercentage)
|
||||
settings.value = latest
|
||||
mode.value = WallpaperMode.LIVE
|
||||
}
|
||||
slide(0, 40f)
|
||||
compose.runOnIdle {
|
||||
assertEquals(20, latest.homeEffects.blurPercentage)
|
||||
assertEquals(55, latest.lockEffects.blurPercentage)
|
||||
assertEquals(40, latest.liveEffects.blurPercentage)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun failedAlbumCreationKeepsNameAndAllowsRetryAfterPendingSave() {
|
||||
val pending = CompletableDeferred<Int?>()
|
||||
var attempts = 0
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
LibraryScreen(emptyList(), {}, { name, encrypted ->
|
||||
assertEquals("Mountains", name)
|
||||
assertTrue(encrypted)
|
||||
attempts++
|
||||
if (attempts == 1) pending.await() else null
|
||||
})
|
||||
}
|
||||
}
|
||||
compose.onNodeWithContentDescription(context.getString(R.string.add_album)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.album_name)).performTextInput("Mountains")
|
||||
compose.onNodeWithText(context.getString(R.string.encrypted_album)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.save)).performClick().assertIsNotEnabled()
|
||||
compose.runOnIdle { pending.complete(R.string.album_create_failed) }
|
||||
compose.onNodeWithText(context.getString(R.string.album_create_failed)).assertIsDisplayed()
|
||||
compose.onNodeWithText(context.getString(R.string.album_name)).assertTextContains("Mountains")
|
||||
compose.onNodeWithText(context.getString(R.string.save)).performClick()
|
||||
compose.onNodeWithText(context.getString(R.string.album_name)).assertDoesNotExist()
|
||||
compose.runOnIdle { assertEquals(2, attempts) }
|
||||
}
|
||||
|
||||
@Test fun albumOptionsExposeActionsAndDisableRescanWithoutFolders() {
|
||||
val hasFolders = mutableStateOf(false)
|
||||
var action = ""
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
AlbumViewTopBar(
|
||||
title = "Album", isSelectionMode = false, selectedCount = 0, allSelected = false,
|
||||
onBackClick = {}, onSortClick = {}, onDeleteAlbum = { action = "delete" },
|
||||
onRenameAlbum = { action = "rename" }, onFilterAlbum = null, onRefreshFolders = { action = "refresh" },
|
||||
albumActionsEnabled = true, hasFolders = hasFolders.value,
|
||||
onSelectAll = {}, onDeleteSelected = {}, onClearSelection = {}
|
||||
)
|
||||
}
|
||||
}
|
||||
fun openMenu() = compose.onNodeWithContentDescription(context.getString(R.string.album_menu)).performClick()
|
||||
openMenu()
|
||||
compose.onNodeWithText(context.getString(R.string.refresh_album_folders)).assertIsNotEnabled()
|
||||
compose.onNodeWithText(context.getString(R.string.rename_album)).performClick()
|
||||
compose.runOnIdle { assertEquals("rename", action); hasFolders.value = true }
|
||||
openMenu()
|
||||
compose.onNodeWithText(context.getString(R.string.refresh_album_folders)).performClick()
|
||||
compose.runOnIdle { assertEquals("refresh", action) }
|
||||
openMenu()
|
||||
compose.onNodeWithText(context.getString(R.string.delete_album)).performClick()
|
||||
compose.runOnIdle { assertEquals("delete", action) }
|
||||
}
|
||||
|
||||
@Test fun sortSheetExposesCurrentSelectionAndAppliesNewChoice() {
|
||||
var chosen: SortOption? = null
|
||||
var dismissed = false
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
SortBottomSheet(SortOption.DATE_ADDED_DESC, { chosen = it }, { dismissed = true })
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText(context.getString(R.string.sort_date_added_desc)).assertIsSelected()
|
||||
compose.onNodeWithText(context.getString(R.string.sort_name_asc)).performClick()
|
||||
compose.runOnIdle { assertEquals(SortOption.NAME_ASC, chosen); assertTrue(dismissed) }
|
||||
}
|
||||
|
||||
@Test fun wallpaperThumbnailsExposeNameAndSelection() {
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
WallpaperItem("content://test/image", "Mountains.jpg", true, true, {}, {}, Modifier.size(160.dp))
|
||||
}
|
||||
}
|
||||
compose.onNodeWithContentDescription("Mountains.jpg")
|
||||
.assertIsSelected().assertHasClickAction()
|
||||
}
|
||||
@Test fun albumCoverLoadsThroughCoilAndFallsBackForMissingFiles() {
|
||||
val file = File.createTempFile("album-cover", ".png", context.cacheDir)
|
||||
val bitmap = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888)
|
||||
bitmap.eraseColor(Color.RED)
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
bitmap.recycle()
|
||||
val uri = mutableStateOf<String?>(file.toURI().toString())
|
||||
try {
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
AlbumItem(testAlbumSummary("album").copy(name = "Cover", coverUri = uri.value), {}, Modifier.size(180.dp))
|
||||
}
|
||||
}
|
||||
fun centerColor(): Int {
|
||||
val pixels = compose.onNodeWithContentDescription("Cover").captureToImage().toPixelMap()
|
||||
return pixels[pixels.width / 2, pixels.height / 2].toArgb()
|
||||
}
|
||||
compose.waitUntil(5_000) { centerColor() == Color.RED }
|
||||
compose.runOnIdle { uri.value = File(context.cacheDir, "missing-cover.png").toURI().toString() }
|
||||
compose.waitUntil(5_000) { centerColor() != Color.RED }
|
||||
compose.onNodeWithContentDescription("Cover").assertIsDisplayed()
|
||||
} finally {
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun intervalEditsDebounceAndExternalValuesCancelPendingEdits() {
|
||||
val minutes = mutableIntStateOf(60)
|
||||
val changes = mutableListOf<Int>()
|
||||
compose.setContent {
|
||||
PaperizeTheme(false, false) {
|
||||
TimeIntervalPicker("Interval", minutes.intValue, { changes.add(it) })
|
||||
}
|
||||
}
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.mainClock.advanceTimeBy(Constants.DEBOUNCE_DELAY_MS + 50)
|
||||
compose.runOnIdle { assertTrue(changes.isEmpty()) }
|
||||
compose.onNodeWithText(context.getString(R.string.hours_txt)).performTextReplacement("0")
|
||||
compose.mainClock.advanceTimeBy(100)
|
||||
compose.onNodeWithText(context.getString(R.string.mins)).performTextReplacement("1")
|
||||
compose.mainClock.advanceTimeBy(Constants.DEBOUNCE_DELAY_MS + 50)
|
||||
compose.runOnIdle { assertEquals(listOf(Constants.MIN_INTERVAL_MINUTES), changes) }
|
||||
|
||||
compose.onNodeWithText(context.getString(R.string.mins)).performTextReplacement("30")
|
||||
compose.runOnIdle { minutes.intValue = 120 }
|
||||
compose.mainClock.advanceTimeBy(Constants.DEBOUNCE_DELAY_MS + 50)
|
||||
compose.runOnIdle { assertEquals(1, changes.size) }
|
||||
compose.onNodeWithText(context.getString(R.string.hours_txt)).assertTextContains("2")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.anthonyla.paperize.presentation
|
||||
|
||||
import android.content.ContextWrapper
|
||||
import android.graphics.Bitmap
|
||||
import android.net.Uri
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import coil3.request.CachePolicy
|
||||
import coil3.request.ImageRequest
|
||||
import com.anthonyla.paperize.data.source.EncryptedImageStore
|
||||
import com.anthonyla.paperize.data.source.encryptTestJpeg
|
||||
import com.anthonyla.paperize.presentation.common.components.encryptedPreviewImageRequest
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class EncryptedPreviewInstrumentedTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
private val directory = File(instrumentation.targetContext.cacheDir, "encrypted-preview-${UUID.randomUUID()}")
|
||||
private val context = object : ContextWrapper(instrumentation.targetContext) {
|
||||
override fun getNoBackupFilesDir(): File = directory
|
||||
}
|
||||
private val image = File(directory, "image.jpg_enc")
|
||||
private val store = EncryptedImageStore(context)
|
||||
|
||||
@Before fun setup() {
|
||||
check(directory.mkdirs())
|
||||
val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)
|
||||
val jpeg = try {
|
||||
ByteArrayOutputStream().use { output ->
|
||||
check(bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output))
|
||||
output.toByteArray()
|
||||
}
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
image.writeBytes(encryptTestJpeg(jpeg, "test"))
|
||||
store.setPassphrase("test")
|
||||
}
|
||||
|
||||
@After fun cleanup() {
|
||||
directory.deleteRecursively()
|
||||
}
|
||||
|
||||
@Test fun disablingPreviewsDropsTheDecryptedRequestAndNeverCachesIt() {
|
||||
val enabled = mutableStateOf(true)
|
||||
val request = AtomicReference<ImageRequest?>()
|
||||
compose.setContent {
|
||||
CompositionLocalProvider(LocalContext provides context) {
|
||||
val value = encryptedPreviewImageRequest(
|
||||
Uri.fromFile(image).toString(), 32, 32, false, enabled.value, store
|
||||
)
|
||||
SideEffect { request.set(value) }
|
||||
}
|
||||
}
|
||||
compose.waitUntil(20_000) { request.get() != null }
|
||||
val decrypted = checkNotNull(request.get())
|
||||
assertTrue(decrypted.data is Bitmap)
|
||||
assertEquals(CachePolicy.DISABLED, decrypted.memoryCachePolicy)
|
||||
assertEquals(CachePolicy.DISABLED, decrypted.diskCachePolicy)
|
||||
compose.runOnIdle { enabled.value = false }
|
||||
compose.waitUntil(20_000) { request.get() == null }
|
||||
compose.runOnIdle { enabled.value = true }
|
||||
compose.waitUntil(20_000) { request.get() != null }
|
||||
}
|
||||
|
||||
@Test fun missingDocumentMetadataStillLoadsTheOriginalUri() {
|
||||
val uri = Uri.parse("content://missing.provider/image")
|
||||
val request = AtomicReference<ImageRequest?>()
|
||||
compose.setContent {
|
||||
CompositionLocalProvider(LocalContext provides context) {
|
||||
val value = encryptedPreviewImageRequest(uri.toString(), 32, 32, false, false, store)
|
||||
SideEffect { request.set(value) }
|
||||
}
|
||||
}
|
||||
compose.waitUntil(20_000) { request.get() != null }
|
||||
assertEquals(uri, checkNotNull(request.get()).data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
package com.anthonyla.paperize.service.livewallpaper.renderer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.opengl.EGL14
|
||||
import android.opengl.EGLConfig
|
||||
import android.opengl.EGLContext
|
||||
import android.opengl.EGLDisplay
|
||||
import android.opengl.EGLSurface
|
||||
import android.opengl.GLES20
|
||||
import android.opengl.GLUtils
|
||||
import android.opengl.Matrix
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.anthonyla.paperize.service.livewallpaper.gl.GLUtil
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.nio.FloatBuffer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class LiveWallpaperShaderInstrumentedTest {
|
||||
private lateinit var display: EGLDisplay
|
||||
private lateinit var context: EGLContext
|
||||
private lateinit var surface: EGLSurface
|
||||
|
||||
@Before
|
||||
fun createGlContext() {
|
||||
display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
|
||||
assertTrue(display != EGL14.EGL_NO_DISPLAY)
|
||||
assertTrue(EGL14.eglInitialize(display, IntArray(2), 0, IntArray(2), 0))
|
||||
|
||||
val configs = arrayOfNulls<EGLConfig>(1)
|
||||
val configCount = IntArray(1)
|
||||
assertTrue(
|
||||
EGL14.eglChooseConfig(
|
||||
display,
|
||||
intArrayOf(
|
||||
EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT,
|
||||
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
|
||||
EGL14.EGL_RED_SIZE, 8,
|
||||
EGL14.EGL_GREEN_SIZE, 8,
|
||||
EGL14.EGL_BLUE_SIZE, 8,
|
||||
EGL14.EGL_ALPHA_SIZE, 8,
|
||||
EGL14.EGL_NONE
|
||||
),
|
||||
0,
|
||||
configs,
|
||||
0,
|
||||
configs.size,
|
||||
configCount,
|
||||
0
|
||||
)
|
||||
)
|
||||
val config = requireNotNull(configs.first())
|
||||
context = EGL14.eglCreateContext(
|
||||
display,
|
||||
config,
|
||||
EGL14.EGL_NO_CONTEXT,
|
||||
intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE),
|
||||
0
|
||||
)
|
||||
surface = EGL14.eglCreatePbufferSurface(
|
||||
display,
|
||||
config,
|
||||
intArrayOf(EGL14.EGL_WIDTH, SIZE, EGL14.EGL_HEIGHT, SIZE, EGL14.EGL_NONE),
|
||||
0
|
||||
)
|
||||
assertTrue(EGL14.eglMakeCurrent(display, surface, surface, context))
|
||||
GLES20.glViewport(0, 0, SIZE, SIZE)
|
||||
GLES20.glDisable(GLES20.GL_BLEND)
|
||||
}
|
||||
|
||||
@After
|
||||
fun destroyGlContext() {
|
||||
EGL14.eglMakeCurrent(
|
||||
display,
|
||||
EGL14.EGL_NO_SURFACE,
|
||||
EGL14.EGL_NO_SURFACE,
|
||||
EGL14.EGL_NO_CONTEXT
|
||||
)
|
||||
EGL14.eglDestroySurface(display, surface)
|
||||
EGL14.eglDestroyContext(display, context)
|
||||
EGL14.eglTerminate(display)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wallpaperConfigSupportsEs2WindowSurfaces() {
|
||||
val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
|
||||
val eglDisplay = egl.eglGetCurrentDisplay()
|
||||
val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
|
||||
.chooseConfig(egl, eglDisplay)
|
||||
val attribute = IntArray(1)
|
||||
assertTrue(egl.eglGetConfigAttrib(eglDisplay, config, EGL14.EGL_RENDERABLE_TYPE, attribute))
|
||||
assertTrue(attribute[0] and EGL14.EGL_OPENGL_ES2_BIT != 0)
|
||||
assertTrue(egl.eglGetConfigAttrib(eglDisplay, config, EGL14.EGL_SURFACE_TYPE, attribute))
|
||||
assertTrue(attribute[0] and EGL14.EGL_WINDOW_BIT != 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rendererSurvivesSupersededUploadsCrossfadeResizeAndContextLoss() {
|
||||
val app = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
|
||||
var renderRequests = 0
|
||||
val renderer = PaperizeWallpaperRenderer(app, object : PaperizeWallpaperRenderer.Callbacks {
|
||||
override fun queueEventOnGlThread(event: () -> Unit): Boolean = uploads.offer(event)
|
||||
override fun requestRender() { renderRequests++ }
|
||||
})
|
||||
val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
|
||||
val gl = egl.eglGetCurrentContext().gl as javax.microedition.khronos.opengles.GL10
|
||||
val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
|
||||
.chooseConfig(egl, egl.eglGetCurrentDisplay())
|
||||
val file = java.io.File.createTempFile("live-renderer", ".png", app.cacheDir)
|
||||
val replacement = java.io.File.createTempFile("live-renderer-next", ".png", app.cacheDir)
|
||||
try {
|
||||
val bitmap = solidBitmap(Color.WHITE)
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
bitmap.recycle()
|
||||
val loader = ContentUriImageLoader(app.contentResolver, android.net.Uri.fromFile(file))
|
||||
renderer.onSurfaceCreated(gl, config)
|
||||
renderer.onSurfaceChanged(gl, SIZE, SIZE)
|
||||
renderer.queueWallpaper(loader)
|
||||
val staleUpload = checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
renderer.queueWallpaper(loader)
|
||||
val activeUpload = checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
staleUpload()
|
||||
assertEquals(0, renderRequests)
|
||||
activeUpload()
|
||||
renderer.onDrawFrame(gl)
|
||||
android.os.SystemClock.sleep(com.anthonyla.paperize.core.constants.Constants.CROSSFADE_DURATION_MS.toLong() + 50L)
|
||||
val requestsBeforeFinalFrame = renderRequests
|
||||
renderer.onDrawFrame(gl)
|
||||
assertEquals(requestsBeforeFinalFrame, renderRequests)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
|
||||
|
||||
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(
|
||||
enableBlur = true, blurPercentage = 50
|
||||
))
|
||||
renderer.onDrawFrame(gl)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
|
||||
|
||||
val red = solidBitmap(Color.RED)
|
||||
replacement.outputStream().use { red.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
red.recycle()
|
||||
renderer.queueWallpaper(ContentUriImageLoader(app.contentResolver, android.net.Uri.fromFile(replacement)))
|
||||
val uploadBeforeResize = checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS))
|
||||
renderer.onSurfaceChanged(gl, SIZE, SIZE - 2)
|
||||
uploadBeforeResize()
|
||||
checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
|
||||
renderer.onDrawFrame(gl)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
|
||||
assertTrue(Color.green(readPixel(SIZE / 2, SIZE / 2)) <= 2)
|
||||
|
||||
destroyGlContext()
|
||||
createGlContext()
|
||||
renderer.onSurfaceCreated(gl, config)
|
||||
renderer.onSurfaceChanged(gl, SIZE, SIZE)
|
||||
checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
|
||||
renderer.onDrawFrame(gl)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) >= 253)
|
||||
assertTrue(Color.green(readPixel(SIZE / 2, SIZE / 2)) <= 2)
|
||||
GLUtil.checkGLError("recreated wallpaper surface")
|
||||
} finally {
|
||||
renderer.cancelLoading()
|
||||
file.delete()
|
||||
replacement.delete()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blurredFitBackgroundFillsTheBarsTheRightWayUpWithAndWithoutBlur() {
|
||||
val app = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
|
||||
val renderer = PaperizeWallpaperRenderer(app, object : PaperizeWallpaperRenderer.Callbacks {
|
||||
override fun queueEventOnGlThread(event: () -> Unit): Boolean = uploads.offer(event)
|
||||
override fun requestRender() = Unit
|
||||
})
|
||||
val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
|
||||
val gl = egl.eglGetCurrentContext().gl as javax.microedition.khronos.opengles.GL10
|
||||
val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
|
||||
.chooseConfig(egl, egl.eglGetCurrentDisplay())
|
||||
val file = java.io.File.createTempFile("fit-backdrop", ".png", app.cacheDir)
|
||||
try {
|
||||
// Wide image, red over blue, so Fit leaves bars above and below it.
|
||||
val bitmap = Bitmap.createBitmap(SIZE * 2, SIZE, Bitmap.Config.ARGB_8888).apply {
|
||||
eraseColor(Color.BLUE)
|
||||
Canvas(this).drawRect(0f, 0f, SIZE * 2f, SIZE / 2f, android.graphics.Paint().apply { color = Color.RED })
|
||||
}
|
||||
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
bitmap.recycle()
|
||||
renderer.onSurfaceCreated(gl, config)
|
||||
renderer.onSurfaceChanged(gl, SIZE, SIZE)
|
||||
renderer.updateScalingType(com.anthonyla.paperize.core.ScalingType.FIT)
|
||||
renderer.queueWallpaper(
|
||||
ContentUriImageLoader(
|
||||
app.contentResolver,
|
||||
android.net.Uri.fromFile(file),
|
||||
com.anthonyla.paperize.core.ScalingType.FIT
|
||||
),
|
||||
skipCrossfade = true
|
||||
)
|
||||
checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
|
||||
|
||||
renderer.onDrawFrame(gl)
|
||||
assertEquals(Color.BLACK, readPixel(SIZE / 2, SIZE - 2))
|
||||
|
||||
renderer.updateBlurFitBackground(true)
|
||||
renderer.onDrawFrame(gl)
|
||||
assertTopRedBottomBlue()
|
||||
|
||||
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(enableBlur = true, blurPercentage = 10))
|
||||
renderer.onDrawFrame(gl)
|
||||
assertTopRedBottomBlue()
|
||||
|
||||
// A vignette over the whole screen leaves no seam where the picture meets the backdrop.
|
||||
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(enableVignette = true, vignettePercentage = 100))
|
||||
renderer.onDrawFrame(gl)
|
||||
val inside = Color.red(readPixel(SIZE / 2, SIZE * 3 / 4 - 1))
|
||||
val outside = Color.red(readPixel(SIZE / 2, SIZE * 3 / 4 + 1))
|
||||
assertTrue("inside=$inside outside=$outside", kotlin.math.abs(inside - outside) <= 20)
|
||||
GLUtil.checkGLError("blurred fit background")
|
||||
} finally {
|
||||
renderer.cancelLoading()
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
// glReadPixels counts rows from the bottom of the surface.
|
||||
private fun assertTopRedBottomBlue() {
|
||||
val top = readPixel(SIZE / 2, SIZE - 2)
|
||||
val bottom = readPixel(SIZE / 2, 1)
|
||||
assertTrue("Top bar ${Integer.toHexString(top)}", Color.red(top) > 200 && Color.blue(top) < 50)
|
||||
assertTrue("Bottom bar ${Integer.toHexString(bottom)}", Color.blue(bottom) > 200 && Color.red(bottom) < 50)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveColorEffectsChangeRenderedPixels() {
|
||||
val sourceColor = Color.rgb(200, 100, 40)
|
||||
val texture = createTexture(solidBitmap(sourceColor))
|
||||
val program = GLUtil.createProgram(GLShaders.VERTEX_SHADER, GLShaders.EFFECTS_FRAGMENT_SHADER)
|
||||
|
||||
try {
|
||||
drawEffects(program, texture)
|
||||
val baseline = readPixel(SIZE / 2, SIZE / 2)
|
||||
assertTrue(Color.red(baseline) in 195..205)
|
||||
assertTrue(Color.green(baseline) in 95..105)
|
||||
|
||||
drawEffects(program, texture, darken = 1f)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) <= 2)
|
||||
|
||||
drawEffects(program, texture, grayscale = 1f)
|
||||
val gray = readPixel(SIZE / 2, SIZE / 2)
|
||||
assertTrue(kotlin.math.abs(Color.red(gray) - Color.green(gray)) <= 2)
|
||||
assertTrue(kotlin.math.abs(Color.green(gray) - Color.blue(gray)) <= 2)
|
||||
|
||||
drawEffects(program, texture, adaptiveBrightness = 0.5f)
|
||||
val dimmed = readPixel(SIZE / 2, SIZE / 2)
|
||||
assertTrue(Color.red(dimmed) in 95..105)
|
||||
|
||||
drawEffects(program, texture, vignette = 1f)
|
||||
val center = Color.red(readPixel(SIZE / 2, SIZE / 2))
|
||||
val corner = Color.red(readPixel(1, 1))
|
||||
assertTrue("Expected vignette corner $corner below center $center", corner < center)
|
||||
} finally {
|
||||
GLES20.glDeleteProgram(program)
|
||||
GLES20.glDeleteTextures(1, intArrayOf(texture), 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveBlurShadersSoftenHorizontalAndVerticalBoundaries() {
|
||||
val horizontal = boundaryBitmap(horizontalBoundary = true)
|
||||
val vertical = boundaryBitmap(horizontalBoundary = false)
|
||||
val horizontalTexture = createTexture(horizontal)
|
||||
val verticalTexture = createTexture(vertical)
|
||||
|
||||
val blurProgram = GLUtil.createProgram(
|
||||
GLShaders.VERTEX_SHADER,
|
||||
GLShaders.BLUR_FRAGMENT_SHADER
|
||||
)
|
||||
try {
|
||||
drawBlur(blurProgram, horizontalTexture, 1f, 0f)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) in 10..245)
|
||||
|
||||
drawBlur(blurProgram, verticalTexture, 0f, 1f)
|
||||
assertTrue(Color.red(readPixel(SIZE / 2, SIZE / 2)) in 10..245)
|
||||
} finally {
|
||||
GLES20.glDeleteProgram(blurProgram)
|
||||
GLES20.glDeleteTextures(2, intArrayOf(horizontalTexture, verticalTexture), 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun liveBlurSpreadsAnEdgeAsFarAsStaticBlur() {
|
||||
val app = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
val uploads = java.util.concurrent.LinkedBlockingQueue<() -> Unit>()
|
||||
val renderer = PaperizeWallpaperRenderer(app, object : PaperizeWallpaperRenderer.Callbacks {
|
||||
override fun queueEventOnGlThread(event: () -> Unit): Boolean = uploads.offer(event)
|
||||
override fun requestRender() = Unit
|
||||
})
|
||||
val egl = javax.microedition.khronos.egl.EGLContext.getEGL() as javax.microedition.khronos.egl.EGL10
|
||||
val gl = egl.eglGetCurrentContext().gl as javax.microedition.khronos.opengles.GL10
|
||||
val config = com.anthonyla.paperize.service.livewallpaper.gl.WallpaperEglConfigChooser()
|
||||
.chooseConfig(egl, egl.eglGetCurrentDisplay())
|
||||
val file = java.io.File.createTempFile("blur-edge", ".png", app.cacheDir)
|
||||
val static = com.anthonyla.paperize.core.util.processBitmap(
|
||||
boundaryBitmap(horizontalBoundary = true), enableBlur = true, blurPercent = 100
|
||||
)
|
||||
try {
|
||||
val edge = boundaryBitmap(horizontalBoundary = true)
|
||||
file.outputStream().use { edge.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
edge.recycle()
|
||||
renderer.onSurfaceCreated(gl, config)
|
||||
renderer.onSurfaceChanged(gl, SIZE, SIZE)
|
||||
renderer.updateEffects(com.anthonyla.paperize.domain.model.WallpaperEffects(enableBlur = true, blurPercentage = 100))
|
||||
renderer.queueWallpaper(
|
||||
ContentUriImageLoader(app.contentResolver, android.net.Uri.fromFile(file)),
|
||||
skipCrossfade = true
|
||||
)
|
||||
checkNotNull(uploads.poll(5, java.util.concurrent.TimeUnit.SECONDS)).invoke()
|
||||
renderer.onDrawFrame(gl)
|
||||
|
||||
for (x in listOf(20, 24, 28, 36, 40, 44)) {
|
||||
val live = Color.red(readPixel(x, SIZE / 2))
|
||||
val expected = Color.red(static.getPixel(x, SIZE / 2))
|
||||
assertTrue("x=$x live=$live static=$expected", kotlin.math.abs(live - expected) <= 16)
|
||||
}
|
||||
} finally {
|
||||
renderer.cancelLoading()
|
||||
static.recycle()
|
||||
file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun drawEffects(
|
||||
program: Int,
|
||||
texture: Int,
|
||||
darken: Float = 0f,
|
||||
vignette: Float = 0f,
|
||||
grayscale: Float = 0f,
|
||||
adaptiveBrightness: Float = 1f
|
||||
) {
|
||||
prepareDraw(program, texture)
|
||||
GLES20.glUniform1f(GLES20.glGetUniformLocation(program, "u_alpha"), 1f)
|
||||
GLES20.glUniform1f(GLES20.glGetUniformLocation(program, "u_darkenFactor"), darken)
|
||||
GLES20.glUniform1f(GLES20.glGetUniformLocation(program, "u_vignetteFactor"), vignette)
|
||||
GLES20.glUniform1f(GLES20.glGetUniformLocation(program, "u_grayscaleFactor"), grayscale)
|
||||
GLES20.glUniform1f(
|
||||
GLES20.glGetUniformLocation(program, "u_adaptiveBrightnessFactor"),
|
||||
adaptiveBrightness
|
||||
)
|
||||
finishDraw(program)
|
||||
}
|
||||
|
||||
private fun drawBlur(program: Int, texture: Int, x: Float, y: Float) {
|
||||
prepareDraw(program, texture)
|
||||
GLES20.glUniform2f(GLES20.glGetUniformLocation(program, "u_resolution"), SIZE.toFloat(), SIZE.toFloat())
|
||||
GLES20.glUniform1f(GLES20.glGetUniformLocation(program, "u_blurRadius"), 4f)
|
||||
GLES20.glUniform2f(GLES20.glGetUniformLocation(program, "u_direction"), x, y)
|
||||
finishDraw(program)
|
||||
}
|
||||
|
||||
private fun prepareDraw(program: Int, texture: Int) {
|
||||
GLES20.glClearColor(0f, 0f, 0f, 1f)
|
||||
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
|
||||
GLES20.glUseProgram(program)
|
||||
GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture)
|
||||
GLES20.glUniform1i(GLES20.glGetUniformLocation(program, "u_texture"), 0)
|
||||
|
||||
val identity = FloatArray(16).also { Matrix.setIdentityM(it, 0) }
|
||||
GLES20.glUniformMatrix4fv(
|
||||
GLES20.glGetUniformLocation(program, "u_mvpMatrix"),
|
||||
1,
|
||||
false,
|
||||
identity,
|
||||
0
|
||||
)
|
||||
|
||||
val position = GLES20.glGetAttribLocation(program, "a_position")
|
||||
val textureCoordinate = GLES20.glGetAttribLocation(program, "a_texCoord")
|
||||
GLES20.glEnableVertexAttribArray(position)
|
||||
GLES20.glEnableVertexAttribArray(textureCoordinate)
|
||||
GLES20.glVertexAttribPointer(position, 2, GLES20.GL_FLOAT, false, 0, floatBuffer(VERTICES))
|
||||
GLES20.glVertexAttribPointer(
|
||||
textureCoordinate,
|
||||
2,
|
||||
GLES20.GL_FLOAT,
|
||||
false,
|
||||
0,
|
||||
floatBuffer(TEXTURE_COORDINATES)
|
||||
)
|
||||
}
|
||||
|
||||
private fun finishDraw(program: Int) {
|
||||
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
|
||||
GLES20.glFinish()
|
||||
GLES20.glDisableVertexAttribArray(GLES20.glGetAttribLocation(program, "a_position"))
|
||||
GLES20.glDisableVertexAttribArray(GLES20.glGetAttribLocation(program, "a_texCoord"))
|
||||
GLUtil.checkGLError("live wallpaper shader draw")
|
||||
}
|
||||
|
||||
private fun createTexture(bitmap: Bitmap): Int {
|
||||
val texture = IntArray(1)
|
||||
GLES20.glGenTextures(1, texture, 0)
|
||||
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0])
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
|
||||
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
|
||||
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0)
|
||||
if (!bitmap.isRecycled) bitmap.recycle()
|
||||
return texture[0]
|
||||
}
|
||||
|
||||
private fun readPixel(x: Int, y: Int): Int {
|
||||
val buffer = ByteBuffer.allocateDirect(4)
|
||||
GLES20.glReadPixels(x, y, 1, 1, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer)
|
||||
return Color.argb(
|
||||
buffer.get(3).toInt() and 0xff,
|
||||
buffer.get(0).toInt() and 0xff,
|
||||
buffer.get(1).toInt() and 0xff,
|
||||
buffer.get(2).toInt() and 0xff
|
||||
)
|
||||
}
|
||||
|
||||
private fun solidBitmap(color: Int): Bitmap =
|
||||
Bitmap.createBitmap(SIZE, SIZE, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }
|
||||
|
||||
private fun boundaryBitmap(horizontalBoundary: Boolean): Bitmap =
|
||||
Bitmap.createBitmap(SIZE, SIZE, Bitmap.Config.ARGB_8888).apply {
|
||||
for (y in 0 until SIZE) {
|
||||
for (x in 0 until SIZE) {
|
||||
val white = if (horizontalBoundary) x >= SIZE / 2 else y >= SIZE / 2
|
||||
setPixel(x, y, if (white) Color.WHITE else Color.BLACK)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun floatBuffer(values: FloatArray): FloatBuffer =
|
||||
ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
.asFloatBuffer()
|
||||
.apply {
|
||||
put(values)
|
||||
position(0)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val SIZE = 64
|
||||
val VERTICES = floatArrayOf(-1f, -1f, 1f, -1f, -1f, 1f, 1f, 1f)
|
||||
val TEXTURE_COORDINATES = floatArrayOf(0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.anthonyla.paperize.service.worker
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.impl.WorkManagerImpl
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class WallpaperSchedulerInstrumentedTest {
|
||||
private val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
private val workManager = WorkManager.getInstance(context) as WorkManagerImpl
|
||||
private val scheduler = WallpaperScheduler(context)
|
||||
private val targets = mapOf(
|
||||
ScreenType.HOME to Constants.WORK_NAME_HOME,
|
||||
ScreenType.LOCK to Constants.WORK_NAME_LOCK,
|
||||
ScreenType.BOTH to Constants.WORK_NAME_BOTH,
|
||||
ScreenType.LIVE to Constants.WORK_NAME_LIVE
|
||||
)
|
||||
|
||||
@Before
|
||||
@After
|
||||
fun clearTestSchedules() {
|
||||
(targets.values + Constants.WORK_NAME_REFRESH).forEach { name ->
|
||||
workManager.cancelUniqueWork(name).result.get(10, TimeUnit.SECONDS)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun manualResetJobsRemainInTheirFirstPeriodUntilTheFullDelay() = runBlocking {
|
||||
val delayMillis = TimeUnit.MINUTES.toMillis(15)
|
||||
val jobs = targets.map { (screen, name) ->
|
||||
val before = System.currentTimeMillis()
|
||||
scheduler.scheduleWallpaperChange(screen, 15, resetInterval = true)
|
||||
val info = awaitEnqueued(name)
|
||||
assertTrue(info.nextScheduleTimeMillis >= before + delayMillis)
|
||||
info.id to before
|
||||
}
|
||||
|
||||
// Checking only the next countdown can miss an immediate first run: after that run,
|
||||
// periodic work also shows a full interval. Inspect the persisted first-period state.
|
||||
SystemClock.sleep(2_000)
|
||||
jobs.forEach { (id, before) ->
|
||||
val spec = requireNotNull(workManager.workDatabase.workSpecDao().getWorkSpec(id.toString()))
|
||||
assertEquals(delayMillis, spec.intervalDuration)
|
||||
assertEquals(0, spec.periodCount)
|
||||
assertEquals(WorkInfo.State.ENQUEUED, spec.state)
|
||||
assertTrue(spec.calculateNextRunTime() >= before + delayMillis)
|
||||
assertTrue(spec.calculateNextRunTime() <= System.currentTimeMillis() + delayMillis)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun settingsUpdatePreservesThePendingManualResetDelay() = runBlocking {
|
||||
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60, resetInterval = true)
|
||||
val reset = awaitEnqueued(Constants.WORK_NAME_HOME)
|
||||
|
||||
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60)
|
||||
|
||||
val updated = awaitEnqueued(Constants.WORK_NAME_HOME, minimumGeneration = reset.generation + 1)
|
||||
assertEquals(reset.id, updated.id)
|
||||
assertEquals(reset.nextScheduleTimeMillis, updated.nextScheduleTimeMillis)
|
||||
val spec = requireNotNull(workManager.workDatabase.workSpecDao().getWorkSpec(updated.id.toString()))
|
||||
assertEquals(0, spec.periodCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun repeatedHomeResetLeavesTheIndependentLockCountdownUntouched() = runBlocking {
|
||||
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60, resetInterval = true)
|
||||
scheduler.scheduleWallpaperChange(ScreenType.LOCK, 90, resetInterval = true)
|
||||
val home = awaitEnqueued(Constants.WORK_NAME_HOME)
|
||||
val lock = awaitEnqueued(Constants.WORK_NAME_LOCK)
|
||||
val before = System.currentTimeMillis()
|
||||
|
||||
scheduler.resetAfterManualChange(
|
||||
ScreenType.HOME,
|
||||
ScheduleSettings(
|
||||
enableChanger = true,
|
||||
separateSchedules = true,
|
||||
homeEnabled = true,
|
||||
lockEnabled = true,
|
||||
homeAlbumId = "home",
|
||||
lockAlbumId = "lock",
|
||||
homeIntervalMinutes = 60,
|
||||
lockIntervalMinutes = 90
|
||||
),
|
||||
WallpaperMode.STATIC
|
||||
)
|
||||
|
||||
val newHome = awaitEnqueued(Constants.WORK_NAME_HOME, minimumGeneration = home.generation + 1)
|
||||
val sameLock = awaitEnqueued(Constants.WORK_NAME_LOCK)
|
||||
assertEquals(home.id, newHome.id)
|
||||
assertTrue(newHome.nextScheduleTimeMillis >= before + TimeUnit.MINUTES.toMillis(60))
|
||||
assertEquals(lock.id, sameLock.id)
|
||||
assertEquals(lock.nextScheduleTimeMillis, sameLock.nextScheduleTimeMillis)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun startupKeepsExistingCountdownsAndSwitchesBetweenCombinedAndSeparateJobs() = runBlocking {
|
||||
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60, resetInterval = true)
|
||||
scheduler.scheduleWallpaperChange(ScreenType.LOCK, 90, resetInterval = true)
|
||||
val home = awaitEnqueued(Constants.WORK_NAME_HOME)
|
||||
val lock = awaitEnqueued(Constants.WORK_NAME_LOCK)
|
||||
|
||||
val settings = ScheduleSettings(
|
||||
enableChanger = true, homeEnabled = true, lockEnabled = true,
|
||||
homeAlbumId = "home", lockAlbumId = "lock", separateSchedules = true,
|
||||
homeIntervalMinutes = 15, lockIntervalMinutes = 15
|
||||
)
|
||||
scheduler.updateSchedules(settings, WallpaperMode.STATIC, onlyIfNotScheduled = true)
|
||||
awaitEnqueued(Constants.WORK_NAME_REFRESH)
|
||||
for ((name, previous) in listOf(Constants.WORK_NAME_HOME to home, Constants.WORK_NAME_LOCK to lock)) {
|
||||
val kept = awaitEnqueued(name)
|
||||
assertEquals(previous.id, kept.id)
|
||||
assertEquals(previous.generation, kept.generation)
|
||||
assertEquals(previous.nextScheduleTimeMillis, kept.nextScheduleTimeMillis)
|
||||
}
|
||||
|
||||
scheduler.updateSchedules(settings.copy(homeIntervalMinutes = 60, lockAlbumId = "home", separateSchedules = false), WallpaperMode.STATIC, onlyIfNotScheduled = true)
|
||||
awaitEnqueued(Constants.WORK_NAME_BOTH)
|
||||
awaitCancelled(Constants.WORK_NAME_HOME)
|
||||
awaitCancelled(Constants.WORK_NAME_LOCK)
|
||||
|
||||
scheduler.updateSchedules(settings.copy(homeIntervalMinutes = 30, lockIntervalMinutes = 45), WallpaperMode.STATIC, onlyIfNotScheduled = true)
|
||||
val newHome = awaitEnqueued(Constants.WORK_NAME_HOME)
|
||||
val newLock = awaitEnqueued(Constants.WORK_NAME_LOCK)
|
||||
awaitCancelled(Constants.WORK_NAME_BOTH)
|
||||
assertTrue(home.id != newHome.id)
|
||||
assertTrue(lock.id != newLock.id)
|
||||
}
|
||||
|
||||
private suspend fun awaitCancelled(name: String) = withTimeout(10_000) {
|
||||
workManager.getWorkInfosForUniqueWorkFlow(name).first { infos ->
|
||||
infos.isNotEmpty() && infos.all { it.state == WorkInfo.State.CANCELLED }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun awaitEnqueued(
|
||||
name: String,
|
||||
minimumGeneration: Int = 0
|
||||
): WorkInfo =
|
||||
withTimeout(10_000) {
|
||||
workManager.getWorkInfosForUniqueWorkFlow(name).first { infos ->
|
||||
infos.any {
|
||||
it.state == WorkInfo.State.ENQUEUED &&
|
||||
it.generation >= minimumGeneration
|
||||
}
|
||||
}.single {
|
||||
it.state == WorkInfo.State.ENQUEUED &&
|
||||
it.generation >= minimumGeneration
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,16 @@
|
||||
|
||||
<!-- Permissions -->
|
||||
<uses-permission android:name="android.permission.SET_WALLPAPER" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<!-- WorkManager contributes this permission for optional network constraints. Paperize never
|
||||
schedules network-constrained work, so keep it out of the final manifest. -->
|
||||
<uses-permission
|
||||
android:name="android.permission.ACCESS_NETWORK_STATE"
|
||||
tools:node="remove" />
|
||||
<!-- Features -->
|
||||
<uses-feature
|
||||
android:name="android.software.wallpaper"
|
||||
@@ -49,25 +52,25 @@
|
||||
<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"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
<!-- Broadcast Receivers -->
|
||||
<receiver
|
||||
android:name=".service.alarm.BootReceiver"
|
||||
android:enabled="true"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<!-- Quick Settings Tile -->
|
||||
<service
|
||||
android:name=".service.tile.WallpaperTileService"
|
||||
|
||||
|
Before Width: | Height: | Size: 44 KiB |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 108 108">
|
||||
<rect width="108" height="108" fill="#ffd9e2"/>
|
||||
<path d="M68.25 36.59L77.37 42.74A5.5 5.5 0 0 1 78.85 50.38L65.01 70.9L64.68 70.08L68.2 36.56A5.5 5.5 0 0 1 68.25 36.59Z" fill="#e03a72"/>
|
||||
<path d="M49.61 32.64L60.55 33.79A5.5 5.5 0 0 1 65.44 39.83L62.76 65.34L49.55 32.63A5.5 5.5 0 0 1 49.61 32.64Z" fill="#c2255c"/>
|
||||
<path d="M31.29 37.9L41.49 33.78A5.5 5.5 0 0 1 48.65 36.82L61.01 67.42A5.5 5.5 0 0 1 57.97 74.58L47.77 78.7A5.5 5.5 0 0 1 40.61 75.66L28.25 45.06A5.5 5.5 0 0 1 31.29 37.9Z" fill="#000000"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 584 B |
@@ -4,42 +4,36 @@ 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.WallpaperScheduler
|
||||
import dagger.hilt.android.HiltAndroidApp
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Application class for Paperize
|
||||
*
|
||||
* Annotated with @HiltAndroidApp to enable dependency injection
|
||||
* Implements Configuration.Provider for WorkManager with Hilt support
|
||||
*/
|
||||
@HiltAndroidApp
|
||||
class PaperizeApplication : Application(), Configuration.Provider {
|
||||
class PaperizeApplication : Application(), Configuration.Provider, DefaultLifecycleObserver {
|
||||
|
||||
@Inject
|
||||
lateinit var workerFactory: HiltWorkerFactory
|
||||
|
||||
@Inject
|
||||
lateinit var wallpaperScheduler: WallpaperScheduler
|
||||
|
||||
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
|
||||
DataResetManager.performResetIfNeeded(this)
|
||||
|
||||
// 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 +55,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) {
|
||||
wallpaperScheduler.refreshAlbumsNow()
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* A generic class that holds a value or an error
|
||||
*/
|
||||
sealed class Result<out T> {
|
||||
data class Success<T>(val data: T) : Result<T>()
|
||||
data class Error(val exception: Throwable, val message: String? = exception.message) : Result<Nothing>()
|
||||
data object Loading : Result<Nothing>()
|
||||
|
||||
val isSuccess: Boolean get() = this is Success
|
||||
val isError: Boolean get() = this is Error
|
||||
val isLoading: Boolean get() = this is Loading
|
||||
|
||||
fun getOrNull(): T? = if (this is Success) data else null
|
||||
fun exceptionOrNull(): Throwable? = if (this is Error) exception else null
|
||||
|
||||
inline fun onSuccess(action: (T) -> Unit): Result<T> {
|
||||
if (this is Success) action(data)
|
||||
return this
|
||||
}
|
||||
|
||||
inline fun onError(action: (Throwable) -> Unit): Result<T> {
|
||||
if (this is Error) action(exception)
|
||||
return this
|
||||
}
|
||||
|
||||
companion object {
|
||||
inline fun <T> runCatching(block: () -> T): Result<T> {
|
||||
return try {
|
||||
Success(block())
|
||||
} catch (e: Exception) {
|
||||
Error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a Result to another type
|
||||
*/
|
||||
inline fun <T, R> Result<T>.map(transform: (T) -> R): Result<R> {
|
||||
return when (this) {
|
||||
is Result.Success -> Result.Success(transform(data))
|
||||
is Result.Error -> Result.Error(exception, message)
|
||||
is Result.Loading -> Result.Loading
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat map a Result
|
||||
*/
|
||||
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> {
|
||||
return when (this) {
|
||||
is Result.Success -> transform(data)
|
||||
is Result.Error -> Result.Error(exception, message)
|
||||
is Result.Loading -> Result.Loading
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** [runCatching] for suspend callers: coroutine cancellation propagates instead of becoming a failure. */
|
||||
inline fun <T> runCatchingCancellable(block: () -> T): Result<T> =
|
||||
try {
|
||||
Result.success(block())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
@@ -1,27 +1,9 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Wallpaper scaling options
|
||||
*/
|
||||
enum class ScalingType {
|
||||
/**
|
||||
* Fill the screen, cropping if necessary
|
||||
*/
|
||||
FILL,
|
||||
|
||||
/**
|
||||
* Fit the entire image, adding letterboxing/pillarboxing if necessary
|
||||
*/
|
||||
FIT,
|
||||
|
||||
/**
|
||||
* Stretch the image to fill the screen
|
||||
*/
|
||||
STRETCH,
|
||||
|
||||
/**
|
||||
* Display at original size
|
||||
*/
|
||||
NONE;
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Screen types for wallpaper setting
|
||||
*/
|
||||
enum class ScreenType {
|
||||
HOME,
|
||||
LOCK,
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Exception thrown when an album has no wallpapers available
|
||||
*/
|
||||
class EmptyAlbumException(message: String) : Exception(message)
|
||||
class EmptyAlbumException : Exception("Album has no wallpapers")
|
||||
|
||||
/**
|
||||
* Exception thrown when no valid wallpaper can be found after retries
|
||||
*/
|
||||
class NoValidWallpaperException(message: String) : Exception(message)
|
||||
class NoValidWallpaperException : Exception("No readable wallpaper found")
|
||||
@@ -1,61 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Media type for wallpapers
|
||||
*
|
||||
* Determines what type of media the wallpaper file is, which affects
|
||||
* how it's rendered in live wallpaper mode.
|
||||
*
|
||||
* Note: Currently only IMAGE type is supported.
|
||||
*/
|
||||
enum class WallpaperMediaType {
|
||||
/**
|
||||
* Image files: JPEG, PNG, WEBP, AVIF, HEIC, HEIF, BMP, GIF, TIFF
|
||||
* Supported in both static and live wallpaper modes
|
||||
*/
|
||||
IMAGE;
|
||||
|
||||
/**
|
||||
* Supported file extensions for this media type
|
||||
*/
|
||||
val supportedExtensions: Set<String>
|
||||
get() = when (this) {
|
||||
IMAGE -> setOf(
|
||||
"jpg", "jpeg", "png", "webp", "avif",
|
||||
"heic", "heif", // HEIC/HEIF - Apple's high efficiency format
|
||||
"bmp", // Bitmap - legacy but still used
|
||||
"gif", // GIF - mostly for static images (first frame used)
|
||||
"tiff", "tif", // TIFF - high quality archival format
|
||||
"svg" // SVG - vector graphics (rasterized for wallpaper)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this media type is supported in static wallpaper mode
|
||||
*/
|
||||
val supportedInStaticMode: Boolean
|
||||
get() = this == IMAGE
|
||||
|
||||
/**
|
||||
* Whether this media type is supported in live wallpaper mode
|
||||
*/
|
||||
val supportedInLiveMode: Boolean
|
||||
get() = true // All types supported in live mode
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Detect media type from file extension
|
||||
*/
|
||||
fun fromExtension(extension: String): WallpaperMediaType? {
|
||||
val ext = extension.lowercase()
|
||||
return entries.find { ext in it.supportedExtensions }
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert string to WallpaperMediaType
|
||||
*/
|
||||
fun fromString(value: String?): WallpaperMediaType? {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +1,15 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Wallpaper mode enum
|
||||
*
|
||||
* Determines whether the app uses static wallpaper (WallpaperManager.setBitmap)
|
||||
* or live wallpaper (WallpaperService) for applying wallpapers.
|
||||
*
|
||||
* Users choose their preferred mode during onboarding and can switch later
|
||||
* with full data reset.
|
||||
* How wallpapers are applied: [STATIC] via WallpaperManager.setBitmap, or [LIVE] via the
|
||||
* Paperize WallpaperService (continuous rendering, double-tap and parallax, higher battery use).
|
||||
* Users pick a mode during onboarding; switching later resets all data.
|
||||
*/
|
||||
enum class WallpaperMode {
|
||||
/**
|
||||
* Static wallpaper mode
|
||||
* - Uses WallpaperManager.setBitmap() to apply wallpapers
|
||||
* - Supports images only
|
||||
* - Lower battery usage
|
||||
* - No interactive effects
|
||||
*/
|
||||
STATIC,
|
||||
|
||||
/**
|
||||
* Live wallpaper mode
|
||||
* - Uses WallpaperService for continuous rendering
|
||||
* - Supports images only (with effects)
|
||||
* - Interactive effects (double-tap, parallax)
|
||||
* - Higher battery usage
|
||||
*/
|
||||
LIVE;
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Convert string to WallpaperMode
|
||||
* Defaults to STATIC if string is null or doesn't match any mode
|
||||
*/
|
||||
fun fromString(value: String?): WallpaperMode {
|
||||
return entries.find { it.name.equals(value, ignoreCase = true) } ?: STATIC
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.anthonyla.paperize.core
|
||||
|
||||
/**
|
||||
* Source type for wallpapers
|
||||
*/
|
||||
enum class WallpaperSourceType {
|
||||
/**
|
||||
* Directly selected wallpaper files
|
||||
*/
|
||||
DIRECT,
|
||||
|
||||
/**
|
||||
* Wallpapers from monitored folders
|
||||
*/
|
||||
FOLDER
|
||||
}
|
||||
@@ -1,42 +1,23 @@
|
||||
package com.anthonyla.paperize.core.constants
|
||||
|
||||
/**
|
||||
* Application-wide constants
|
||||
*/
|
||||
object Constants {
|
||||
// Database
|
||||
const val DATABASE_NAME = "paperize_database"
|
||||
const val DATABASE_VERSION = 4 // v4: Removed unused cropOffsetX/Y/Scale columns from wallpapers table
|
||||
const val DATABASE_VERSION = 7
|
||||
|
||||
// DataStore
|
||||
const val PREFERENCES_NAME = "paperize_preferences"
|
||||
|
||||
// Notifications
|
||||
const val NOTIFICATION_CHANNEL_ID = "paperize_channel"
|
||||
const val NOTIFICATION_ID = 1
|
||||
|
||||
// Services
|
||||
const val ACTION_CHANGE_WALLPAPER = "com.anthonyla.paperize.ACTION_CHANGE_WALLPAPER"
|
||||
const val ACTION_REAPPLY_EFFECTS = "com.anthonyla.paperize.ACTION_REAPPLY_EFFECTS"
|
||||
const val ACTION_RELOAD_WALLPAPER = "com.anthonyla.paperize.ACTION_RELOAD_WALLPAPER"
|
||||
|
||||
// WorkManager
|
||||
const val WORK_NAME_HOME = "wallpaper_change_home"
|
||||
const val WORK_NAME_LOCK = "wallpaper_change_lock"
|
||||
const val WORK_NAME_BOTH = "wallpaper_change_both"
|
||||
const val WORK_NAME_LIVE = "wallpaper_change_live"
|
||||
const val WORK_NAME_REFRESH = "album_refresh"
|
||||
const val WORK_TAG_HOME = "wallpaper_change_home_tag"
|
||||
const val WORK_TAG_LOCK = "wallpaper_change_lock_tag"
|
||||
const val WORK_TAG_BOTH = "wallpaper_change_both_tag"
|
||||
const val WORK_TAG_LIVE = "wallpaper_change_live_tag"
|
||||
const val WORK_TAG_REFRESH = "album_refresh_tag"
|
||||
const val MAX_WORK_RETRY_ATTEMPTS = 3
|
||||
|
||||
// Intents
|
||||
const val EXTRA_SCREEN_TYPE = "screen_type"
|
||||
|
||||
// Wallpaper
|
||||
const val DEFAULT_BLUR_PERCENTAGE = 0
|
||||
const val DEFAULT_DARKEN_PERCENTAGE = 0
|
||||
const val DEFAULT_VIGNETTE_PERCENTAGE = 0
|
||||
@@ -44,164 +25,54 @@ object Constants {
|
||||
const val DEFAULT_GRAYSCALE_PERCENTAGE = 0
|
||||
const val MAX_EFFECT_PERCENTAGE = 100
|
||||
const val SLIDER_EFFECT_STEPS = 99
|
||||
const val DIALOG_MESSAGE_MAX_LINES = 10
|
||||
const val MIN_EFFECT_PERCENTAGE = 0
|
||||
const val FLOW_SUBSCRIPTION_TIMEOUT_MS = 5000L
|
||||
|
||||
// Scheduling
|
||||
const val MIN_LIVE_INTERVAL_MINUTES = 1
|
||||
const val MIN_INTERVAL_MINUTES = 15
|
||||
const val MAX_INTERVAL_MINUTES = 43200 // 30 days in minutes
|
||||
const val DEFAULT_INTERVAL_MINUTES = 60
|
||||
|
||||
// UI
|
||||
const val ANIMATION_DURATION_LONG_MS = 800 // For item reordering animations
|
||||
const val ANIMATION_DURATION_LONG_MS = 800
|
||||
const val DEBOUNCE_DELAY_MS = 500L
|
||||
const val PERMISSION_SCREEN_TRANSITION_DELAY_MS = 300L // Brief delay for permission screen transitions
|
||||
const val SETTINGS_DEBOUNCE_MS = 2000L // Debounce for settings changes before persisting
|
||||
const val WALLPAPER_CHANGE_DEBOUNCE_MS = 2000L
|
||||
const val WALLPAPER_ASPECT_RATIO = 9f / 16f // Standard phone aspect ratio
|
||||
const val SETTINGS_DEBOUNCE_MS = 2000L
|
||||
const val WALLPAPER_ASPECT_RATIO = 9f / 16f
|
||||
const val GRID_THUMBNAIL_WIDTH = 300
|
||||
const val GRID_THUMBNAIL_HEIGHT = 500
|
||||
const val LIST_THUMBNAIL_SIZE = 150
|
||||
const val PREVIEW_THUMBNAIL_WIDTH = 600
|
||||
const val PREVIEW_THUMBNAIL_HEIGHT = 1200
|
||||
|
||||
// Time conversion
|
||||
const val MINUTES_PER_HOUR = 60
|
||||
const val MINUTES_PER_DAY = 1440
|
||||
|
||||
// Image processing
|
||||
const val MAX_BLUR_RADIUS = 25.0f
|
||||
const val BRIGHTNESS_SAMPLE_SIZE = 10 // Pixel sample size for brightness calculation
|
||||
const val DEFAULT_BRIGHTNESS = 0.5f // Default brightness fallback
|
||||
const val BACKDROP_MAX_SIZE = 64
|
||||
const val BACKDROP_BLUR_PERCENT = 25
|
||||
const val BRIGHTNESS_SAMPLE_SIZE = 10
|
||||
|
||||
// Luminance coefficients (ITU-R BT.709 standard)
|
||||
// ITU-R BT.709
|
||||
const val LUMINANCE_RED = 0.2126
|
||||
const val LUMINANCE_GREEN = 0.7152
|
||||
const val LUMINANCE_BLUE = 0.0722
|
||||
|
||||
// Adaptive brightness thresholds (based on WallYou implementation)
|
||||
const val LIGHT_BRIGHTNESS_MIN = 0.8f // Threshold for bright images in dark mode
|
||||
const val DARK_BRIGHTNESS_MAX = 0.3f // Threshold for dark images in light mode
|
||||
const val TARGET_BRIGHTNESS_DARK = 0.7f // Target brightness in dark mode
|
||||
const val TARGET_BRIGHTNESS_LIGHT = 0.4f // Target brightness in light mode
|
||||
// Adaptive brightness thresholds follow WallYou.
|
||||
const val LIGHT_BRIGHTNESS_MIN = 0.8f
|
||||
const val DARK_BRIGHTNESS_MAX = 0.3f
|
||||
const val TARGET_BRIGHTNESS_DARK = 0.7f
|
||||
const val TARGET_BRIGHTNESS_LIGHT = 0.4f
|
||||
|
||||
// Vignette effect
|
||||
const val VIGNETTE_DIVISOR = 150f // Radius calculation divisor
|
||||
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
|
||||
const val VIGNETTE_DIVISOR = 150f
|
||||
const val VIGNETTE_MIN_RADIUS = 1f // guards against zero-radius RadialGradient crash
|
||||
const val VIGNETTE_INNER_ALPHA = 0.1f
|
||||
const val VIGNETTE_OUTER_ALPHA = 0.8f
|
||||
val VIGNETTE_GRADIENT_POSITIONS = floatArrayOf(0f, 0.7f, 1f)
|
||||
|
||||
// Wallpaper loading retry
|
||||
const val WALLPAPER_READ_INITIAL_DELAY_MS = 500L // Initial retry delay (with linear backoff)
|
||||
|
||||
// Input validation
|
||||
const val MAX_DAYS_INPUT_LENGTH = 3
|
||||
const val MAX_HOURS_MINUTES_INPUT_LENGTH = 2
|
||||
|
||||
// File types
|
||||
val SUPPORTED_IMAGE_EXTENSIONS = setOf(
|
||||
"jpg", "jpeg", "png", "webp", "avif",
|
||||
"heic", "heif", // HEIC/HEIF - Apple's high efficiency format
|
||||
"bmp", // Bitmap - legacy but still used
|
||||
"gif", // GIF - mostly for static images (first frame used)
|
||||
"tiff", "tif", // TIFF - high quality archival format
|
||||
"svg" // SVG - vector graphics (rasterized for wallpaper)
|
||||
"jpg", "jpeg", "png", "webp", "avif", "heic", "heif", "bmp", "gif", "tiff", "tif"
|
||||
)
|
||||
|
||||
// Renderer
|
||||
/** Crossfade animation duration in milliseconds - consistent across all refresh rates */
|
||||
const val CROSSFADE_DURATION_MS = 750f
|
||||
const val RELOAD_THROTTLE_MS = 250L
|
||||
const val BLUR_MIN_THRESHOLD = 0.01f
|
||||
const val PERCENTAGE_DIVISOR = 100f
|
||||
const val GL_ES_VERSION = 2
|
||||
const val SURFACE_POLL_INTERVAL_MS = 50L
|
||||
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
|
||||
const val MAX_QUEUE_REBUILD_ATTEMPTS = 2
|
||||
}
|
||||
|
||||
/**
|
||||
* Preference keys for DataStore
|
||||
*/
|
||||
object PreferenceKeys {
|
||||
// Theme
|
||||
const val DARK_MODE = "dark_mode"
|
||||
const val DYNAMIC_THEMING = "dynamic_theming"
|
||||
const val ANIMATE = "animate"
|
||||
|
||||
// Scheduling
|
||||
const val ENABLE_CHANGER = "enable_changer"
|
||||
const val SEPARATE_SCHEDULES = "separate_schedules"
|
||||
const val SHUFFLE_ENABLED = "shuffle_enabled"
|
||||
const val HOME_ENABLED = "home_enabled"
|
||||
const val LOCK_ENABLED = "lock_enabled"
|
||||
const val HOME_ALBUM_ID = "home_album_id"
|
||||
const val LOCK_ALBUM_ID = "lock_album_id"
|
||||
const val HOME_INTERVAL_MINUTES = "home_interval_minutes"
|
||||
const val LOCK_INTERVAL_MINUTES = "lock_interval_minutes"
|
||||
|
||||
// Effects - Home
|
||||
const val HOME_ENABLE_BLUR = "home_enable_blur"
|
||||
const val HOME_BLUR = "home_blur"
|
||||
const val HOME_ENABLE_DARKEN = "home_enable_darken"
|
||||
const val HOME_DARKEN = "home_darken"
|
||||
const val HOME_ENABLE_VIGNETTE = "home_enable_vignette"
|
||||
const val HOME_VIGNETTE = "home_vignette"
|
||||
const val HOME_ENABLE_GRAYSCALE = "home_enable_grayscale"
|
||||
const val HOME_GRAYSCALE = "home_grayscale"
|
||||
|
||||
// Effects - Lock
|
||||
const val LOCK_ENABLE_BLUR = "lock_enable_blur"
|
||||
const val LOCK_BLUR = "lock_blur"
|
||||
const val LOCK_ENABLE_DARKEN = "lock_enable_darken"
|
||||
const val LOCK_DARKEN = "lock_darken"
|
||||
const val LOCK_ENABLE_VIGNETTE = "lock_enable_vignette"
|
||||
const val LOCK_VIGNETTE = "lock_vignette"
|
||||
const val LOCK_ENABLE_GRAYSCALE = "lock_enable_grayscale"
|
||||
const val LOCK_GRAYSCALE = "lock_grayscale"
|
||||
|
||||
// Interactive Effects - Home (live wallpaper mode only)
|
||||
const val HOME_ENABLE_DOUBLE_TAP = "home_enable_double_tap"
|
||||
const val HOME_ENABLE_PARALLAX = "home_enable_parallax"
|
||||
const val HOME_PARALLAX_INTENSITY = "home_parallax_intensity"
|
||||
|
||||
// Interactive Effects - Lock (live wallpaper mode only)
|
||||
const val LOCK_ENABLE_DOUBLE_TAP = "lock_enable_double_tap"
|
||||
const val LOCK_ENABLE_PARALLAX = "lock_enable_parallax"
|
||||
const val LOCK_PARALLAX_INTENSITY = "lock_parallax_intensity"
|
||||
|
||||
// Live Wallpaper Mode Settings
|
||||
const val LIVE_ALBUM_ID = "live_album_id"
|
||||
const val LIVE_INTERVAL_MINUTES = "live_interval_minutes"
|
||||
const val LIVE_ENABLE_BLUR = "live_enable_blur"
|
||||
const val LIVE_BLUR = "live_blur"
|
||||
const val LIVE_ENABLE_DARKEN = "live_enable_darken"
|
||||
const val LIVE_DARKEN = "live_darken"
|
||||
const val LIVE_ENABLE_VIGNETTE = "live_enable_vignette"
|
||||
const val LIVE_VIGNETTE = "live_vignette"
|
||||
const val LIVE_ENABLE_GRAYSCALE = "live_enable_grayscale"
|
||||
const val LIVE_GRAYSCALE = "live_grayscale"
|
||||
const val LIVE_ENABLE_DOUBLE_TAP = "live_enable_double_tap"
|
||||
const val LIVE_ENABLE_CHANGE_ON_SCREEN_OFF = "live_enable_change_on_screen_off"
|
||||
const val LIVE_ENABLE_PARALLAX = "live_enable_parallax"
|
||||
const val LIVE_PARALLAX_INTENSITY = "live_parallax_intensity"
|
||||
|
||||
// Scaling
|
||||
const val HOME_SCALING_TYPE = "home_scaling_type"
|
||||
const val LOCK_SCALING_TYPE = "lock_scaling_type"
|
||||
const val LIVE_SCALING_TYPE = "live_scaling_type"
|
||||
|
||||
// Behavior
|
||||
const val ADAPTIVE_BRIGHTNESS = "adaptive_brightness"
|
||||
|
||||
// First launch
|
||||
const val FIRST_LAUNCH = "first_launch"
|
||||
|
||||
// Wallpaper mode
|
||||
const val WALLPAPER_MODE = "wallpaper_mode"
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package com.anthonyla.paperize.core.di
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperCurrentDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperQueueDao
|
||||
import com.anthonyla.paperize.data.datastore.PreferencesManager
|
||||
import com.anthonyla.paperize.data.repository.AlbumRepositoryImpl
|
||||
import com.anthonyla.paperize.data.repository.SettingsRepositoryImpl
|
||||
import com.anthonyla.paperize.data.repository.WallpaperRepositoryImpl
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Hilt dependency injection module
|
||||
*
|
||||
* Provides all application-wide dependencies
|
||||
*/
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object AppModule {
|
||||
|
||||
/**
|
||||
* Provide Room database
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun providePaperizeDatabase(app: Application): PaperizeDatabase {
|
||||
return Room.databaseBuilder(
|
||||
app,
|
||||
PaperizeDatabase::class.java,
|
||||
Constants.DATABASE_NAME
|
||||
)
|
||||
.fallbackToDestructiveMigration(dropAllTables = true)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide DAOs
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumDao(database: PaperizeDatabase): AlbumDao =
|
||||
database.albumDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperDao(database: PaperizeDatabase): WallpaperDao =
|
||||
database.wallpaperDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideFolderDao(database: PaperizeDatabase): FolderDao =
|
||||
database.folderDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperQueueDao(database: PaperizeDatabase): WallpaperQueueDao =
|
||||
database.wallpaperQueueDao()
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperCurrentDao(database: PaperizeDatabase): WallpaperCurrentDao =
|
||||
database.wallpaperCurrentDao()
|
||||
|
||||
/**
|
||||
* Provide PreferencesManager
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun providePreferencesManager(@ApplicationContext context: Context): PreferencesManager =
|
||||
PreferencesManager(context)
|
||||
|
||||
/**
|
||||
* Provide Repositories
|
||||
*/
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideAlbumRepository(
|
||||
@ApplicationContext context: Context,
|
||||
database: PaperizeDatabase,
|
||||
albumDao: AlbumDao,
|
||||
wallpaperDao: WallpaperDao,
|
||||
folderDao: FolderDao,
|
||||
wallpaperRepository: dagger.Lazy<WallpaperRepository>
|
||||
): AlbumRepository = AlbumRepositoryImpl(context, database, albumDao, wallpaperDao, folderDao, wallpaperRepository)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideWallpaperRepository(
|
||||
@ApplicationContext context: Context,
|
||||
wallpaperDao: WallpaperDao,
|
||||
wallpaperQueueDao: WallpaperQueueDao,
|
||||
wallpaperCurrentDao: WallpaperCurrentDao
|
||||
): WallpaperRepository = WallpaperRepositoryImpl(context, wallpaperDao, wallpaperQueueDao, wallpaperCurrentDao)
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun provideSettingsRepository(
|
||||
preferencesManager: PreferencesManager
|
||||
): SettingsRepository = SettingsRepositoryImpl(preferencesManager)
|
||||
}
|
||||
@@ -2,39 +2,28 @@ package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Utility for handling battery optimization (Doze mode) exclusion
|
||||
*/
|
||||
object BatteryOptimizationUtil {
|
||||
private const val TAG = "BatteryOptimizationUtil"
|
||||
|
||||
/**
|
||||
* Check if the app is currently excluded from battery optimizations
|
||||
*/
|
||||
fun isIgnoringBatteryOptimizations(context: Context): Boolean {
|
||||
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
val powerManager = context.getSystemService(PowerManager::class.java)
|
||||
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
|
||||
/**
|
||||
* Request the user to exclude the app from battery optimizations
|
||||
* Opens the system battery optimization settings page
|
||||
*/
|
||||
fun requestIgnoreBatteryOptimizations(context: Context) {
|
||||
try {
|
||||
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
|
||||
data = Uri.parse("package:${context.packageName}")
|
||||
data = "package:${context.packageName}".toUri()
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
context.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error requesting battery optimization exclusion", e)
|
||||
// Fallback: open general battery optimization settings
|
||||
try {
|
||||
val fallbackIntent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
@@ -3,17 +3,10 @@ package com.anthonyla.paperize.core.util
|
||||
import android.graphics.Bitmap
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
* Utility class for brightness calculations and adaptive adjustments.
|
||||
* Extracted from WallpaperUtil for better testability.
|
||||
*/
|
||||
object BrightnessCalculator {
|
||||
|
||||
/**
|
||||
* Calculate relative luminance of a single pixel using ITU-R BT.709 standard.
|
||||
* Use bitwise operations to avoid dependency on android.graphics.Color in core logic tests.
|
||||
*/
|
||||
fun calculateLuminance(pixel: Int): Double {
|
||||
/** Estimates luminance with BT.709 coefficients; channels remain in their encoded color space. */
|
||||
private fun calculateLuminance(pixel: Int): Double {
|
||||
val r = ((pixel shr 16) and 0xFF) / 255.0
|
||||
val g = ((pixel shr 8) and 0xFF) / 255.0
|
||||
val b = (pixel and 0xFF) / 255.0
|
||||
@@ -21,19 +14,11 @@ object BrightnessCalculator {
|
||||
return Constants.LUMINANCE_RED * r + Constants.LUMINANCE_GREEN * g + Constants.LUMINANCE_BLUE * b
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
/** Samples rows in bulk to avoid a JNI call for every pixel. Returns brightness in 0..1. */
|
||||
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
|
||||
@@ -47,35 +32,16 @@ object BrightnessCalculator {
|
||||
}
|
||||
}
|
||||
|
||||
return if (pixelCount > 0) {
|
||||
(totalLuminance / pixelCount).toFloat()
|
||||
} else {
|
||||
Constants.DEFAULT_BRIGHTNESS
|
||||
}
|
||||
return (totalLuminance / pixelCount).toFloat()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get adaptive brightness multiplier factor based on system dark/light mode.
|
||||
*
|
||||
* @param isDarkMode Whether the system is in dark mode
|
||||
* @param brightness Current image brightness (0.0 to 1.0)
|
||||
* @return Multiplier factor to apply to colors
|
||||
*/
|
||||
fun getAdaptiveMultiplier(isDarkMode: Boolean, brightness: Float): Float {
|
||||
val lightBrightnessMin = Constants.LIGHT_BRIGHTNESS_MIN
|
||||
val darkBrightnessMax = Constants.DARK_BRIGHTNESS_MAX
|
||||
val targetBrightnessDark = Constants.TARGET_BRIGHTNESS_DARK
|
||||
val targetBrightnessLight = Constants.TARGET_BRIGHTNESS_LIGHT
|
||||
|
||||
// Avoid issues with very dark items or division by zero
|
||||
if (brightness < 0.01f) return 1.0f
|
||||
|
||||
return when {
|
||||
// In dark mode with very bright image: darken it
|
||||
isDarkMode && brightness > lightBrightnessMin -> targetBrightnessDark / brightness
|
||||
// In light mode with very dark image: brighten it
|
||||
!isDarkMode && brightness < darkBrightnessMax -> targetBrightnessLight / brightness
|
||||
// No adjustment needed
|
||||
isDarkMode && brightness > Constants.LIGHT_BRIGHTNESS_MIN -> Constants.TARGET_BRIGHTNESS_DARK / brightness
|
||||
!isDarkMode && brightness < Constants.DARK_BRIGHTNESS_MAX -> Constants.TARGET_BRIGHTNESS_LIGHT / brightness
|
||||
else -> 1.0f
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,129 +2,38 @@ package com.anthonyla.paperize.core.util
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.io.File
|
||||
import androidx.core.content.edit
|
||||
import androidx.datastore.preferences.preferencesDataStoreFile
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
|
||||
/**
|
||||
* Manages one-time data reset for major version upgrades.
|
||||
*
|
||||
* Uses a separate preferences file (version_prefs) to track reset status,
|
||||
* ensuring the flag survives the data wipe itself.
|
||||
* Wipes all data once when upgrading across a major version whose data is incompatible.
|
||||
* The flag lives in its own preferences file so it survives the wipe.
|
||||
*/
|
||||
object DataResetManager {
|
||||
private const val TAG = "DataResetManager"
|
||||
|
||||
/**
|
||||
* Version tracking preferences - stored separately from main app prefs
|
||||
* so it survives the data wipe.
|
||||
*/
|
||||
private const val VERSION_PREFS_NAME = "version_prefs"
|
||||
private const val KEY_LAST_RESET_VERSION = "last_reset_version"
|
||||
|
||||
/**
|
||||
* Target reset version - increment this for future major version upgrades
|
||||
* that require a complete data wipe.
|
||||
*
|
||||
* Version 4 = v4.0.0 release (complete app rewrite)
|
||||
*/
|
||||
/** Increment for a release that needs a wipe. 4 = the v4.0.0 rewrite. */
|
||||
private const val TARGET_RESET_VERSION = 4
|
||||
|
||||
/**
|
||||
* Database and DataStore names to clear (must match Constants)
|
||||
*/
|
||||
private const val DATABASE_NAME = "paperize_database"
|
||||
private const val DATASTORE_NAME = "paperize_preferences.preferences_pb"
|
||||
|
||||
/**
|
||||
* Performs a complete data reset if needed for the current app version.
|
||||
*
|
||||
* This should be called at the very start of Application.onCreate(),
|
||||
* before any other initialization occurs.
|
||||
*
|
||||
* @return true if a reset was performed, false otherwise
|
||||
*/
|
||||
fun performResetIfNeeded(context: Context): Boolean {
|
||||
/** Must run before anything opens the database or preferences. */
|
||||
fun performResetIfNeeded(context: Context) {
|
||||
val versionPrefs = context.getSharedPreferences(VERSION_PREFS_NAME, Context.MODE_PRIVATE)
|
||||
val lastResetVersion = versionPrefs.getInt(KEY_LAST_RESET_VERSION, 0)
|
||||
|
||||
if (lastResetVersion >= TARGET_RESET_VERSION) {
|
||||
Log.d(TAG, "No reset needed (last=$lastResetVersion, target=$TARGET_RESET_VERSION)")
|
||||
return false
|
||||
}
|
||||
if (lastResetVersion >= TARGET_RESET_VERSION) return
|
||||
|
||||
Log.w(TAG, "Performing data reset: upgrading from version $lastResetVersion to $TARGET_RESET_VERSION")
|
||||
|
||||
try {
|
||||
// 1. Delete Room database files
|
||||
deleteDatabase(context)
|
||||
|
||||
// 2. Delete DataStore file
|
||||
deleteDataStore(context)
|
||||
|
||||
// 3. Update version after successful wipe
|
||||
versionPrefs.edit()
|
||||
.putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION)
|
||||
.apply()
|
||||
|
||||
Log.i(TAG, "Data reset completed successfully")
|
||||
return true
|
||||
|
||||
context.deleteDatabase(Constants.DATABASE_NAME)
|
||||
context.preferencesDataStoreFile(Constants.PREFERENCES_NAME).delete()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error during data reset", e)
|
||||
// Still mark as reset to avoid infinite reset loops on corrupted data
|
||||
versionPrefs.edit()
|
||||
.putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION)
|
||||
.apply()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes Room database and all related files (WAL, SHM, journal)
|
||||
*/
|
||||
private fun deleteDatabase(context: Context) {
|
||||
val dbPath = context.getDatabasePath(DATABASE_NAME)
|
||||
val dbDir = dbPath.parentFile
|
||||
|
||||
if (dbDir != null && dbDir.exists()) {
|
||||
// Delete main database file and all related files
|
||||
val filesToDelete = listOf(
|
||||
DATABASE_NAME,
|
||||
"$DATABASE_NAME-wal",
|
||||
"$DATABASE_NAME-shm",
|
||||
"$DATABASE_NAME-journal"
|
||||
)
|
||||
|
||||
for (fileName in filesToDelete) {
|
||||
val file = File(dbDir, fileName)
|
||||
if (file.exists()) {
|
||||
val deleted = file.delete()
|
||||
Log.d(TAG, "Deleted $fileName: $deleted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Also use Context.deleteDatabase for good measure
|
||||
val deleted = context.deleteDatabase(DATABASE_NAME)
|
||||
Log.d(TAG, "Context.deleteDatabase result: $deleted")
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes DataStore preferences file
|
||||
*/
|
||||
private fun deleteDataStore(context: Context) {
|
||||
val dataStoreFile = File(context.filesDir, "datastore/$DATASTORE_NAME")
|
||||
if (dataStoreFile.exists()) {
|
||||
val deleted = dataStoreFile.delete()
|
||||
Log.d(TAG, "Deleted DataStore file: $deleted")
|
||||
}
|
||||
|
||||
// Also delete the datastore directory if empty
|
||||
val dataStoreDir = File(context.filesDir, "datastore")
|
||||
if (dataStoreDir.exists() && dataStoreDir.isDirectory) {
|
||||
val files = dataStoreDir.listFiles()
|
||||
if (files.isNullOrEmpty()) {
|
||||
dataStoreDir.delete()
|
||||
}
|
||||
} finally {
|
||||
// Do not repeat a destructive upgrade attempt on the next launch after a failure.
|
||||
versionPrefs.edit { putInt(KEY_LAST_RESET_VERSION, TARGET_RESET_VERSION) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,131 +1,16 @@
|
||||
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
|
||||
|
||||
/**
|
||||
* URI extensions
|
||||
*/
|
||||
fun Uri.isValid(contentResolver: ContentResolver): Boolean {
|
||||
// Basic scheme check - we only handle content URIs
|
||||
if (scheme != "content") return false
|
||||
|
||||
fun Uri.isReadable(contentResolver: ContentResolver): Boolean {
|
||||
if (scheme != ContentResolver.SCHEME_CONTENT) return false
|
||||
return try {
|
||||
// Optimization: Use query to check existence/accessibility without opening the file
|
||||
// This is significantly faster and less likely to hang on slow cloud providers
|
||||
contentResolver.query(this, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
|
||||
cursor.moveToFirst()
|
||||
} ?: false
|
||||
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
|
||||
} catch (_: Exception) {
|
||||
// Fallback to opening the stream if the provider doesn't support the specific query
|
||||
try {
|
||||
contentResolver.openFileDescriptor(this, "r")?.use { true } ?: false
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fun Uri.getFileName(context: Context): String? {
|
||||
return DocumentFile.fromSingleUri(context, this)?.name
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
data class ScannedImage(
|
||||
val uri: Uri,
|
||||
val name: String,
|
||||
val lastModified: Long
|
||||
)
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
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
|
||||
*/
|
||||
fun generateId(): String = UUID.randomUUID().toString()
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
internal fun calculateDecodeSize(
|
||||
sourceWidth: Int,
|
||||
sourceHeight: Int,
|
||||
targetWidth: Int,
|
||||
targetHeight: Int,
|
||||
scaling: ScalingType
|
||||
): Pair<Int, Int> {
|
||||
val widthRatio = targetWidth.toFloat() / sourceWidth
|
||||
val heightRatio = targetHeight.toFloat() / sourceHeight
|
||||
val scale = when (scaling) {
|
||||
ScalingType.FILL -> maxOf(widthRatio, heightRatio)
|
||||
ScalingType.FIT -> minOf(widthRatio, heightRatio)
|
||||
// Keep native size unless decoding would exceed twice the screen size.
|
||||
ScalingType.NONE -> minOf(1f, widthRatio * 2, heightRatio * 2)
|
||||
ScalingType.STRETCH -> return targetWidth to targetHeight
|
||||
}
|
||||
return (sourceWidth * scale).roundToInt().coerceAtLeast(1) to
|
||||
(sourceHeight * scale).roundToInt().coerceAtLeast(1)
|
||||
}
|
||||
@@ -1,39 +1,6 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
/**
|
||||
* Utility object for building and managing wallpaper queues
|
||||
* Extracted from WallpaperRepositoryImpl for testability
|
||||
*
|
||||
* Note: The DAO-specific operations remain in the repository,
|
||||
* but the pure logic functions are extracted here for testing.
|
||||
*/
|
||||
object QueueBuilder {
|
||||
|
||||
/**
|
||||
* Build a queue of wallpaper IDs based on display order (sequential mode)
|
||||
* @param wallpaperIds List of wallpaper IDs with their display orders
|
||||
* @return List of IDs sorted by display order
|
||||
*/
|
||||
fun buildSequentialQueue(wallpaperIds: List<Pair<String, Int>>): List<String> {
|
||||
return wallpaperIds.sortedBy { it.second }.map { it.first }
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a shuffled queue of wallpaper IDs
|
||||
* @param wallpaperIds List of wallpaper IDs to shuffle
|
||||
* @return Shuffled list of IDs
|
||||
*/
|
||||
fun buildShuffledQueue(wallpaperIds: List<String>): List<String> {
|
||||
return wallpaperIds.shuffled()
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge existing queue with new wallpapers while preserving existing order
|
||||
* Used when new wallpapers are added to an album during shuffle mode
|
||||
* @param existingQueueIds Current queue order (filtered to valid IDs)
|
||||
* @param allWallpaperIds All current wallpaper IDs in the album
|
||||
* @return Combined list with existing order preserved, new IDs shuffled at end
|
||||
*/
|
||||
fun mergeWithExistingQueue(
|
||||
existingQueueIds: List<String>,
|
||||
allWallpaperIds: List<String>
|
||||
@@ -45,44 +12,9 @@ object QueueBuilder {
|
||||
return existingValid + newWallpaperIds.shuffled()
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic version of mergeWithExistingQueue for testing
|
||||
* New wallpapers are appended in their original order instead of shuffled
|
||||
*/
|
||||
fun mergeWithExistingQueueDeterministic(
|
||||
existingQueueIds: List<String>,
|
||||
allWallpaperIds: List<String>
|
||||
): List<String> {
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a wallpaper queue based on shuffle and existing queues
|
||||
* @param wallpapers Current list of wallpapers in the album
|
||||
* @param shuffle Whether shuffle is enabled
|
||||
* @param otherScreenQueue Optional existing queue for another screen type to synchronize with
|
||||
* @return List of wallpaper IDs for the new queue
|
||||
*/
|
||||
fun buildQueue(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper>,
|
||||
shuffle: Boolean,
|
||||
otherScreenQueue: List<String>? = null
|
||||
): List<String> {
|
||||
return if (shuffle) {
|
||||
if (otherScreenQueue != null && otherScreenQueue.isNotEmpty()) {
|
||||
// Synchronize with existing queue from another screen
|
||||
mergeWithExistingQueue(otherScreenQueue, wallpapers.map { it.id })
|
||||
} else {
|
||||
// New shuffled order
|
||||
buildShuffledQueue(wallpapers.map { it.id })
|
||||
}
|
||||
} else {
|
||||
// Sequential order by displayOrder
|
||||
buildSequentialQueue(wallpapers.map { it.id to it.displayOrder })
|
||||
}
|
||||
/** Ids before [pickedId] are left out: the ordered rebuild of an empty queue starts at the first item. */
|
||||
fun idsAfter(orderedIds: List<String>, pickedId: String): List<String> {
|
||||
val index = orderedIds.indexOf(pickedId)
|
||||
return if (index < 0) orderedIds else orderedIds.subList(index + 1, orderedIds.size).toList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
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 =
|
||||
setBitmap(bitmap, null, true, which).also { wallpaperId ->
|
||||
if (wallpaperId == 0) throw IOException("WallpaperManager rejected the wallpaper")
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
package com.anthonyla.paperize.core.util
|
||||
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Utility object for sorting wallpapers and folders
|
||||
* Extracted from ViewModels for testability
|
||||
*/
|
||||
object WallpaperSorter {
|
||||
|
||||
/**
|
||||
* Sort wallpapers by filename (alphabetically)
|
||||
* @param wallpapers List of wallpapers to sort
|
||||
* @param ascending True for A-Z, false for Z-A
|
||||
* @return New sorted list preserving original list
|
||||
*/
|
||||
fun sortWallpapersByName(
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): List<Wallpaper> {
|
||||
return if (ascending) {
|
||||
wallpapers.sortedBy { it.fileName.lowercase() }
|
||||
} else {
|
||||
wallpapers.sortedByDescending { it.fileName.lowercase() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort wallpapers by date added (addedAt timestamp)
|
||||
* @param wallpapers List of wallpapers to sort
|
||||
* @param ascending True for oldest first, false for newest first
|
||||
* @return New sorted list preserving original list
|
||||
*/
|
||||
fun sortWallpapersByDateAdded(
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): List<Wallpaper> {
|
||||
return if (ascending) {
|
||||
wallpapers.sortedBy { it.addedAt }
|
||||
} else {
|
||||
wallpapers.sortedByDescending { it.addedAt }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort wallpapers by date modified (dateModified timestamp)
|
||||
* @param wallpapers List of wallpapers to sort
|
||||
* @param ascending True for oldest first, false for newest first
|
||||
* @return New sorted list preserving original list
|
||||
*/
|
||||
fun sortWallpapersByDateModified(
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): List<Wallpaper> {
|
||||
return if (ascending) {
|
||||
wallpapers.sortedBy { it.dateModified }
|
||||
} else {
|
||||
wallpapers.sortedByDescending { it.dateModified }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort folders by name (alphabetically)
|
||||
*/
|
||||
fun sortFoldersByName(
|
||||
folders: List<Folder>,
|
||||
ascending: Boolean = true
|
||||
): List<Folder> {
|
||||
return if (ascending) {
|
||||
folders.sortedBy { it.name.lowercase() }
|
||||
} else {
|
||||
folders.sortedByDescending { it.name.lowercase() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort folders by date modified
|
||||
*/
|
||||
fun sortFoldersByDateModified(
|
||||
folders: List<Folder>,
|
||||
ascending: Boolean = true
|
||||
): List<Folder> {
|
||||
return if (ascending) {
|
||||
folders.sortedBy { it.dateModified }
|
||||
} else {
|
||||
folders.sortedByDescending { it.dateModified }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift a wallpaper within a list (drag and drop)
|
||||
* @param wallpapers Current list of wallpapers
|
||||
* @param fromUri URI of the wallpaper being moved
|
||||
* @param toUri URI of the target position
|
||||
* @return New list with wallpaper moved and display orders updated
|
||||
*/
|
||||
fun shiftWallpaper(
|
||||
wallpapers: List<Wallpaper>,
|
||||
fromUri: String,
|
||||
toUri: String
|
||||
): List<Wallpaper> {
|
||||
val mutableList = wallpapers.toMutableList()
|
||||
val fromIndex = mutableList.indexOfFirst { it.uri == fromUri }
|
||||
val toIndex = mutableList.indexOfFirst { it.uri == toUri }
|
||||
|
||||
if (fromIndex == -1 || toIndex == -1) return wallpapers
|
||||
|
||||
val movedItem = mutableList.removeAt(fromIndex)
|
||||
mutableList.add(toIndex, movedItem)
|
||||
|
||||
return applyDisplayOrder(mutableList)
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift a folder within a list (drag and drop)
|
||||
* @param folders Current list of folders
|
||||
* @param fromUri URI of the folder being moved
|
||||
* @param toUri URI of the target position
|
||||
* @return New list with folder moved and display orders updated
|
||||
*/
|
||||
fun shiftFolder(
|
||||
folders: List<Folder>,
|
||||
fromUri: String,
|
||||
toUri: String
|
||||
): List<Folder> {
|
||||
val mutableList = folders.toMutableList()
|
||||
val fromIndex = mutableList.indexOfFirst { it.uri == fromUri }
|
||||
val toIndex = mutableList.indexOfFirst { it.uri == toUri }
|
||||
|
||||
if (fromIndex == -1 || toIndex == -1) return folders
|
||||
|
||||
val movedItem = mutableList.removeAt(fromIndex)
|
||||
mutableList.add(toIndex, movedItem)
|
||||
|
||||
return applyFolderDisplayOrder(mutableList)
|
||||
}
|
||||
|
||||
/**
|
||||
* Shift a wallpaper within a folder's wallpaper list
|
||||
* @param folders List of all folders
|
||||
* @param folderId ID of the folder containing the wallpaper
|
||||
* @param fromUri URI of the wallpaper being moved
|
||||
* @param toUri URI of the target position
|
||||
* @return Pair of updated folders list and the new cover URI for the folder
|
||||
*/
|
||||
fun shiftWallpaperInFolder(
|
||||
folders: List<Folder>,
|
||||
folderId: String,
|
||||
fromUri: String,
|
||||
toUri: String
|
||||
): List<Folder> {
|
||||
return folders.map { folder ->
|
||||
if (folder.id == folderId) {
|
||||
val updatedWallpapers = shiftWallpaper(folder.wallpapers, fromUri, toUri)
|
||||
folder.copy(
|
||||
wallpapers = updatedWallpapers,
|
||||
coverUri = updatedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
} else {
|
||||
folder
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort all folders and wallpapers alphabetically
|
||||
*/
|
||||
fun sortAllAlphabetically(
|
||||
folders: List<Folder>,
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByName(folder.wallpapers, ascending)
|
||||
val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
|
||||
folder.copy(
|
||||
wallpapers = orderedWallpapers,
|
||||
coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
sortedFolders.sortedBy { it.name.lowercase() }
|
||||
} else {
|
||||
sortedFolders.sortedByDescending { it.name.lowercase() }
|
||||
}
|
||||
|
||||
val finalWallpapers = sortWallpapersByName(wallpapers, ascending)
|
||||
|
||||
return Pair(
|
||||
applyFolderDisplayOrder(finalFolders),
|
||||
applyDisplayOrder(finalWallpapers)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort all folders and wallpapers by date modified
|
||||
*/
|
||||
fun sortAllByDateModified(
|
||||
folders: List<Folder>,
|
||||
wallpapers: List<Wallpaper>,
|
||||
ascending: Boolean = true
|
||||
): Pair<List<Folder>, List<Wallpaper>> {
|
||||
val sortedFolders = folders.map { folder ->
|
||||
val sortedWallpapers = sortWallpapersByDateModified(folder.wallpapers, ascending)
|
||||
val orderedWallpapers = applyDisplayOrder(sortedWallpapers)
|
||||
folder.copy(
|
||||
wallpapers = orderedWallpapers,
|
||||
coverUri = orderedWallpapers.firstOrNull()?.uri ?: folder.coverUri
|
||||
)
|
||||
}
|
||||
|
||||
val finalFolders = if (ascending) {
|
||||
sortedFolders.sortedBy { it.dateModified }
|
||||
} else {
|
||||
sortedFolders.sortedByDescending { it.dateModified }
|
||||
}
|
||||
|
||||
val finalWallpapers = sortWallpapersByDateModified(wallpapers, ascending)
|
||||
|
||||
return Pair(
|
||||
applyFolderDisplayOrder(finalFolders),
|
||||
applyDisplayOrder(finalWallpapers)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply displayOrder indices to sorted wallpapers
|
||||
* @param wallpapers Sorted list of wallpapers
|
||||
* @return New list with displayOrder updated to match list position
|
||||
*/
|
||||
fun applyDisplayOrder(wallpapers: List<Wallpaper>): List<Wallpaper> {
|
||||
return wallpapers.mapIndexed { index, wallpaper ->
|
||||
wallpaper.copy(displayOrder = index)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply displayOrder indices to sorted folders
|
||||
* @param folders Sorted list of folders
|
||||
* @return New list with folder moved and display orders updated
|
||||
*/
|
||||
fun applyFolderDisplayOrder(folders: List<Folder>): List<Folder> {
|
||||
return folders.mapIndexed { index, folder ->
|
||||
folder.copy(displayOrder = index)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.anthonyla.paperize.data.database
|
||||
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
|
||||
/** Versions 1–3 used the same library tables, with extra crop columns in versions 2–3. */
|
||||
val LIBRARY_MIGRATIONS: Array<Migration> = (1..3).map<Int, Migration> { version ->
|
||||
object : Migration(version, 4) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
// Rebuilding the parent table would cascade-delete these rows; preserve them first.
|
||||
db.execSQL("CREATE TEMP TABLE saved_queue AS SELECT * FROM wallpaper_queue")
|
||||
db.execSQL("DROP TABLE wallpaper_queue")
|
||||
if (version >= 3) {
|
||||
db.execSQL("CREATE TEMP TABLE saved_current AS SELECT * FROM wallpaper_current")
|
||||
db.execSQL("DROP TABLE wallpaper_current")
|
||||
}
|
||||
db.execSQL("CREATE TABLE IF NOT EXISTS `wallpapers_new` (`id` TEXT NOT NULL, `albumId` TEXT NOT NULL, `folderId` TEXT, `uri` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `sourceType` TEXT NOT NULL, `addedAt` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )")
|
||||
val mediaType = if (version == 1) "'IMAGE'" else "mediaType"
|
||||
db.execSQL("""
|
||||
INSERT INTO wallpapers_new (id, albumId, folderId, uri, fileName, dateModified, displayOrder, sourceType, addedAt, mediaType)
|
||||
SELECT id, albumId, folderId, uri, fileName, dateModified, displayOrder, sourceType, addedAt, $mediaType FROM wallpapers
|
||||
""")
|
||||
db.execSQL("DROP TABLE wallpapers")
|
||||
db.execSQL("ALTER TABLE wallpapers_new RENAME TO wallpapers")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpapers_albumId` ON `wallpapers` (`albumId`)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpapers_folderId` ON `wallpapers` (`folderId`)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpapers_uri` ON `wallpapers` (`uri`)")
|
||||
db.execSQL("CREATE TABLE IF NOT EXISTS `wallpaper_queue` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `albumId` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `queuePosition` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_albumId_screenType` ON `wallpaper_queue` (`albumId`, `screenType`)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_wallpaperId` ON `wallpaper_queue` (`wallpaperId`)")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_queue_queuePosition` ON `wallpaper_queue` (`queuePosition`)")
|
||||
db.execSQL("CREATE TABLE IF NOT EXISTS `wallpaper_current` (`albumId` TEXT NOT NULL, `screenType` TEXT NOT NULL, `wallpaperId` TEXT NOT NULL, `appliedAt` INTEGER NOT NULL, PRIMARY KEY(`albumId`, `screenType`), FOREIGN KEY(`albumId`) REFERENCES `albums`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`wallpaperId`) REFERENCES `wallpapers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )")
|
||||
db.execSQL("CREATE INDEX IF NOT EXISTS `index_wallpaper_current_wallpaperId` ON `wallpaper_current` (`wallpaperId`)")
|
||||
db.execSQL("INSERT INTO wallpaper_queue SELECT * FROM saved_queue")
|
||||
db.execSQL("DROP TABLE saved_queue")
|
||||
if (version >= 3) {
|
||||
db.execSQL("INSERT INTO wallpaper_current SELECT * FROM saved_current")
|
||||
db.execSQL("DROP TABLE saved_current")
|
||||
}
|
||||
}
|
||||
}
|
||||
}.toTypedArray() + object : Migration(5, 6) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
val hasEncryptionColumn = db.query("PRAGMA table_info(`albums`)").use { cursor ->
|
||||
val nameColumn = cursor.getColumnIndexOrThrow("name")
|
||||
var found = false
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(nameColumn) == "isEncrypted") {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
if (!hasEncryptionColumn) {
|
||||
db.execSQL("ALTER TABLE `albums` ADD COLUMN `isEncrypted` INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
db.execSQL(
|
||||
"CREATE TABLE IF NOT EXISTS `excluded_wallpapers` (`folderId` TEXT NOT NULL, `uri` TEXT NOT NULL, `id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `dateModified` INTEGER NOT NULL, `displayOrder` INTEGER NOT NULL, `addedAt` INTEGER NOT NULL, PRIMARY KEY(`folderId`, `uri`), FOREIGN KEY(`folderId`) REFERENCES `folders`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE)"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,40 @@
|
||||
package com.anthonyla.paperize.data.database
|
||||
|
||||
import androidx.room.AutoMigration
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import com.anthonyla.paperize.data.database.converters.TypeConverters as PaperizeTypeConverters
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.ExcludedWallpaperDao
|
||||
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.ExcludedWallpaperEntity
|
||||
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
|
||||
|
||||
/**
|
||||
* Paperize Room Database
|
||||
*
|
||||
* **MAJOR ARCHITECTURAL IMPROVEMENT:**
|
||||
* - Properly normalized schema (no nested collections in entities)
|
||||
* - NO CursorWindow reflection hack needed!
|
||||
* - Proper foreign keys with cascade delete
|
||||
* - Indexed columns for performance
|
||||
* - Separate queue management table
|
||||
* - Room migrations support (no destructive migrations!)
|
||||
*
|
||||
* Version: 1
|
||||
*/
|
||||
@Database(
|
||||
entities = [
|
||||
AlbumEntity::class,
|
||||
WallpaperEntity::class,
|
||||
FolderEntity::class,
|
||||
WallpaperQueueEntity::class,
|
||||
WallpaperCurrentEntity::class
|
||||
WallpaperCurrentEntity::class,
|
||||
ExcludedWallpaperEntity::class
|
||||
],
|
||||
version = Constants.DATABASE_VERSION,
|
||||
exportSchema = true
|
||||
exportSchema = true,
|
||||
autoMigrations = [AutoMigration(from = 4, to = 5), AutoMigration(from = 6, to = 7)]
|
||||
)
|
||||
@TypeConverters(PaperizeTypeConverters::class)
|
||||
abstract class PaperizeDatabase : RoomDatabase() {
|
||||
abstract fun albumDao(): AlbumDao
|
||||
abstract fun wallpaperDao(): WallpaperDao
|
||||
abstract fun folderDao(): FolderDao
|
||||
abstract fun wallpaperQueueDao(): WallpaperQueueDao
|
||||
abstract fun wallpaperCurrentDao(): WallpaperCurrentDao
|
||||
abstract fun excludedWallpaperDao(): ExcludedWallpaperDao
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.anthonyla.paperize.data.database.converters
|
||||
|
||||
import androidx.room.TypeConverter
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
|
||||
/**
|
||||
* Room type converters for enum types
|
||||
*/
|
||||
class TypeConverters {
|
||||
@TypeConverter
|
||||
fun fromScreenType(value: ScreenType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toScreenType(value: String): ScreenType = ScreenType.fromString(value)
|
||||
|
||||
@TypeConverter
|
||||
fun fromScalingType(value: ScalingType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toScalingType(value: String): ScalingType = ScalingType.fromString(value)
|
||||
|
||||
@TypeConverter
|
||||
fun fromWallpaperSourceType(value: WallpaperSourceType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toWallpaperSourceType(value: String): WallpaperSourceType =
|
||||
WallpaperSourceType.entries.find { it.name == value } ?: WallpaperSourceType.DIRECT
|
||||
|
||||
@TypeConverter
|
||||
fun fromWallpaperMediaType(value: WallpaperMediaType): String = value.name
|
||||
|
||||
@TypeConverter
|
||||
fun toWallpaperMediaType(value: String): WallpaperMediaType =
|
||||
WallpaperMediaType.fromString(value) ?: WallpaperMediaType.IMAGE
|
||||
}
|
||||
@@ -1,26 +1,17 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity
|
||||
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Album operations
|
||||
*/
|
||||
@Dao
|
||||
interface AlbumDao {
|
||||
/**
|
||||
* Get all album summaries (lightweight metadata + counts)
|
||||
* Efficiently handles large libraries by avoiding loading all wallpaper objects
|
||||
*/
|
||||
@Query("""
|
||||
SELECT
|
||||
a.id,
|
||||
@@ -35,89 +26,31 @@ interface AlbumDao {
|
||||
""")
|
||||
fun getAlbumSummaries(): Flow<List<AlbumSummaryEntity>>
|
||||
|
||||
/**
|
||||
* Get all albums with their wallpapers and folders
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM albums ORDER BY modifiedAt DESC")
|
||||
fun getAllAlbumsWithDetails(): Flow<List<AlbumWithDetails>>
|
||||
|
||||
/**
|
||||
* Get a specific album by ID with details
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM albums WHERE id = :albumId")
|
||||
fun getAlbumWithDetails(albumId: String): Flow<AlbumWithDetails?>
|
||||
|
||||
/**
|
||||
* Get all albums (without relations)
|
||||
*/
|
||||
@Query("SELECT * FROM albums ORDER BY modifiedAt DESC")
|
||||
fun getAllAlbums(): Flow<List<AlbumEntity>>
|
||||
|
||||
/**
|
||||
* Get a specific album by ID
|
||||
*/
|
||||
@Query("SELECT * FROM albums WHERE id = :albumId")
|
||||
suspend fun getAlbumById(albumId: String): AlbumEntity?
|
||||
|
||||
/**
|
||||
* Get a specific album by name
|
||||
*/
|
||||
@Query("SELECT * FROM albums WHERE name = :name LIMIT 1")
|
||||
suspend fun getAlbumByName(name: String): AlbumEntity?
|
||||
|
||||
/**
|
||||
* Get album count
|
||||
*/
|
||||
@Query("SELECT COUNT(*) FROM albums")
|
||||
suspend fun getAlbumCount(): Int
|
||||
|
||||
/**
|
||||
* Insert album
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertAlbum(album: AlbumEntity)
|
||||
|
||||
/**
|
||||
* Update album
|
||||
*/
|
||||
@Update
|
||||
suspend fun updateAlbum(album: AlbumEntity)
|
||||
|
||||
/**
|
||||
* Delete album
|
||||
*/
|
||||
@Delete
|
||||
suspend fun deleteAlbum(album: AlbumEntity)
|
||||
|
||||
/**
|
||||
* Delete album by ID
|
||||
*/
|
||||
@Query("DELETE FROM albums WHERE id = :albumId")
|
||||
suspend fun deleteAlbumById(albumId: String)
|
||||
|
||||
/**
|
||||
* Update album name
|
||||
*/
|
||||
@Query("UPDATE albums SET name = :name, modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumName(albumId: String, name: String, modifiedAt: Long)
|
||||
suspend fun renameAlbum(albumId: String, name: String, modifiedAt: Long): Int
|
||||
|
||||
@Query("UPDATE albums SET filter = :filter, modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun setFilter(albumId: String, filter: String?, modifiedAt: Long): Int
|
||||
|
||||
/**
|
||||
* Update album cover
|
||||
*/
|
||||
@Query("UPDATE albums SET coverUri = :coverUri, modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumCover(albumId: String, coverUri: String?, modifiedAt: Long)
|
||||
|
||||
/**
|
||||
* Update album modified time
|
||||
*/
|
||||
@Query("UPDATE albums SET modifiedAt = :modifiedAt WHERE id = :albumId")
|
||||
suspend fun updateAlbumModifiedTime(albumId: String, modifiedAt: Long)
|
||||
|
||||
/**
|
||||
* Delete all albums
|
||||
*/
|
||||
@Query("DELETE FROM albums")
|
||||
suspend fun deleteAllAlbums()
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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.data.database.entities.ExcludedWallpaperEntity
|
||||
|
||||
@Dao
|
||||
interface ExcludedWallpaperDao {
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insert(entity: ExcludedWallpaperEntity)
|
||||
|
||||
@Query("SELECT uri FROM excluded_wallpapers WHERE folderId = :folderId")
|
||||
suspend fun getUris(folderId: String): List<String>
|
||||
|
||||
@Query("DELETE FROM excluded_wallpapers WHERE folderId = :folderId AND uri IN (:uris)")
|
||||
suspend fun deleteUris(folderId: String, uris: List<String>)
|
||||
}
|
||||
@@ -1,68 +1,45 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Transaction
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Folder operations
|
||||
*/
|
||||
@Dao
|
||||
interface FolderDao {
|
||||
/**
|
||||
* Get all folders for an album with their wallpapers
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM folders WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
fun getFoldersWithWallpapersByAlbum(albumId: String): Flow<List<FolderWithWallpapers>>
|
||||
@Query("SELECT * FROM folders WHERE albumId = :albumId ORDER BY displayOrder, id")
|
||||
suspend fun getFoldersByAlbum(albumId: String): List<FolderEntity>
|
||||
|
||||
@Query("DELETE FROM folders WHERE id = :folderId AND albumId = :albumId")
|
||||
suspend fun deleteAlbumFolder(albumId: String, folderId: String): Int
|
||||
|
||||
@Query("SELECT EXISTS(SELECT 1 FROM folders WHERE albumId = :albumId AND uri = :uri)")
|
||||
suspend fun containsUri(albumId: String, uri: String): Boolean
|
||||
|
||||
@Query("SELECT COALESCE(MAX(displayOrder), -1) FROM folders WHERE albumId = :albumId")
|
||||
suspend fun getMaxOrder(albumId: String): Int
|
||||
|
||||
/**
|
||||
* Get a specific folder by ID with wallpapers
|
||||
*/
|
||||
@Transaction
|
||||
@Query("SELECT * FROM folders WHERE id = :folderId")
|
||||
fun getFolderWithWallpapers(folderId: String): Flow<FolderWithWallpapers?>
|
||||
|
||||
/**
|
||||
* Get a specific folder by ID
|
||||
*/
|
||||
@Query("SELECT * FROM folders WHERE id = :folderId")
|
||||
suspend fun getFolderById(folderId: String): FolderEntity?
|
||||
|
||||
/**
|
||||
* Get folder by URI
|
||||
*/
|
||||
@Query("SELECT * FROM folders WHERE uri = :uri LIMIT 1")
|
||||
suspend fun getFolderByUri(uri: String): FolderEntity?
|
||||
|
||||
/**
|
||||
* Insert folder
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertFolder(folder: FolderEntity)
|
||||
|
||||
/**
|
||||
* Update folder
|
||||
*/
|
||||
@Update
|
||||
suspend fun updateFolder(folder: FolderEntity)
|
||||
|
||||
/**
|
||||
* Update folder cover
|
||||
*/
|
||||
@Query("UPDATE folders SET coverUri = :coverUri WHERE id = :folderId")
|
||||
suspend fun updateFolderCover(folderId: String, coverUri: String?)
|
||||
|
||||
/**
|
||||
* Delete folder by ID
|
||||
*/
|
||||
@Query("DELETE FROM folders WHERE id = :folderId")
|
||||
suspend fun deleteFolderById(folderId: String)
|
||||
@Query("""
|
||||
UPDATE folders SET coverUri = (
|
||||
SELECT uri FROM wallpapers WHERE folderId = folders.id ORDER BY displayOrder, id LIMIT 1
|
||||
) WHERE albumId = :albumId
|
||||
""")
|
||||
suspend fun refreshFolderCovers(albumId: String)
|
||||
}
|
||||
@@ -12,19 +12,7 @@ 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. */
|
||||
/** Emits null until a wallpaper is applied, and again if that wallpaper or album is deleted. */
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_current wc ON w.id = wc.wallpaperId
|
||||
@@ -33,7 +21,6 @@ interface WallpaperCurrentDao {
|
||||
""")
|
||||
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)
|
||||
}
|
||||
@@ -1,150 +1,46 @@
|
||||
package com.anthonyla.paperize.data.database.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Delete
|
||||
import androidx.room.Insert
|
||||
import androidx.room.OnConflictStrategy
|
||||
import androidx.room.Query
|
||||
import androidx.room.Update
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/**
|
||||
* Data Access Object for Wallpaper operations
|
||||
*/
|
||||
@Dao
|
||||
interface WallpaperDao {
|
||||
/**
|
||||
* Get all wallpapers for an album
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
fun getWallpapersByAlbum(albumId: String): Flow<List<WallpaperEntity>>
|
||||
@Query("DELETE FROM wallpapers WHERE albumId = :albumId AND id IN (:ids)")
|
||||
suspend fun deleteAlbumWallpapers(albumId: String, ids: List<String>): Int
|
||||
|
||||
/**
|
||||
* Get direct wallpapers for an album (not from folders)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND folderId IS NULL ORDER BY displayOrder ASC")
|
||||
fun getDirectWallpapersByAlbum(albumId: String): Flow<List<WallpaperEntity>>
|
||||
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId AND folderId IS :folderId")
|
||||
suspend fun getUrisInCollection(albumId: String, folderId: String?): List<String>
|
||||
|
||||
/**
|
||||
* Get all wallpapers for an album (synchronous for transactions)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC")
|
||||
suspend fun getWallpapersByAlbumSync(albumId: String): List<WallpaperEntity>
|
||||
@Query("DELETE FROM wallpapers WHERE albumId = :albumId AND folderId = :folderId AND uri IN (:uris)")
|
||||
suspend fun deleteFolderWallpapersByUris(albumId: String, folderId: String, uris: List<String>): Int
|
||||
|
||||
/**
|
||||
* Get wallpapers for an album (paginated for memory-intensive operations)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder ASC LIMIT :limit OFFSET :offset")
|
||||
suspend fun getWallpapersByAlbumPaged(albumId: String, limit: Int, offset: Int): List<WallpaperEntity>
|
||||
@Query("SELECT COALESCE(MAX(displayOrder), -1) FROM wallpapers WHERE albumId = :albumId")
|
||||
suspend fun getMaxOrder(albumId: String): Int
|
||||
|
||||
/**
|
||||
* Get direct wallpapers for an album (synchronous for transactions)
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND folderId IS NULL ORDER BY displayOrder ASC")
|
||||
suspend fun getDirectWallpapersByAlbumSync(albumId: String): List<WallpaperEntity>
|
||||
@Query("SELECT * FROM wallpapers WHERE albumId = :albumId AND (:afterId IS NULL OR id > :afterId) ORDER BY id LIMIT :limit")
|
||||
suspend fun getWallpapersByAlbumPage(albumId: String, limit: Int, afterId: String?): List<WallpaperEntity>
|
||||
|
||||
/**
|
||||
* Get wallpapers for a folder
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE folderId = :folderId ORDER BY displayOrder ASC")
|
||||
fun getWallpapersByFolder(folderId: String): Flow<List<WallpaperEntity>>
|
||||
@Query("SELECT uri FROM wallpapers WHERE albumId = :albumId ORDER BY folderId IS NOT NULL, displayOrder, id LIMIT 1")
|
||||
suspend fun getAlbumCoverUri(albumId: String): String?
|
||||
|
||||
@Query("SELECT uri FROM wallpapers WHERE folderId = :folderId ORDER BY displayOrder, id LIMIT 1")
|
||||
suspend fun getFolderCoverUri(folderId: String): String?
|
||||
|
||||
/**
|
||||
* Get a specific wallpaper by ID
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE id = :wallpaperId")
|
||||
suspend fun getWallpaperById(wallpaperId: String): WallpaperEntity?
|
||||
|
||||
/**
|
||||
* Get wallpaper by URI
|
||||
*/
|
||||
@Query("SELECT * FROM wallpapers WHERE uri = :uri LIMIT 1")
|
||||
suspend fun getWallpaperByUri(uri: String): WallpaperEntity?
|
||||
|
||||
/**
|
||||
* Insert wallpaper
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
/**
|
||||
* Insert multiple wallpapers
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertWallpapers(wallpapers: List<WallpaperEntity>)
|
||||
|
||||
/**
|
||||
* Update wallpaper
|
||||
*/
|
||||
@Update
|
||||
suspend fun updateWallpaper(wallpaper: WallpaperEntity)
|
||||
@Query("SELECT * FROM wallpapers WHERE folderId = :folderId")
|
||||
suspend fun getFolderWallpapers(folderId: String): List<WallpaperEntity>
|
||||
|
||||
/**
|
||||
* Update wallpaper display order
|
||||
*/
|
||||
@Query("UPDATE wallpapers SET displayOrder = :order WHERE id = :wallpaperId")
|
||||
suspend fun updateWallpaperOrder(wallpaperId: String, order: Int)
|
||||
|
||||
/**
|
||||
* Delete wallpaper
|
||||
*/
|
||||
@Delete
|
||||
suspend fun deleteWallpaper(wallpaper: WallpaperEntity)
|
||||
|
||||
/**
|
||||
* Delete wallpaper by ID
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE id = :wallpaperId")
|
||||
suspend fun deleteWallpaperById(wallpaperId: String)
|
||||
|
||||
/**
|
||||
* Delete wallpapers by IDs (batch operation)
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE id IN (:wallpaperIds)")
|
||||
suspend fun deleteWallpapersByIds(wallpaperIds: List<String>)
|
||||
|
||||
/**
|
||||
* Delete all wallpapers for a folder
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE folderId = :folderId")
|
||||
suspend fun deleteWallpapersByFolder(folderId: String)
|
||||
|
||||
/**
|
||||
* Delete wallpapers by URIs
|
||||
*/
|
||||
@Query("DELETE FROM wallpapers WHERE uri IN (:uris)")
|
||||
suspend fun deleteWallpapersByUris(uris: List<String>)
|
||||
|
||||
/**
|
||||
* Get total wallpaper count for an album
|
||||
*/
|
||||
@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>
|
||||
@Query("SELECT id FROM wallpapers WHERE albumId = :albumId ORDER BY displayOrder, id")
|
||||
suspend fun getOrderedWallpaperIdsByAlbum(albumId: String): List<String>
|
||||
}
|
||||
|
||||
/** Lightweight projection used for queue building — avoids loading full WallpaperEntity. */
|
||||
data class WallpaperIdAndOrder(
|
||||
val id: String,
|
||||
val displayOrder: Int
|
||||
)
|
||||
@@ -9,16 +9,8 @@ import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperQueueEntity
|
||||
|
||||
/**
|
||||
* Data Access Object for Wallpaper Queue operations
|
||||
*
|
||||
* This replaces the manual queue management in the old Album entity
|
||||
*/
|
||||
@Dao
|
||||
interface WallpaperQueueDao {
|
||||
/**
|
||||
* Get next wallpaper in queue
|
||||
*/
|
||||
@Query("""
|
||||
SELECT w.* FROM wallpapers w
|
||||
INNER JOIN wallpaper_queue wq ON w.id = wq.wallpaperId
|
||||
@@ -28,39 +20,21 @@ interface WallpaperQueueDao {
|
||||
""")
|
||||
suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): WallpaperEntity?
|
||||
|
||||
/**
|
||||
* Atomically get and remove next wallpaper from queue
|
||||
* This prevents race conditions when multiple services try to get wallpapers simultaneously
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): WallpaperEntity? {
|
||||
val wallpaper = getNextWallpaperInQueue(albumId, screenType)
|
||||
if (wallpaper != null) {
|
||||
// Delete specifically the item we just retrieved to ensure atomicity
|
||||
deleteQueueItem(albumId, screenType, wallpaper.id)
|
||||
}
|
||||
return wallpaper
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue items for album and screen type
|
||||
*/
|
||||
@Query("SELECT * FROM wallpaper_queue WHERE albumId = :albumId AND screenType = :screenType ORDER BY queuePosition ASC")
|
||||
suspend fun getQueueItems(albumId: String, screenType: ScreenType): List<WallpaperQueueEntity>
|
||||
|
||||
/**
|
||||
* Insert multiple queue items
|
||||
*/
|
||||
@Insert(onConflict = OnConflictStrategy.REPLACE)
|
||||
suspend fun insertQueueItems(items: List<WallpaperQueueEntity>)
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -68,27 +42,41 @@ interface WallpaperQueueDao {
|
||||
""")
|
||||
suspend fun deleteQueueItem(albumId: String, screenType: ScreenType, wallpaperId: String)
|
||||
|
||||
/**
|
||||
* Clear queue for album and screen type
|
||||
*/
|
||||
@Query("""
|
||||
SELECT MIN(queuePosition) FROM wallpaper_queue
|
||||
WHERE albumId = :albumId AND screenType = :screenType
|
||||
""")
|
||||
suspend fun getFirstQueuePosition(albumId: String, screenType: ScreenType): Int?
|
||||
|
||||
@Transaction
|
||||
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
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId AND screenType = :screenType")
|
||||
suspend fun clearQueue(albumId: String, screenType: ScreenType)
|
||||
|
||||
/**
|
||||
* Clear all queues for an album
|
||||
*/
|
||||
@Query("DELETE FROM wallpaper_queue WHERE albumId = :albumId")
|
||||
suspend fun clearAllQueues(albumId: String)
|
||||
|
||||
/**
|
||||
* Delete all queue items
|
||||
*/
|
||||
@Query("DELETE FROM wallpaper_queue")
|
||||
suspend fun deleteAllQueueItems()
|
||||
|
||||
/**
|
||||
* Rebuild queue with wallpaper IDs
|
||||
*/
|
||||
@Transaction
|
||||
suspend fun rebuildQueue(
|
||||
albumId: String,
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Room entity for Album
|
||||
*
|
||||
* Stores album metadata without nested collections to avoid CursorWindow issues
|
||||
*/
|
||||
@Entity(tableName = "albums")
|
||||
data class AlbumEntity(
|
||||
@PrimaryKey
|
||||
@@ -15,5 +11,7 @@ data class AlbumEntity(
|
||||
val name: String,
|
||||
val coverUri: String?,
|
||||
val createdAt: Long = System.currentTimeMillis(),
|
||||
val modifiedAt: Long = System.currentTimeMillis()
|
||||
val modifiedAt: Long = System.currentTimeMillis(),
|
||||
@ColumnInfo(defaultValue = "0") val isEncrypted: Boolean = false,
|
||||
val filter: String? = null
|
||||
)
|
||||
@@ -1,8 +1,5 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
/**
|
||||
* Entity for holding lightweight album summary query results
|
||||
*/
|
||||
data class AlbumSummaryEntity(
|
||||
val id: String,
|
||||
val name: String,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
|
||||
/** A folder image the user removed, so folder rescans skip it. Keeps the row to restore it as it was. */
|
||||
@Entity(
|
||||
tableName = "excluded_wallpapers",
|
||||
primaryKeys = ["folderId", "uri"],
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = FolderEntity::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["folderId"],
|
||||
onDelete = ForeignKey.CASCADE
|
||||
)
|
||||
]
|
||||
)
|
||||
data class ExcludedWallpaperEntity(
|
||||
val folderId: String,
|
||||
val uri: String,
|
||||
val id: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int,
|
||||
val addedAt: Long
|
||||
)
|
||||
@@ -1,16 +1,10 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Room entity for Folder
|
||||
*
|
||||
* No longer stores nested wallpapers - they're separate entities with foreign keys
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "folders",
|
||||
foreignKeys = [
|
||||
@@ -30,7 +24,6 @@ data class FolderEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
val name: String,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
@@ -33,12 +32,10 @@ import com.anthonyla.paperize.core.ScreenType
|
||||
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()
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.anthonyla.paperize.core.WallpaperMediaType
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
|
||||
/**
|
||||
* Room entity for Wallpaper
|
||||
*
|
||||
* Properly indexed foreign key to Album and optional foreign key to Folder
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "wallpapers",
|
||||
foreignKeys = [
|
||||
@@ -39,18 +31,18 @@ data class WallpaperEntity(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
@ColumnInfo(name = "folderId")
|
||||
val folderId: String? = null,
|
||||
|
||||
val uri: String,
|
||||
val fileName: String,
|
||||
val dateModified: Long,
|
||||
val displayOrder: Int = 0,
|
||||
val sourceType: WallpaperSourceType = WallpaperSourceType.DIRECT,
|
||||
// Legacy: always derived from [folderId] ("DIRECT" or "FOLDER").
|
||||
val sourceType: String = "DIRECT",
|
||||
val addedAt: Long = System.currentTimeMillis(),
|
||||
|
||||
val mediaType: WallpaperMediaType = WallpaperMediaType.IMAGE,
|
||||
// Legacy: Paperize only stores images.
|
||||
val mediaType: String = "IMAGE",
|
||||
)
|
||||
@@ -1,18 +1,11 @@
|
||||
package com.anthonyla.paperize.data.database.entities
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.ForeignKey
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
|
||||
/**
|
||||
* Room entity for Wallpaper Queue
|
||||
*
|
||||
* Properly manages wallpaper queues instead of storing them as JSON lists in Album
|
||||
* Separate queues for HOME and LOCK screens
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "wallpaper_queue",
|
||||
foreignKeys = [
|
||||
@@ -39,10 +32,8 @@ data class WallpaperQueueEntity(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
|
||||
@ColumnInfo(name = "albumId")
|
||||
val albumId: String,
|
||||
|
||||
@ColumnInfo(name = "wallpaperId")
|
||||
val wallpaperId: String,
|
||||
|
||||
val screenType: ScreenType,
|
||||
|
||||
@@ -6,12 +6,6 @@ import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
/**
|
||||
* Room relation combining Album with its Wallpapers and Folders
|
||||
*
|
||||
* This replaces the old AlbumWithWallpaperAndFolder but with proper foreign keys
|
||||
* No nested collections in entities - avoiding CursorWindow issues!
|
||||
*/
|
||||
data class AlbumWithDetails(
|
||||
@Embedded
|
||||
val album: AlbumEntity,
|
||||
@@ -29,19 +23,4 @@ data class AlbumWithDetails(
|
||||
entity = FolderEntity::class
|
||||
)
|
||||
val folders: List<FolderEntity> = emptyList()
|
||||
) {
|
||||
/**
|
||||
* Get direct wallpapers (not from folders)
|
||||
*/
|
||||
val directWallpapers: List<WallpaperEntity>
|
||||
get() = wallpapers.filter { it.folderId == null }
|
||||
|
||||
/**
|
||||
* Get total count including folder wallpapers
|
||||
*/
|
||||
fun getTotalWallpaperCount(folderWallpapers: Map<String, Int>): Int {
|
||||
val directCount = directWallpapers.size
|
||||
val folderCount = folders.sumOf { folderWallpapers[it.id] ?: 0 }
|
||||
return directCount + folderCount
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -2,12 +2,10 @@ package com.anthonyla.paperize.data.database.relations
|
||||
|
||||
import androidx.room.Embedded
|
||||
import androidx.room.Relation
|
||||
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
|
||||
/**
|
||||
* Room relation combining Folder with its Wallpapers
|
||||
*/
|
||||
data class FolderWithWallpapers(
|
||||
@Embedded
|
||||
val folder: FolderEntity,
|
||||
@@ -17,5 +15,12 @@ data class FolderWithWallpapers(
|
||||
entityColumn = "folderId",
|
||||
entity = WallpaperEntity::class
|
||||
)
|
||||
val wallpapers: List<WallpaperEntity> = emptyList()
|
||||
val wallpapers: List<WallpaperEntity> = emptyList(),
|
||||
|
||||
@Relation(
|
||||
parentColumn = "id",
|
||||
entityColumn = "folderId",
|
||||
entity = ExcludedWallpaperEntity::class
|
||||
)
|
||||
val excluded: List<ExcludedWallpaperEntity> = emptyList()
|
||||
)
|
||||
@@ -1,536 +0,0 @@
|
||||
package com.anthonyla.paperize.data.datastore
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.longPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.core.constants.PreferenceKeys
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.WallpaperEffects
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Context extension for DataStore
|
||||
*/
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = Constants.PREFERENCES_NAME
|
||||
)
|
||||
|
||||
/**
|
||||
* PreferencesManager - Clean interface for DataStore operations
|
||||
*
|
||||
* Replaces the old SettingsDataStore with better organization and type safety
|
||||
*/
|
||||
@Singleton
|
||||
class PreferencesManager @Inject constructor(
|
||||
context: Context
|
||||
) {
|
||||
private val dataStore = context.dataStore
|
||||
|
||||
// ============ App Settings ============
|
||||
|
||||
suspend fun getAppSettings(): AppSettings {
|
||||
val prefs = dataStore.data.first()
|
||||
return AppSettings(
|
||||
darkMode = prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)],
|
||||
dynamicTheming = prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] ?: false,
|
||||
animate = prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] ?: true,
|
||||
firstLaunch = prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] ?: true
|
||||
)
|
||||
}
|
||||
|
||||
fun getAppSettingsFlow(): Flow<AppSettings> = dataStore.data.map { prefs ->
|
||||
AppSettings(
|
||||
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
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun updateAppSettings(settings: AppSettings) {
|
||||
dataStore.edit { prefs ->
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Wallpaper Mode ============
|
||||
|
||||
/**
|
||||
* Get current wallpaper mode (STATIC or LIVE)
|
||||
* Defaults to STATIC for new installations and backward compatibility
|
||||
*/
|
||||
suspend fun getWallpaperMode(): WallpaperMode {
|
||||
val prefs = dataStore.data.first()
|
||||
val modeString = prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]
|
||||
return WallpaperMode.fromString(modeString)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get wallpaper mode as a Flow for reactive updates
|
||||
*/
|
||||
fun getWallpaperModeFlow(): Flow<WallpaperMode> = dataStore.data.map { prefs ->
|
||||
val modeString = prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)]
|
||||
WallpaperMode.fromString(modeString)
|
||||
}
|
||||
|
||||
/**
|
||||
* Update wallpaper mode
|
||||
* IMPORTANT: Caller should handle data reset when switching modes
|
||||
*/
|
||||
suspend fun updateWallpaperMode(mode: WallpaperMode) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[stringPreferencesKey(PreferenceKeys.WALLPAPER_MODE)] = mode.name
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Schedule Settings ============
|
||||
|
||||
suspend fun getScheduleSettings(): ScheduleSettings {
|
||||
val prefs = dataStore.data.first()
|
||||
return ScheduleSettings(
|
||||
enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
|
||||
separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
|
||||
shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
|
||||
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
|
||||
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
|
||||
homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
|
||||
lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
|
||||
liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
|
||||
homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
|
||||
lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
|
||||
liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
|
||||
homeEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
|
||||
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
),
|
||||
lockEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
|
||||
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
),
|
||||
liveEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
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
|
||||
),
|
||||
adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
|
||||
)
|
||||
}
|
||||
|
||||
fun getScheduleSettingsFlow(): Flow<ScheduleSettings> = dataStore.data.map { prefs ->
|
||||
ScheduleSettings(
|
||||
enableChanger = prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] ?: false,
|
||||
separateSchedules = prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] ?: false,
|
||||
shuffleEnabled = prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] ?: false,
|
||||
homeEnabled = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] ?: false,
|
||||
lockEnabled = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] ?: false,
|
||||
homeAlbumId = prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)],
|
||||
lockAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)],
|
||||
liveAlbumId = prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)],
|
||||
homeIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
lockIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
liveIntervalMinutes = prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)]
|
||||
?: Constants.DEFAULT_INTERVAL_MINUTES,
|
||||
homeScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)]),
|
||||
lockScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)]),
|
||||
liveScalingType = ScalingType.fromString(prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)]),
|
||||
homeEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] ?: false,
|
||||
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
),
|
||||
lockEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
enableParallax = prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] ?: false,
|
||||
parallaxIntensity = prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] ?: Constants.DEFAULT_PARALLAX_INTENSITY
|
||||
),
|
||||
liveEffects = WallpaperEffects(
|
||||
enableBlur = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] ?: false,
|
||||
blurPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] ?: 0,
|
||||
enableDarken = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] ?: false,
|
||||
darkenPercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] ?: 0,
|
||||
enableVignette = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] ?: false,
|
||||
vignettePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] ?: 0,
|
||||
enableGrayscale = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_GRAYSCALE)] ?: false,
|
||||
grayscalePercentage = prefs[intPreferencesKey(PreferenceKeys.LIVE_GRAYSCALE)] ?: 0,
|
||||
enableDoubleTap = prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DOUBLE_TAP)] ?: false,
|
||||
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
|
||||
),
|
||||
adaptiveBrightness = prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] ?: false
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun updateScheduleSettings(settings: ScheduleSettings) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] = settings.enableChanger
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES)] = settings.separateSchedules
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED)] = settings.shuffleEnabled
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLED)] = settings.homeEnabled
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED)] = settings.lockEnabled
|
||||
if (settings.homeAlbumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)] = settings.homeAlbumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
}
|
||||
if (settings.lockAlbumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)] = settings.lockAlbumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
|
||||
}
|
||||
if (settings.liveAlbumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)] = settings.liveAlbumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
|
||||
}
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES)] = settings.homeIntervalMinutes
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES)] = settings.lockIntervalMinutes
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES)] = settings.liveIntervalMinutes
|
||||
prefs[stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE)] = settings.homeScalingType.name
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE)] = settings.lockScalingType.name
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE)] = settings.liveScalingType.name
|
||||
|
||||
// Home effects
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR)] = settings.homeEffects.enableBlur
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_BLUR)] = settings.homeEffects.blurPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN)] = settings.homeEffects.enableDarken
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_DARKEN)] = settings.homeEffects.darkenPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE)] = settings.homeEffects.enableVignette
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_VIGNETTE)] = settings.homeEffects.vignettePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE)] = settings.homeEffects.enableGrayscale
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE)] = settings.homeEffects.grayscalePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP)] = settings.homeEffects.enableDoubleTap
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX)] = settings.homeEffects.enableParallax
|
||||
prefs[intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY)] = settings.homeEffects.parallaxIntensity
|
||||
|
||||
// Lock effects
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR)] = settings.lockEffects.enableBlur
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_BLUR)] = settings.lockEffects.blurPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN)] = settings.lockEffects.enableDarken
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_DARKEN)] = settings.lockEffects.darkenPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE)] = settings.lockEffects.enableVignette
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE)] = settings.lockEffects.vignettePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE)] = settings.lockEffects.enableGrayscale
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE)] = settings.lockEffects.grayscalePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP)] = settings.lockEffects.enableDoubleTap
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX)] = settings.lockEffects.enableParallax
|
||||
prefs[intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY)] = settings.lockEffects.parallaxIntensity
|
||||
|
||||
// Live effects
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR)] = settings.liveEffects.enableBlur
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_BLUR)] = settings.liveEffects.blurPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN)] = settings.liveEffects.enableDarken
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_DARKEN)] = settings.liveEffects.darkenPercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE)] = settings.liveEffects.enableVignette
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE)] = settings.liveEffects.vignettePercentage
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_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_OFF)] = settings.liveEffects.enableChangeOnScreenOff
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX)] = settings.liveEffects.enableParallax
|
||||
prefs[intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY)] = settings.liveEffects.parallaxIntensity
|
||||
|
||||
// Adaptive brightness
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS)] = settings.adaptiveBrightness
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Atomic Album Selection Operations ============
|
||||
|
||||
/**
|
||||
* Atomically update home album ID without race conditions
|
||||
* This prevents lost updates when both home and lock albums are selected simultaneously
|
||||
*/
|
||||
suspend fun updateHomeAlbumId(albumId: String?) {
|
||||
dataStore.edit { prefs ->
|
||||
if (albumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID)] = albumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update lock album ID without race conditions
|
||||
* This prevents lost updates when both home and lock albums are selected simultaneously
|
||||
*/
|
||||
suspend fun updateLockAlbumId(albumId: String?) {
|
||||
dataStore.edit { prefs ->
|
||||
if (albumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID)] = albumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update live album ID without race conditions
|
||||
*/
|
||||
suspend fun updateLiveAlbumId(albumId: String?) {
|
||||
dataStore.edit { prefs ->
|
||||
if (albumId != null) {
|
||||
prefs[stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID)] = albumId
|
||||
} else {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically clear album selections if they match the given album ID
|
||||
* Used when deleting an album to prevent race conditions
|
||||
* Returns true if any selections were cleared
|
||||
*/
|
||||
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)]
|
||||
|
||||
// Clear home album if it matches
|
||||
if (homeAlbumId == albumId) {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
wasCleared = true
|
||||
}
|
||||
|
||||
// Clear lock album if it matches
|
||||
if (lockAlbumId == albumId) {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
|
||||
wasCleared = true
|
||||
}
|
||||
|
||||
// Clear live album if it matches
|
||||
if (liveAlbumId == albumId) {
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
|
||||
wasCleared = true
|
||||
}
|
||||
}
|
||||
return wasCleared
|
||||
}
|
||||
|
||||
// ============ Atomic AppSettings Operations ============
|
||||
|
||||
/**
|
||||
* Atomically update dark mode setting without race conditions
|
||||
*/
|
||||
suspend fun updateDarkMode(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DARK_MODE)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update dynamic theming setting without race conditions
|
||||
*/
|
||||
suspend fun updateDynamicTheming(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.DYNAMIC_THEMING)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update animate setting without race conditions
|
||||
*/
|
||||
suspend fun updateAnimate(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ANIMATE)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically update first launch setting without race conditions
|
||||
*/
|
||||
suspend fun updateFirstLaunch(isFirstLaunch: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.FIRST_LAUNCH)] = isFirstLaunch
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Atomic ScheduleSettings Operations ============
|
||||
|
||||
/**
|
||||
* Atomically update enableChanger setting without race conditions
|
||||
*/
|
||||
suspend fun updateEnableChanger(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER)] = enabled
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Individual Preference Operations ============
|
||||
|
||||
suspend fun <T> setValue(key: String, value: T) {
|
||||
dataStore.edit { prefs ->
|
||||
when (value) {
|
||||
is Boolean -> prefs[booleanPreferencesKey(key)] = value
|
||||
is Int -> prefs[intPreferencesKey(key)] = value
|
||||
is Long -> prefs[longPreferencesKey(key)] = value
|
||||
is String -> prefs[stringPreferencesKey(key)] = value
|
||||
else -> throw IllegalArgumentException("Unsupported preference type")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun <T> getValue(key: String, defaultValue: T): T {
|
||||
val prefs = dataStore.data.first()
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return when (defaultValue) {
|
||||
is Boolean -> prefs[booleanPreferencesKey(key)] ?: defaultValue
|
||||
is Int -> prefs[intPreferencesKey(key)] ?: defaultValue
|
||||
is Long -> prefs[longPreferencesKey(key)] ?: defaultValue
|
||||
is String -> prefs[stringPreferencesKey(key)] ?: defaultValue
|
||||
else -> throw IllegalArgumentException("Unsupported preference type")
|
||||
} as T
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear schedule settings (reset to defaults)
|
||||
* Used when switching wallpaper modes
|
||||
*/
|
||||
suspend fun clearScheduleSettings() {
|
||||
dataStore.edit { prefs ->
|
||||
// Clear scheduling settings
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.ENABLE_CHANGER))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.SEPARATE_SCHEDULES))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.SHUFFLE_ENABLED))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLED))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLED))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_ALBUM_ID))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_ALBUM_ID))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_ALBUM_ID))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_INTERVAL_MINUTES))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_INTERVAL_MINUTES))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_INTERVAL_MINUTES))
|
||||
|
||||
// Clear home effects
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_BLUR))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_BLUR))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DARKEN))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_DARKEN))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_VIGNETTE))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_VIGNETTE))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_GRAYSCALE))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_GRAYSCALE))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_DOUBLE_TAP))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.HOME_ENABLE_PARALLAX))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.HOME_PARALLAX_INTENSITY))
|
||||
|
||||
// Clear lock effects
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_BLUR))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_BLUR))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DARKEN))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_DARKEN))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_VIGNETTE))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_VIGNETTE))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_GRAYSCALE))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_GRAYSCALE))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_DOUBLE_TAP))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LOCK_ENABLE_PARALLAX))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LOCK_PARALLAX_INTENSITY))
|
||||
|
||||
// Clear live effects
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_BLUR))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_BLUR))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_DARKEN))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_DARKEN))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_VIGNETTE))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_VIGNETTE))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_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_OFF))
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.LIVE_ENABLE_PARALLAX))
|
||||
prefs.remove(intPreferencesKey(PreferenceKeys.LIVE_PARALLAX_INTENSITY))
|
||||
|
||||
// Clear scaling
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.HOME_SCALING_TYPE))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LOCK_SCALING_TYPE))
|
||||
prefs.remove(stringPreferencesKey(PreferenceKeys.LIVE_SCALING_TYPE))
|
||||
|
||||
// Clear adaptive brightness
|
||||
prefs.remove(booleanPreferencesKey(PreferenceKeys.ADAPTIVE_BRIGHTNESS))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun clear() {
|
||||
dataStore.edit { it.clear() }
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity
|
||||
import com.anthonyla.paperize.data.database.relations.AlbumWithDetails
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
|
||||
/**
|
||||
* Mappers for Album entity <-> domain model conversion
|
||||
*/
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
fun AlbumEntity.toDomainModel(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList(),
|
||||
folders: List<com.anthonyla.paperize.domain.model.Folder> = emptyList()
|
||||
wallpapers: List<Wallpaper> = emptyList(),
|
||||
folders: List<Folder> = emptyList()
|
||||
): Album = Album(
|
||||
id = id,
|
||||
name = name,
|
||||
@@ -18,7 +18,9 @@ fun AlbumEntity.toDomainModel(
|
||||
wallpapers = wallpapers,
|
||||
folders = folders,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
modifiedAt = modifiedAt,
|
||||
isEncrypted = isEncrypted,
|
||||
filter = filter
|
||||
)
|
||||
|
||||
fun Album.toEntity(): AlbumEntity = AlbumEntity(
|
||||
@@ -26,11 +28,12 @@ fun Album.toEntity(): AlbumEntity = AlbumEntity(
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
modifiedAt = modifiedAt,
|
||||
isEncrypted = isEncrypted,
|
||||
filter = filter
|
||||
)
|
||||
|
||||
fun AlbumWithDetails.toDomainModel(): Album {
|
||||
// Optimization: Group wallpapers by folderId once to avoid repeated filtering
|
||||
val wallpapersByFolder = wallpapers.groupBy { it.folderId }
|
||||
|
||||
val domainWallpapers = wallpapersByFolder[null]?.map { it.toDomainModel() } ?: emptyList()
|
||||
@@ -46,20 +49,12 @@ fun AlbumWithDetails.toDomainModel(): Album {
|
||||
)
|
||||
}
|
||||
|
||||
fun List<AlbumEntity>.toDomainModels(): List<Album> = map { it.toDomainModel() }
|
||||
|
||||
fun List<AlbumWithDetails>.toDomainModelsFromRelations(): List<Album> = map { it.toDomainModel() }
|
||||
|
||||
fun com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity.toDomainModel(): com.anthonyla.paperize.domain.model.AlbumSummary =
|
||||
com.anthonyla.paperize.domain.model.AlbumSummary(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
wallpaperCount = wallpaperCount,
|
||||
folderCount = folderCount,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
)
|
||||
|
||||
fun List<com.anthonyla.paperize.data.database.entities.AlbumSummaryEntity>.toDomainModelsFromSummaries(): List<com.anthonyla.paperize.domain.model.AlbumSummary> =
|
||||
map { it.toDomainModel() }
|
||||
fun AlbumSummaryEntity.toDomainModel(): AlbumSummary = AlbumSummary(
|
||||
id = id,
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
wallpaperCount = wallpaperCount,
|
||||
folderCount = folderCount,
|
||||
createdAt = createdAt,
|
||||
modifiedAt = modifiedAt
|
||||
)
|
||||
@@ -3,13 +3,11 @@ package com.anthonyla.paperize.data.mapper
|
||||
import com.anthonyla.paperize.data.database.entities.FolderEntity
|
||||
import com.anthonyla.paperize.data.database.relations.FolderWithWallpapers
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
|
||||
/**
|
||||
* Mappers for Folder entity <-> domain model conversion
|
||||
*/
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
fun FolderEntity.toDomainModel(
|
||||
wallpapers: List<com.anthonyla.paperize.domain.model.Wallpaper> = emptyList()
|
||||
wallpapers: List<Wallpaper> = emptyList(),
|
||||
removedWallpapers: List<Wallpaper> = emptyList()
|
||||
): Folder = Folder(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
@@ -19,6 +17,7 @@ fun FolderEntity.toDomainModel(
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
wallpapers = wallpapers,
|
||||
removedWallpapers = removedWallpapers,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
@@ -34,9 +33,6 @@ fun Folder.toEntity(): FolderEntity = FolderEntity(
|
||||
)
|
||||
|
||||
fun FolderWithWallpapers.toDomainModel(): Folder = folder.toDomainModel(
|
||||
wallpapers = wallpapers.map { it.toDomainModel() }
|
||||
wallpapers = wallpapers.map { it.toDomainModel() },
|
||||
removedWallpapers = excluded.map { it.toDomainModel(folder.albumId) }
|
||||
)
|
||||
|
||||
fun List<FolderEntity>.toDomainModels(): List<Folder> = map { it.toDomainModel() }
|
||||
|
||||
fun List<FolderWithWallpapers>.toDomainModelsFromRelations(): List<Folder> = map { it.toDomainModel() }
|
||||
@@ -1,12 +1,9 @@
|
||||
package com.anthonyla.paperize.data.mapper
|
||||
|
||||
import com.anthonyla.paperize.data.database.entities.ExcludedWallpaperEntity
|
||||
import com.anthonyla.paperize.data.database.entities.WallpaperEntity
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
|
||||
/**
|
||||
* Mappers for Wallpaper entity <-> domain model conversion
|
||||
*/
|
||||
|
||||
fun WallpaperEntity.toDomainModel(): Wallpaper = Wallpaper(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
@@ -15,9 +12,7 @@ fun WallpaperEntity.toDomainModel(): Wallpaper = Wallpaper(
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
sourceType = sourceType,
|
||||
addedAt = addedAt,
|
||||
mediaType = mediaType
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
|
||||
@@ -28,11 +23,27 @@ fun Wallpaper.toEntity(): WallpaperEntity = WallpaperEntity(
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
sourceType = sourceType,
|
||||
addedAt = addedAt,
|
||||
mediaType = mediaType
|
||||
sourceType = if (folderId == null) "DIRECT" else "FOLDER",
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun List<WallpaperEntity>.toDomainModels(): List<Wallpaper> = map { it.toDomainModel() }
|
||||
fun ExcludedWallpaperEntity.toDomainModel(albumId: String): Wallpaper = Wallpaper(
|
||||
id = id,
|
||||
albumId = albumId,
|
||||
folderId = folderId,
|
||||
uri = uri,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
addedAt = addedAt
|
||||
)
|
||||
|
||||
fun List<Wallpaper>.toEntities(): List<WallpaperEntity> = map { it.toEntity() }
|
||||
fun Wallpaper.toExcludedEntity(folderId: String): ExcludedWallpaperEntity = ExcludedWallpaperEntity(
|
||||
folderId = folderId,
|
||||
uri = uri,
|
||||
id = id,
|
||||
fileName = fileName,
|
||||
dateModified = dateModified,
|
||||
displayOrder = displayOrder,
|
||||
addedAt = addedAt
|
||||
)
|
||||
@@ -1,360 +1,245 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import androidx.room.withTransaction
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import com.anthonyla.paperize.core.util.generateId
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.database.dao.AlbumDao
|
||||
import com.anthonyla.paperize.data.database.dao.FolderDao
|
||||
import com.anthonyla.paperize.data.database.dao.WallpaperDao
|
||||
import com.anthonyla.paperize.data.database.entities.AlbumEntity
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModel
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModelsFromRelations
|
||||
import com.anthonyla.paperize.data.mapper.toDomainModelsFromSummaries
|
||||
import com.anthonyla.paperize.data.mapper.toEntities
|
||||
import com.anthonyla.paperize.data.mapper.toEntity
|
||||
import com.anthonyla.paperize.data.mapper.toExcludedEntity
|
||||
import com.anthonyla.paperize.domain.model.Album
|
||||
import com.anthonyla.paperize.domain.model.AlbumSummary
|
||||
import com.anthonyla.paperize.domain.model.Folder
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Implementation of AlbumRepository
|
||||
*
|
||||
* Handles data operations for albums using Room database
|
||||
*/
|
||||
@Singleton
|
||||
class AlbumRepositoryImpl @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val database: PaperizeDatabase,
|
||||
private val albumDao: AlbumDao,
|
||||
private val wallpaperDao: WallpaperDao,
|
||||
private val folderDao: FolderDao,
|
||||
private val wallpaperRepository: dagger.Lazy<com.anthonyla.paperize.domain.repository.WallpaperRepository>
|
||||
private val documents: DocumentSource,
|
||||
private val database: PaperizeDatabase
|
||||
) : AlbumRepository {
|
||||
private val albumDao = database.albumDao()
|
||||
private val wallpaperDao = database.wallpaperDao()
|
||||
private val folderDao = database.folderDao()
|
||||
private val excludedDao = database.excludedWallpaperDao()
|
||||
|
||||
companion object {
|
||||
/** Number of wallpapers written per insert/progress step during an import. */
|
||||
private const val WALLPAPER_INSERT_CHUNK_SIZE = 500
|
||||
private const val WALLPAPER_BATCH_SIZE = 500
|
||||
}
|
||||
|
||||
override fun getAlbumSummaries(): Flow<List<AlbumSummary>> =
|
||||
albumDao.getAlbumSummaries().map { it.toDomainModelsFromSummaries() }
|
||||
|
||||
override fun getAllAlbums(): Flow<List<Album>> =
|
||||
albumDao.getAllAlbumsWithDetails().map { it.toDomainModelsFromRelations() }
|
||||
albumDao.getAlbumSummaries().map { it.map { summary -> summary.toDomainModel() } }
|
||||
|
||||
override fun getAlbumById(albumId: String): Flow<Album?> =
|
||||
albumDao.getAlbumWithDetails(albumId).map { it?.toDomainModel() }
|
||||
|
||||
override suspend fun getAlbumByName(name: String): Album? =
|
||||
albumDao.getAlbumByName(name)?.toDomainModel()
|
||||
override suspend fun getAlbumEncryption(albumId: String): Boolean? =
|
||||
albumDao.getAlbumById(albumId)?.isEncrypted
|
||||
|
||||
override fun getFolderById(folderId: String): Flow<Folder?> =
|
||||
folderDao.getFolderWithWallpapers(folderId).map { it?.toDomainModel() }
|
||||
|
||||
override suspend fun createAlbum(name: String, coverUri: String?): Result<Album> {
|
||||
return try {
|
||||
val album = Album(
|
||||
id = generateId(),
|
||||
name = name,
|
||||
coverUri = coverUri,
|
||||
createdAt = System.currentTimeMillis(),
|
||||
modifiedAt = System.currentTimeMillis()
|
||||
)
|
||||
albumDao.insertAlbum(album.toEntity())
|
||||
Result.Success(album)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
override suspend fun createAlbum(name: String, coverUri: String?, isEncrypted: Boolean): Album {
|
||||
val now = System.currentTimeMillis()
|
||||
val album = Album(id = generateId(), name = name, coverUri = coverUri, createdAt = now, modifiedAt = now, isEncrypted = isEncrypted)
|
||||
albumDao.insertAlbum(album.toEntity())
|
||||
return album
|
||||
}
|
||||
|
||||
override suspend fun updateAlbum(album: Album): Result<Unit> {
|
||||
return try {
|
||||
albumDao.updateAlbum(album.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
override suspend fun deleteAlbum(albumId: String) {
|
||||
albumDao.deleteAlbumById(albumId)
|
||||
}
|
||||
|
||||
override suspend fun deleteAlbum(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
database.withTransaction {
|
||||
albumDao.deleteAlbumById(albumId)
|
||||
wallpaperRepository.get().clearQueuesForAlbum(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
override suspend fun renameAlbum(albumId: String, name: String): Boolean = database.withTransaction {
|
||||
if (albumDao.getAlbumSummaries().first().any { it.id != albumId && it.name.equals(name, ignoreCase = true) }) {
|
||||
return@withTransaction false
|
||||
}
|
||||
check(albumDao.renameAlbum(albumId, name, System.currentTimeMillis()) == 1)
|
||||
true
|
||||
}
|
||||
|
||||
override suspend fun updateAlbumName(albumId: String, name: String): Result<Unit> {
|
||||
return try {
|
||||
albumDao.updateAlbumName(albumId, name, System.currentTimeMillis())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateAlbumCover(albumId: String, coverUri: String?): Result<Unit> {
|
||||
return try {
|
||||
albumDao.updateAlbumCover(albumId, coverUri, System.currentTimeMillis())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
override suspend fun setAlbumFilter(albumId: String, filter: String?) = database.withTransaction {
|
||||
check(albumDao.setFilter(albumId, filter?.takeIf { it.isNotBlank() }, System.currentTimeMillis()) == 1)
|
||||
database.wallpaperQueueDao().clearAllQueues(albumId)
|
||||
}
|
||||
|
||||
override suspend fun addWallpapersToAlbum(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (saved: Int, total: Int) -> Unit
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - insert wallpapers, update timestamp, and update cover
|
||||
database.withTransaction {
|
||||
insertWallpapersChunked(wallpapers, onProgress)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Update album cover if it doesn't have one
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
): Int = database.withTransaction {
|
||||
checkNotNull(albumDao.getAlbumById(albumId))
|
||||
insertNewWallpapers(albumId, wallpapers, onProgress)
|
||||
}
|
||||
|
||||
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
|
||||
insertWallpapersChunked(folder.wallpapers, onProgress)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Update album cover if it doesn't have one
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
): Boolean = database.withTransaction {
|
||||
checkNotNull(albumDao.getAlbumById(albumId))
|
||||
if (folderDao.containsUri(albumId, folder.uri)) return@withTransaction false
|
||||
folderDao.insertFolder(folder.toEntity().copy(
|
||||
albumId = albumId, displayOrder = folderDao.getMaxOrder(albumId) + 1, coverUri = null
|
||||
))
|
||||
insertNewWallpapers(albumId, folder.wallpapers.map { it.copy(folderId = folder.id) }, onProgress)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
true
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
override suspend fun syncFolderWallpapers(
|
||||
albumId: String,
|
||||
folderId: String,
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (Int, Int) -> Unit
|
||||
): Int = database.withTransaction {
|
||||
checkNotNull(albumDao.getAlbumById(albumId))
|
||||
val scanned = wallpapers.mapTo(HashSet()) { it.uri }
|
||||
// An empty scan can be an unavailable provider, so it removes nothing.
|
||||
val stale = if (scanned.isEmpty()) emptyList()
|
||||
else wallpaperDao.getUrisInCollection(albumId, folderId).filterNot { it in scanned }
|
||||
val excluded = excludedDao.getUris(folderId).toHashSet()
|
||||
if (scanned.isNotEmpty()) excluded.filterNot { it in scanned }.chunked(WALLPAPER_BATCH_SIZE).forEach {
|
||||
excludedDao.deleteUris(folderId, it)
|
||||
}
|
||||
var removed = 0
|
||||
stale.chunked(WALLPAPER_BATCH_SIZE).forEach {
|
||||
removed += wallpaperDao.deleteFolderWallpapersByUris(albumId, folderId, it)
|
||||
}
|
||||
val added = insertNewWallpapers(albumId, wallpapers.filterNot { it.uri in excluded }, onProgress)
|
||||
if (removed > 0) {
|
||||
folderDao.updateFolderCover(folderId, wallpaperDao.getFolderCoverUri(folderId))
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
private suspend fun insertNewWallpapers(
|
||||
albumId: String,
|
||||
wallpapers: List<Wallpaper>,
|
||||
onProgress: (Int, Int) -> Unit
|
||||
): Int {
|
||||
var nextOrder = wallpaperDao.getMaxOrder(albumId) + 1
|
||||
val additions = wallpapers.groupBy { it.folderId }.flatMap { (folderId, images) ->
|
||||
// A folder can be removed while its provider scan is in flight.
|
||||
if (folderId != null && folderDao.getFolderById(folderId)?.albumId != albumId) {
|
||||
emptyList()
|
||||
} else {
|
||||
val existing = wallpaperDao.getUrisInCollection(albumId, folderId).toHashSet()
|
||||
images.filter { existing.add(it.uri) }.map {
|
||||
it.copy(albumId = albumId, displayOrder = nextOrder++)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (additions.isEmpty()) return 0
|
||||
insertWallpapersChunked(additions, onProgress)
|
||||
additions.mapNotNull { it.folderId }.toSet().forEach { folderId ->
|
||||
folderDao.updateFolderCover(folderId, wallpaperDao.getFolderCoverUri(folderId))
|
||||
}
|
||||
database.wallpaperQueueDao().clearAllQueues(albumId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
return additions.size
|
||||
}
|
||||
|
||||
/** Report chunk progress within the caller's transaction; cancellation rolls back every chunk. */
|
||||
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())
|
||||
wallpapers.chunked(WALLPAPER_BATCH_SIZE).forEach { chunk ->
|
||||
wallpaperDao.insertWallpapers(chunk.map { it.toEntity() })
|
||||
saved += chunk.size
|
||||
onProgress(saved, total)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateFolder(folder: Folder): Result<Unit> {
|
||||
return try {
|
||||
folderDao.updateFolder(folder.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeWallpaperFromAlbum(
|
||||
albumId: String,
|
||||
wallpaperId: String
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - delete wallpaper, update timestamp, and refresh cover
|
||||
database.withTransaction {
|
||||
val wallpaper = wallpaperDao.getWallpaperById(wallpaperId)
|
||||
wallpaperDao.deleteWallpaperById(wallpaperId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Refresh cover if deleted wallpaper was the cover
|
||||
val album = albumDao.getAlbumById(albumId)
|
||||
if (album?.coverUri == wallpaper?.uri) {
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeWallpapersFromAlbum(
|
||||
albumId: String,
|
||||
wallpaperIds: List<String>
|
||||
): Result<Unit> {
|
||||
return try {
|
||||
if (wallpaperIds.isEmpty()) {
|
||||
return Result.Success(Unit)
|
||||
) {
|
||||
if (wallpaperIds.isEmpty()) return
|
||||
database.withTransaction {
|
||||
wallpaperIds.chunked(WALLPAPER_BATCH_SIZE).forEach {
|
||||
wallpaperDao.deleteAlbumWallpapers(albumId, it)
|
||||
}
|
||||
|
||||
// Atomic transaction - delete wallpapers, update timestamp, and refresh cover
|
||||
database.withTransaction {
|
||||
val album = albumDao.getAlbumById(albumId)
|
||||
val currentCoverUri = album?.coverUri
|
||||
|
||||
// Batch delete wallpapers
|
||||
wallpaperDao.deleteWallpapersByIds(wallpaperIds)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
|
||||
// Refresh cover if any deleted wallpaper was the cover
|
||||
// (we check by querying the album cover to see if it still exists)
|
||||
if (currentCoverUri != null) {
|
||||
val coverStillExists = wallpaperDao.getWallpaperByUri(currentCoverUri) != null
|
||||
if (!coverStillExists) {
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
}
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
folderDao.refreshFolderCovers(albumId)
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun removeFolderFromAlbum(albumId: String, folderId: String): Result<Unit> {
|
||||
return try {
|
||||
// Atomic transaction - delete folder, update timestamp, and refresh cover
|
||||
database.withTransaction {
|
||||
folderDao.deleteFolderById(folderId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
override suspend fun removeWallpaper(wallpaperId: String): Wallpaper? = database.withTransaction {
|
||||
val wallpaper = wallpaperDao.getWallpaperById(wallpaperId)?.toDomainModel() ?: return@withTransaction null
|
||||
wallpaper.folderId?.let { excludedDao.insert(wallpaper.toExcludedEntity(it)) }
|
||||
removeWallpapersFromAlbum(wallpaper.albumId, listOf(wallpaperId))
|
||||
wallpaper
|
||||
}
|
||||
|
||||
// Always refresh cover after folder deletion (folder wallpapers might be cover)
|
||||
override suspend fun restoreWallpaper(wallpaper: Wallpaper) = database.withTransaction {
|
||||
val albumId = wallpaper.albumId
|
||||
val folderId = wallpaper.folderId
|
||||
if (folderId != null) excludedDao.deleteUris(folderId, listOf(wallpaper.uri))
|
||||
// The same image can be imported again before an undo.
|
||||
if (wallpaper.uri in wallpaperDao.getUrisInCollection(albumId, folderId)) return@withTransaction
|
||||
wallpaperDao.insertWallpapers(listOf(wallpaper.toEntity()))
|
||||
database.wallpaperQueueDao().clearAllQueues(albumId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
folderDao.refreshFolderCovers(albumId)
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
|
||||
override suspend fun removeFolderFromAlbum(albumId: String, folderId: String) {
|
||||
database.withTransaction {
|
||||
folderDao.deleteAlbumFolder(albumId, folderId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteAllAlbums() {
|
||||
albumDao.deleteAllAlbums()
|
||||
}
|
||||
|
||||
override suspend fun pruneMissingEntries(albumId: String): Int {
|
||||
val missingFolders = folderDao.getFoldersByAlbum(albumId)
|
||||
.filter { documents.isMissing(it.uri, isTree = true) }.map { it.id }.toSet()
|
||||
val missingImages = mutableListOf<String>()
|
||||
var afterId: String? = null
|
||||
while (true) {
|
||||
val batch = wallpaperDao.getWallpapersByAlbumPage(albumId, WALLPAPER_BATCH_SIZE, afterId)
|
||||
if (batch.isEmpty()) break
|
||||
batch.filter { it.folderId !in missingFolders && documents.isMissing(it.uri) }
|
||||
.mapTo(missingImages) { it.id }
|
||||
afterId = batch.last().id
|
||||
}
|
||||
return database.withTransaction {
|
||||
var removed = missingFolders.sumOf { folderDao.deleteAlbumFolder(albumId, it) }
|
||||
missingImages.chunked(WALLPAPER_BATCH_SIZE).forEach {
|
||||
removed += wallpaperDao.deleteAlbumWallpapers(albumId, it)
|
||||
}
|
||||
if (removed > 0) {
|
||||
folderDao.refreshFolderCovers(albumId)
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
albumDao.updateAlbumModifiedTime(albumId, System.currentTimeMillis())
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
removed
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getAlbumCount(): Int = albumDao.getAlbumCount()
|
||||
|
||||
override suspend fun deleteAllAlbums(): Result<Unit> {
|
||||
return try {
|
||||
database.withTransaction {
|
||||
albumDao.deleteAllAlbums()
|
||||
wallpaperRepository.get().clearAllQueues()
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun validateAndRemoveInvalidFolders(albumId: String): Result<Int> {
|
||||
return try {
|
||||
val album = albumDao.getAlbumWithDetails(albumId).first() ?: return Result.Success(0)
|
||||
val folders = album.folders.map { it.toDomainModel() }
|
||||
|
||||
val invalidFolderIds = folders.filter { folder ->
|
||||
// Check if folder URI is still valid
|
||||
val uri = Uri.parse(folder.uri)
|
||||
val documentFile = DocumentFile.fromTreeUri(context, uri)
|
||||
documentFile == null || !documentFile.exists() || !documentFile.canRead()
|
||||
}.map { it.id }
|
||||
|
||||
if (invalidFolderIds.isNotEmpty()) {
|
||||
// Atomic transaction - delete all invalid folders or none
|
||||
database.withTransaction {
|
||||
invalidFolderIds.forEach { folderId ->
|
||||
folderDao.deleteFolderById(folderId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Result.Success(invalidFolderIds.size)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun refreshAlbumCover(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
database.withTransaction {
|
||||
updateAlbumCoverIfNeeded(albumId)
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun refreshFolderCovers(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
// Get all folders in the album with their wallpapers
|
||||
val folders = folderDao.getFoldersWithWallpapersByAlbum(albumId).first()
|
||||
|
||||
// Update each folder's cover to its first wallpaper
|
||||
folders.forEach { folderWithWallpapers ->
|
||||
val folder = folderWithWallpapers.folder
|
||||
val wallpapers = folderWithWallpapers.wallpapers
|
||||
val newCoverUri = wallpapers.firstOrNull()?.uri
|
||||
|
||||
// Only update if cover changed
|
||||
if (folder.coverUri != newCoverUri) {
|
||||
folderDao.updateFolderCover(folder.id, newCoverUri)
|
||||
}
|
||||
}
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update album cover art based on available wallpapers
|
||||
* Priority: 1) First direct wallpaper, 2) First wallpaper from first folder
|
||||
* NOTE: This must be called within a transaction
|
||||
*/
|
||||
/** Call within a transaction; direct wallpapers take priority over folder images. */
|
||||
private suspend fun updateAlbumCoverIfNeeded(albumId: String) {
|
||||
val album = albumDao.getAlbumById(albumId) ?: return
|
||||
val newCoverUri = wallpaperDao.getAlbumCoverUri(albumId)
|
||||
|
||||
// Try to get first direct wallpaper (uploaded directly, not from folder)
|
||||
val directWallpapers = wallpaperDao.getDirectWallpapersByAlbumSync(albumId)
|
||||
val newCoverUri = when {
|
||||
// Priority 1: First direct wallpaper
|
||||
directWallpapers.isNotEmpty() -> directWallpapers.first().uri
|
||||
|
||||
// Priority 2: First wallpaper from any folder
|
||||
else -> {
|
||||
val allWallpapers = wallpaperDao.getWallpapersByAlbumSync(albumId)
|
||||
allWallpapers.firstOrNull()?.uri
|
||||
}
|
||||
}
|
||||
|
||||
// Only update if cover changed
|
||||
if (album.coverUri != newCoverUri) {
|
||||
albumDao.updateAlbumCover(albumId, newCoverUri, System.currentTimeMillis())
|
||||
}
|
||||
|
||||
@@ -1,83 +1,261 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.MutablePreferences
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.intPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import com.anthonyla.paperize.core.ScalingType
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperMode
|
||||
import com.anthonyla.paperize.data.datastore.PreferencesManager
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.domain.model.AppSettings
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.WallpaperEffects
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Implementation of SettingsRepository
|
||||
*/
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
name = Constants.PREFERENCES_NAME
|
||||
)
|
||||
|
||||
private val DARK_MODE = booleanPreferencesKey("dark_mode")
|
||||
private val DYNAMIC_THEMING = booleanPreferencesKey("dynamic_theming")
|
||||
private val ANIMATE = booleanPreferencesKey("animate")
|
||||
private val ENCRYPTED_PREVIEWS = booleanPreferencesKey("encrypted_previews")
|
||||
private val FIRST_LAUNCH = booleanPreferencesKey("first_launch")
|
||||
private val WALLPAPER_MODE = stringPreferencesKey("wallpaper_mode")
|
||||
private val ENABLE_CHANGER = booleanPreferencesKey("enable_changer")
|
||||
private val SEPARATE_SCHEDULES = booleanPreferencesKey("separate_schedules")
|
||||
private val SHUFFLE_ENABLED = booleanPreferencesKey("shuffle_enabled")
|
||||
private val HOME_ENABLED = booleanPreferencesKey("home_enabled")
|
||||
private val LOCK_ENABLED = booleanPreferencesKey("lock_enabled")
|
||||
private val HOME_ALBUM_ID = stringPreferencesKey("home_album_id")
|
||||
private val LOCK_ALBUM_ID = stringPreferencesKey("lock_album_id")
|
||||
private val LIVE_ALBUM_ID = stringPreferencesKey("live_album_id")
|
||||
private val HOME_INTERVAL_MINUTES = intPreferencesKey("home_interval_minutes")
|
||||
private val LOCK_INTERVAL_MINUTES = intPreferencesKey("lock_interval_minutes")
|
||||
private val LIVE_INTERVAL_MINUTES = intPreferencesKey("live_interval_minutes")
|
||||
private val HOME_SCALING_TYPE = stringPreferencesKey("home_scaling_type")
|
||||
private val LOCK_SCALING_TYPE = stringPreferencesKey("lock_scaling_type")
|
||||
private val LIVE_SCALING_TYPE = stringPreferencesKey("live_scaling_type")
|
||||
private val HOME_SCROLLING_ENABLED = booleanPreferencesKey("home_scrolling_enabled")
|
||||
private val BLUR_FIT_BACKGROUND = booleanPreferencesKey("blur_fit_background")
|
||||
private val ADAPTIVE_BRIGHTNESS = booleanPreferencesKey("adaptive_brightness")
|
||||
|
||||
/** Effect keys are "<screen>_<field>", e.g. "home_enable_blur" or "live_parallax_intensity". */
|
||||
private class EffectKeys(screen: String) {
|
||||
val enableBlur = booleanPreferencesKey("${screen}_enable_blur")
|
||||
val blur = intPreferencesKey("${screen}_blur")
|
||||
val enableDarken = booleanPreferencesKey("${screen}_enable_darken")
|
||||
val darken = intPreferencesKey("${screen}_darken")
|
||||
val enableVignette = booleanPreferencesKey("${screen}_enable_vignette")
|
||||
val vignette = intPreferencesKey("${screen}_vignette")
|
||||
val enableGrayscale = booleanPreferencesKey("${screen}_enable_grayscale")
|
||||
val grayscale = intPreferencesKey("${screen}_grayscale")
|
||||
val enableDoubleTap = booleanPreferencesKey("${screen}_enable_double_tap")
|
||||
val enableChangeOnScreenOff = booleanPreferencesKey("${screen}_enable_change_on_screen_off")
|
||||
val enableParallax = booleanPreferencesKey("${screen}_enable_parallax")
|
||||
val parallaxIntensity = intPreferencesKey("${screen}_parallax_intensity")
|
||||
}
|
||||
|
||||
private val HOME_EFFECTS = EffectKeys("home")
|
||||
private val LOCK_EFFECTS = EffectKeys("lock")
|
||||
private val LIVE_EFFECTS = EffectKeys("live")
|
||||
|
||||
@Singleton
|
||||
class SettingsRepositoryImpl @Inject constructor(
|
||||
private val preferencesManager: PreferencesManager
|
||||
@ApplicationContext context: Context
|
||||
) : SettingsRepository {
|
||||
private val dataStore = context.dataStore
|
||||
|
||||
override suspend fun getAppSettings(): AppSettings =
|
||||
preferencesManager.getAppSettings()
|
||||
override suspend fun getAppSettings(): AppSettings = getAppSettingsFlow().first()
|
||||
|
||||
override fun getAppSettingsFlow(): Flow<AppSettings> =
|
||||
preferencesManager.getAppSettingsFlow()
|
||||
override fun getAppSettingsFlow(): Flow<AppSettings> = dataStore.data.map { prefs ->
|
||||
val defaults = AppSettings()
|
||||
AppSettings(
|
||||
darkMode = prefs[DARK_MODE],
|
||||
dynamicTheming = prefs[DYNAMIC_THEMING] ?: defaults.dynamicTheming,
|
||||
animate = prefs[ANIMATE] ?: defaults.animate,
|
||||
firstLaunch = prefs[FIRST_LAUNCH] ?: defaults.firstLaunch,
|
||||
encryptedPreviews = prefs[ENCRYPTED_PREVIEWS] ?: defaults.encryptedPreviews
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun updateAppSettings(settings: AppSettings) =
|
||||
preferencesManager.updateAppSettings(settings)
|
||||
|
||||
override suspend fun getWallpaperMode(): WallpaperMode =
|
||||
preferencesManager.getWallpaperMode()
|
||||
override suspend fun getWallpaperMode(): WallpaperMode = getWallpaperModeFlow().first()
|
||||
|
||||
override fun getWallpaperModeFlow(): Flow<WallpaperMode> =
|
||||
preferencesManager.getWallpaperModeFlow()
|
||||
dataStore.data.map { WallpaperMode.fromString(it[WALLPAPER_MODE]) }
|
||||
|
||||
override suspend fun updateWallpaperMode(mode: WallpaperMode) =
|
||||
preferencesManager.updateWallpaperMode(mode)
|
||||
override suspend fun updateWallpaperMode(mode: WallpaperMode) {
|
||||
dataStore.edit { it[WALLPAPER_MODE] = mode.name }
|
||||
}
|
||||
|
||||
override suspend fun getScheduleSettings(): ScheduleSettings =
|
||||
preferencesManager.getScheduleSettings()
|
||||
override suspend fun getScheduleSettings(): ScheduleSettings = getScheduleSettingsFlow().first()
|
||||
|
||||
override fun getScheduleSettingsFlow(): Flow<ScheduleSettings> =
|
||||
preferencesManager.getScheduleSettingsFlow()
|
||||
override fun getScheduleSettingsFlow(): Flow<ScheduleSettings> = dataStore.data.map(::scheduleSettings)
|
||||
|
||||
override suspend fun updateScheduleSettings(settings: ScheduleSettings) =
|
||||
preferencesManager.updateScheduleSettings(settings)
|
||||
override suspend fun updateScheduleSettings(settings: ScheduleSettings) {
|
||||
updateScheduleSettings { settings }
|
||||
}
|
||||
|
||||
override suspend fun clearAllSettings() =
|
||||
preferencesManager.clear()
|
||||
override suspend fun updateScheduleSettings(transform: (ScheduleSettings) -> ScheduleSettings): ScheduleSettings {
|
||||
val updated = dataStore.edit { prefs ->
|
||||
val settings = transform(scheduleSettings(prefs))
|
||||
prefs[ENABLE_CHANGER] = settings.enableChanger
|
||||
prefs[SEPARATE_SCHEDULES] = settings.separateSchedules
|
||||
prefs[SHUFFLE_ENABLED] = settings.shuffleEnabled
|
||||
prefs[HOME_ENABLED] = settings.homeEnabled
|
||||
prefs[LOCK_ENABLED] = settings.lockEnabled
|
||||
prefs.setOrRemove(HOME_ALBUM_ID, settings.homeAlbumId)
|
||||
prefs.setOrRemove(LOCK_ALBUM_ID, settings.lockAlbumId)
|
||||
prefs.setOrRemove(LIVE_ALBUM_ID, settings.liveAlbumId)
|
||||
prefs[HOME_INTERVAL_MINUTES] = settings.homeIntervalMinutes
|
||||
prefs[LOCK_INTERVAL_MINUTES] = settings.lockIntervalMinutes
|
||||
prefs[LIVE_INTERVAL_MINUTES] = settings.liveIntervalMinutes
|
||||
prefs[HOME_SCALING_TYPE] = settings.homeScalingType.name
|
||||
prefs[LOCK_SCALING_TYPE] = settings.lockScalingType.name
|
||||
prefs[LIVE_SCALING_TYPE] = settings.liveScalingType.name
|
||||
prefs[HOME_SCROLLING_ENABLED] = settings.homeScrollingEnabled
|
||||
prefs[BLUR_FIT_BACKGROUND] = settings.blurFitBackground
|
||||
prefs.writeEffects(HOME_EFFECTS, settings.homeEffects)
|
||||
prefs.writeEffects(LOCK_EFFECTS, settings.lockEffects)
|
||||
prefs.writeEffects(LIVE_EFFECTS, settings.liveEffects)
|
||||
prefs[ADAPTIVE_BRIGHTNESS] = settings.adaptiveBrightness
|
||||
}
|
||||
return scheduleSettings(updated)
|
||||
}
|
||||
|
||||
override suspend fun clearScheduleSettings() =
|
||||
preferencesManager.clearScheduleSettings()
|
||||
override suspend fun clearAllSettings() {
|
||||
dataStore.edit { it.clear() }
|
||||
}
|
||||
|
||||
override suspend fun updateHomeAlbumId(albumId: String?) =
|
||||
preferencesManager.updateHomeAlbumId(albumId)
|
||||
override suspend fun clearScheduleSettings() = updateScheduleSettings(ScheduleSettings())
|
||||
|
||||
override suspend fun updateLockAlbumId(albumId: String?) =
|
||||
preferencesManager.updateLockAlbumId(albumId)
|
||||
override suspend fun updateAlbumId(screen: ScreenType, albumId: String?) {
|
||||
dataStore.edit { prefs -> albumIdKeys(screen).forEach { prefs.setOrRemove(it, albumId) } }
|
||||
}
|
||||
|
||||
override suspend fun updateLiveAlbumId(albumId: String?) =
|
||||
preferencesManager.updateLiveAlbumId(albumId)
|
||||
override suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean {
|
||||
var wasCleared = false
|
||||
dataStore.edit { prefs ->
|
||||
val targets = listOf(HOME_ALBUM_ID, LOCK_ALBUM_ID, LIVE_ALBUM_ID).filter { prefs[it] == albumId }
|
||||
targets.forEach { prefs.remove(it) }
|
||||
wasCleared = targets.isNotEmpty()
|
||||
}
|
||||
return wasCleared
|
||||
}
|
||||
|
||||
override suspend fun clearAlbumSelectionsIfMatches(albumId: String): Boolean =
|
||||
preferencesManager.clearAlbumSelectionsIfMatches(albumId)
|
||||
override suspend fun clearEmptyAlbumSelection(albumId: String, screen: ScreenType) {
|
||||
dataStore.edit { prefs ->
|
||||
val targets = albumIdKeys(screen).filter { prefs[it] == albumId }
|
||||
if (targets.isEmpty()) return@edit
|
||||
targets.forEach { prefs.remove(it) }
|
||||
val mode = WallpaperMode.fromString(prefs[WALLPAPER_MODE])
|
||||
if (scheduleSettings(prefs).activeScreens(mode).isEmpty()) prefs[ENABLE_CHANGER] = false
|
||||
}
|
||||
}
|
||||
|
||||
// ============ Atomic AppSettings Operations ============
|
||||
override suspend fun updateDarkMode(enabled: Boolean) {
|
||||
dataStore.edit { it[DARK_MODE] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateDarkMode(enabled: Boolean) =
|
||||
preferencesManager.updateDarkMode(enabled)
|
||||
override suspend fun updateDynamicTheming(enabled: Boolean) {
|
||||
dataStore.edit { it[DYNAMIC_THEMING] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateDynamicTheming(enabled: Boolean) =
|
||||
preferencesManager.updateDynamicTheming(enabled)
|
||||
override suspend fun updateAnimate(enabled: Boolean) {
|
||||
dataStore.edit { it[ANIMATE] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateAnimate(enabled: Boolean) =
|
||||
preferencesManager.updateAnimate(enabled)
|
||||
override suspend fun updateEncryptedPreviews(enabled: Boolean) {
|
||||
dataStore.edit { it[ENCRYPTED_PREVIEWS] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateFirstLaunch(isFirstLaunch: Boolean) =
|
||||
preferencesManager.updateFirstLaunch(isFirstLaunch)
|
||||
override suspend fun completeFirstLaunch() {
|
||||
dataStore.edit { it[FIRST_LAUNCH] = false }
|
||||
}
|
||||
|
||||
// ============ Atomic ScheduleSettings Operations ============
|
||||
override suspend fun updateEnableChanger(enabled: Boolean) {
|
||||
dataStore.edit { it[ENABLE_CHANGER] = enabled }
|
||||
}
|
||||
|
||||
override suspend fun updateEnableChanger(enabled: Boolean) =
|
||||
preferencesManager.updateEnableChanger(enabled)
|
||||
private fun scheduleSettings(prefs: Preferences): ScheduleSettings {
|
||||
val defaults = ScheduleSettings()
|
||||
return ScheduleSettings(
|
||||
enableChanger = prefs[ENABLE_CHANGER] ?: defaults.enableChanger,
|
||||
separateSchedules = prefs[SEPARATE_SCHEDULES] ?: defaults.separateSchedules,
|
||||
shuffleEnabled = prefs[SHUFFLE_ENABLED] ?: defaults.shuffleEnabled,
|
||||
homeEnabled = prefs[HOME_ENABLED] ?: defaults.homeEnabled,
|
||||
lockEnabled = prefs[LOCK_ENABLED] ?: defaults.lockEnabled,
|
||||
homeAlbumId = prefs[HOME_ALBUM_ID],
|
||||
lockAlbumId = prefs[LOCK_ALBUM_ID],
|
||||
liveAlbumId = prefs[LIVE_ALBUM_ID],
|
||||
homeIntervalMinutes = prefs[HOME_INTERVAL_MINUTES] ?: defaults.homeIntervalMinutes,
|
||||
lockIntervalMinutes = prefs[LOCK_INTERVAL_MINUTES] ?: defaults.lockIntervalMinutes,
|
||||
liveIntervalMinutes = prefs[LIVE_INTERVAL_MINUTES] ?: defaults.liveIntervalMinutes,
|
||||
homeScalingType = ScalingType.fromString(prefs[HOME_SCALING_TYPE]),
|
||||
lockScalingType = ScalingType.fromString(prefs[LOCK_SCALING_TYPE]),
|
||||
liveScalingType = ScalingType.fromString(prefs[LIVE_SCALING_TYPE]),
|
||||
homeScrollingEnabled = prefs[HOME_SCROLLING_ENABLED] ?: defaults.homeScrollingEnabled,
|
||||
blurFitBackground = prefs[BLUR_FIT_BACKGROUND] ?: defaults.blurFitBackground,
|
||||
homeEffects = prefs.readEffects(HOME_EFFECTS),
|
||||
lockEffects = prefs.readEffects(LOCK_EFFECTS),
|
||||
liveEffects = prefs.readEffects(LIVE_EFFECTS),
|
||||
adaptiveBrightness = prefs[ADAPTIVE_BRIGHTNESS] ?: defaults.adaptiveBrightness
|
||||
)
|
||||
}
|
||||
|
||||
private fun Preferences.readEffects(keys: EffectKeys): WallpaperEffects {
|
||||
val defaults = WallpaperEffects()
|
||||
return WallpaperEffects(
|
||||
enableBlur = this[keys.enableBlur] ?: defaults.enableBlur,
|
||||
blurPercentage = this[keys.blur] ?: defaults.blurPercentage,
|
||||
enableDarken = this[keys.enableDarken] ?: defaults.enableDarken,
|
||||
darkenPercentage = this[keys.darken] ?: defaults.darkenPercentage,
|
||||
enableVignette = this[keys.enableVignette] ?: defaults.enableVignette,
|
||||
vignettePercentage = this[keys.vignette] ?: defaults.vignettePercentage,
|
||||
enableGrayscale = this[keys.enableGrayscale] ?: defaults.enableGrayscale,
|
||||
grayscalePercentage = this[keys.grayscale] ?: defaults.grayscalePercentage,
|
||||
enableDoubleTap = this[keys.enableDoubleTap] ?: defaults.enableDoubleTap,
|
||||
enableChangeOnScreenOff = this[keys.enableChangeOnScreenOff] ?: defaults.enableChangeOnScreenOff,
|
||||
enableParallax = this[keys.enableParallax] ?: defaults.enableParallax,
|
||||
parallaxIntensity = this[keys.parallaxIntensity] ?: defaults.parallaxIntensity
|
||||
)
|
||||
}
|
||||
|
||||
private fun MutablePreferences.writeEffects(keys: EffectKeys, effects: WallpaperEffects) {
|
||||
this[keys.enableBlur] = effects.enableBlur
|
||||
this[keys.blur] = effects.blurPercentage
|
||||
this[keys.enableDarken] = effects.enableDarken
|
||||
this[keys.darken] = effects.darkenPercentage
|
||||
this[keys.enableVignette] = effects.enableVignette
|
||||
this[keys.vignette] = effects.vignettePercentage
|
||||
this[keys.enableGrayscale] = effects.enableGrayscale
|
||||
this[keys.grayscale] = effects.grayscalePercentage
|
||||
this[keys.enableDoubleTap] = effects.enableDoubleTap
|
||||
this[keys.enableChangeOnScreenOff] = effects.enableChangeOnScreenOff
|
||||
this[keys.enableParallax] = effects.enableParallax
|
||||
this[keys.parallaxIntensity] = effects.parallaxIntensity
|
||||
}
|
||||
|
||||
private fun MutablePreferences.setOrRemove(key: Preferences.Key<String>, value: String?) {
|
||||
if (value != null) this[key] = value else remove(key)
|
||||
}
|
||||
|
||||
private fun albumIdKeys(screen: ScreenType) = when (screen) {
|
||||
ScreenType.HOME -> listOf(HOME_ALBUM_ID)
|
||||
ScreenType.LOCK -> listOf(LOCK_ALBUM_ID)
|
||||
ScreenType.BOTH -> listOf(HOME_ALBUM_ID, LOCK_ALBUM_ID)
|
||||
ScreenType.LIVE -> listOf(LIVE_ALBUM_ID)
|
||||
}
|
||||
}
|
||||
@@ -1,256 +1,122 @@
|
||||
package com.anthonyla.paperize.data.repository
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.core.Result
|
||||
import androidx.room.withTransaction
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.WallpaperSourceType
|
||||
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.core.util.QueueBuilder
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
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
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.data.source.EncryptedImageStore
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import com.anthonyla.paperize.domain.source.albumFilterRegex
|
||||
import com.anthonyla.paperize.domain.source.matchingNamingTableFiles
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
/**
|
||||
* Implementation of WallpaperRepository
|
||||
*/
|
||||
@Singleton
|
||||
class WallpaperRepositoryImpl @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val wallpaperDao: WallpaperDao,
|
||||
private val wallpaperQueueDao: WallpaperQueueDao,
|
||||
private val wallpaperCurrentDao: WallpaperCurrentDao
|
||||
private val database: PaperizeDatabase,
|
||||
private val documents: DocumentSource,
|
||||
private val encryptedImages: EncryptedImageStore
|
||||
) : WallpaperRepository {
|
||||
|
||||
private val contentResolver: ContentResolver = context.contentResolver
|
||||
|
||||
/**
|
||||
* Mutexes to synchronize queue rebuild operations per (albumId, screenType)
|
||||
* Prevents duplicate rebuilds when multiple threads detect empty queue simultaneously
|
||||
*/
|
||||
private val queueRebuildMutexes = ConcurrentHashMap<String, Mutex>()
|
||||
|
||||
override fun getWallpapersByAlbum(albumId: String): Flow<List<Wallpaper>> =
|
||||
wallpaperDao.getWallpapersByAlbum(albumId).map { it.toDomainModels() }
|
||||
|
||||
override fun getDirectWallpapersByAlbum(albumId: String): Flow<List<Wallpaper>> =
|
||||
wallpaperDao.getDirectWallpapersByAlbum(albumId).map { it.toDomainModels() }
|
||||
|
||||
override fun getWallpapersByFolder(folderId: String): Flow<List<Wallpaper>> =
|
||||
wallpaperDao.getWallpapersByFolder(folderId).map { it.toDomainModels() }
|
||||
private val wallpaperDao = database.wallpaperDao()
|
||||
private val wallpaperQueueDao = database.wallpaperQueueDao()
|
||||
private val wallpaperCurrentDao = database.wallpaperCurrentDao()
|
||||
|
||||
override suspend fun getWallpaperById(wallpaperId: String): Wallpaper? =
|
||||
wallpaperDao.getWallpaperById(wallpaperId)?.toDomainModel()
|
||||
|
||||
override suspend fun addWallpaper(wallpaper: Wallpaper): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.insertWallpaper(wallpaper.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateWallpaper(wallpaper: Wallpaper): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.updateWallpaper(wallpaper.toEntity())
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpaper(wallpaperId: String): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.deleteWallpaperById(wallpaperId)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpapers(wallpaperIds: List<String>): Result<Unit> {
|
||||
return try {
|
||||
if (wallpaperIds.isEmpty()) {
|
||||
return Result.Success(Unit)
|
||||
}
|
||||
wallpaperDao.deleteWallpapersByIds(wallpaperIds)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun deleteWallpapersByFolderId(folderId: String): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.deleteWallpapersByFolder(folderId)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun updateWallpaperOrder(wallpaperId: String, order: Int): Result<Unit> {
|
||||
return try {
|
||||
wallpaperDao.updateWallpaperOrder(wallpaperId, order)
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun validateAndRemoveInvalidWallpapers(albumId: String): Result<Int> {
|
||||
return try {
|
||||
var totalRemoved = 0
|
||||
val batchSize = 100 // Process in smaller batches to avoid memory spikes
|
||||
var offset = 0
|
||||
|
||||
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.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
|
||||
}
|
||||
}
|
||||
|
||||
Result.Success(totalRemoved)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getNextWallpaperInQueue(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun getAndDequeueWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperQueueDao.getAndDequeueWallpaper(albumId, screenType)?.toDomainModel()
|
||||
|
||||
override suspend fun buildWallpaperQueue(
|
||||
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 ensureWallpaperQueue(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
shuffle: Boolean
|
||||
): Result<Unit> {
|
||||
// In shuffle mode, use album-level mutex to ensure synchronized shuffle order
|
||||
// In sequential mode, use per-screen mutex for independent rebuilds
|
||||
val mutexKey = if (shuffle) albumId else "$albumId:$screenType"
|
||||
val mutex = queueRebuildMutexes.getOrPut(mutexKey) { Mutex() }
|
||||
|
||||
return mutex.withLock {
|
||||
try {
|
||||
// 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 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 {
|
||||
val otherQueueIsEmpty = wallpaperQueueDao
|
||||
.getQueueItems(albumId, otherScreenType).isEmpty()
|
||||
if (otherQueueIsEmpty) {
|
||||
wallpaperQueueDao.rebuildQueue(albumId, otherScreenType, wallpaperIds)
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// Best-effort: if pre-population fails the other screen will build its
|
||||
// own queue on demand via mergeWithExistingQueue
|
||||
}
|
||||
}
|
||||
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
) {
|
||||
if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return
|
||||
val allowed = allowedWallpaperIds(albumId)
|
||||
database.withTransaction {
|
||||
// Recheck inside the transaction: another caller may already have filled it.
|
||||
if (wallpaperQueueDao.getNextWallpaperInQueue(albumId, screenType) != null) return@withTransaction
|
||||
val otherScreen = if (shuffle) when (screenType) {
|
||||
ScreenType.HOME -> ScreenType.LOCK
|
||||
ScreenType.LOCK -> ScreenType.HOME
|
||||
else -> null
|
||||
} else null
|
||||
val otherQueue = otherScreen?.let { wallpaperQueueDao.getQueueItems(albumId, it) }.orEmpty()
|
||||
val ids = if (shuffle) {
|
||||
val available = wallpaperDao.getWallpaperIdsByAlbum(albumId).allowed(allowed)
|
||||
if (otherQueue.isEmpty()) available.shuffled()
|
||||
else QueueBuilder.mergeWithExistingQueue(otherQueue.map { it.wallpaperId }, available)
|
||||
} else {
|
||||
wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId).allowed(allowed)
|
||||
}
|
||||
wallpaperQueueDao.rebuildQueue(albumId, screenType, ids)
|
||||
if (otherScreen != null && otherQueue.isEmpty()) {
|
||||
wallpaperQueueDao.rebuildQueue(albumId, otherScreen, ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clearAllQueues(): Result<Unit> {
|
||||
return try {
|
||||
wallpaperQueueDao.deleteAllQueueItems()
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
override suspend fun startSequenceAfter(
|
||||
albumId: String,
|
||||
screenType: ScreenType,
|
||||
wallpaperId: String
|
||||
) {
|
||||
val allowed = allowedWallpaperIds(albumId)
|
||||
database.withTransaction {
|
||||
val ordered = wallpaperDao.getOrderedWallpaperIdsByAlbum(albumId)
|
||||
wallpaperQueueDao.rebuildQueue(
|
||||
albumId, screenType, QueueBuilder.idsAfter(ordered, wallpaperId).allowed(allowed)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun clearQueuesForAlbum(albumId: String): Result<Unit> {
|
||||
return try {
|
||||
wallpaperQueueDao.clearAllQueues(albumId)
|
||||
|
||||
// Prune mutexes for this album to prevent memory leak
|
||||
// Keys are either albumId (shuffled) or $albumId:$screenType (sequential)
|
||||
// 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)
|
||||
}
|
||||
|
||||
Result.Success(Unit)
|
||||
} catch (e: Exception) {
|
||||
Result.Error(e)
|
||||
private fun List<String>.allowed(allowed: Set<String>?) = if (allowed == null) this else filter { it in allowed }
|
||||
|
||||
/** Ids passing the album filter, or null without one. Images outside a folder with a naming table never pass. */
|
||||
private suspend fun allowedWallpaperIds(albumId: String): Set<String>? {
|
||||
val filter = database.albumDao().getAlbumById(albumId)?.filter?.let(::albumFilterRegex) ?: return null
|
||||
val allowed = HashSet<String>()
|
||||
database.folderDao().getFoldersByAlbum(albumId).forEach { folder ->
|
||||
val table = documents.readNamingTable(folder.uri) ?: return@forEach
|
||||
val files = matchingNamingTableFiles(encryptedImages.decrypt(table).decodeToString(), filter)
|
||||
wallpaperDao.getFolderWallpapers(folder.id)
|
||||
.filter { it.fileName.substringAfterLast('/') in files }
|
||||
.mapTo(allowed) { it.id }
|
||||
}
|
||||
return allowed
|
||||
}
|
||||
|
||||
override suspend fun clearAllQueues() {
|
||||
wallpaperQueueDao.deleteAllQueueItems()
|
||||
}
|
||||
|
||||
override suspend fun getCurrentWallpaper(albumId: String, screenType: ScreenType): Wallpaper? =
|
||||
wallpaperCurrentDao.getCurrentWallpaper(albumId, screenType)?.toDomainModel()
|
||||
getCurrentWallpaperFlow(albumId, screenType).first()
|
||||
|
||||
override fun getCurrentWallpaperFlow(albumId: String, screenType: ScreenType): Flow<Wallpaper?> =
|
||||
wallpaperCurrentDao.getCurrentWallpaperFlow(albumId, screenType).map { it?.toDomainModel() }
|
||||
@@ -261,28 +127,4 @@ class WallpaperRepositoryImpl @Inject constructor(
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun scanFolderForWallpapers(folderUri: Uri): Result<List<Wallpaper>> {
|
||||
return try {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.CancellationSignal
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.core.net.toUri
|
||||
import androidx.documentfile.provider.DocumentFile
|
||||
import com.anthonyla.paperize.core.runCatchingCancellable
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import com.anthonyla.paperize.domain.source.NAMING_TABLE_FILE
|
||||
import com.anthonyla.paperize.domain.source.SourceFolder
|
||||
import com.anthonyla.paperize.domain.source.SourceImage
|
||||
import com.anthonyla.paperize.domain.source.isSupportedSourceName
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.IOException
|
||||
import javax.inject.Inject
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
class AndroidDocumentSource @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context
|
||||
) : DocumentSource {
|
||||
override suspend fun retainReadPermission(uri: String): Unit = withContext(Dispatchers.IO) {
|
||||
context.contentResolver.takePersistableUriPermission(uri.toUri(), Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
|
||||
override suspend fun readImage(uri: String): SourceImage = withContext(Dispatchers.IO) {
|
||||
val document = DocumentFile.fromSingleUri(context, uri.toUri())
|
||||
SourceImage(uri, document?.name ?: uri.substringAfterLast('/'), document?.lastModified() ?: 0L)
|
||||
}
|
||||
|
||||
override suspend fun readFolder(uri: String, isEncrypted: Boolean, onProgress: (Int) -> Unit): SourceFolder = withContext(Dispatchers.IO) {
|
||||
val tree = uri.toUri()
|
||||
SourceFolder(
|
||||
DocumentFile.fromTreeUri(context, tree)?.name ?: uri.substringAfterLast('/'),
|
||||
tree.scanFolderImages(context, isEncrypted, onProgress)
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun readNamingTable(folderUri: String): ByteArray? = withContext(Dispatchers.IO) {
|
||||
val tree = folderUri.toUri()
|
||||
val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, DocumentsContract.getTreeDocumentId(tree))
|
||||
val projection = arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
||||
val documentId = context.contentResolver.query(children, projection, null, null, null)?.use { cursor ->
|
||||
cursor.requireComplete()
|
||||
generateSequence { if (cursor.moveToNext()) cursor else null }
|
||||
.firstOrNull { it.getString(1) == NAMING_TABLE_FILE }?.getString(0)
|
||||
} ?: return@withContext null
|
||||
val table = DocumentsContract.buildDocumentUriUsingTree(tree, documentId)
|
||||
context.contentResolver.openInputStream(table)?.use { it.readBytes() }
|
||||
}
|
||||
|
||||
override suspend fun isMissing(uri: String, isTree: Boolean): Boolean = withContext(Dispatchers.IO) {
|
||||
val source = uri.toUri()
|
||||
val document = if (isTree) {
|
||||
DocumentsContract.buildDocumentUriUsingTree(source, DocumentsContract.getTreeDocumentId(source))
|
||||
} else source
|
||||
document.isDocumentMissing(context.contentResolver)
|
||||
}
|
||||
}
|
||||
|
||||
/** Only a successful, complete query with no rows proves that a document was removed. */
|
||||
internal fun Uri.isDocumentMissing(contentResolver: ContentResolver): Boolean {
|
||||
if (scheme != ContentResolver.SCHEME_CONTENT) return false
|
||||
// Offline providers, revoked permissions and query failures do not prove deletion.
|
||||
return runCatchingCancellable {
|
||||
contentResolver.query(this, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
|
||||
?.use { cursor ->
|
||||
cursor.requireComplete()
|
||||
!cursor.moveToFirst()
|
||||
} ?: false
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
private fun Cursor.requireComplete() {
|
||||
val metadata = extras
|
||||
if (metadata.getBoolean(DocumentsContract.EXTRA_LOADING, false) ||
|
||||
metadata.getString(DocumentsContract.EXTRA_ERROR) != null) {
|
||||
throw IOException("Document provider has not returned a complete result")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Traverses directories iteratively, querying metadata once per directory.
|
||||
* Rejects incomplete provider results and cancels in-flight queries with the caller.
|
||||
* [onProgress] reports every [PROGRESS_REPORT_INTERVAL] discoveries and on completion.
|
||||
*/
|
||||
internal suspend fun Uri.scanFolderImages(context: Context, isEncrypted: Boolean, onProgress: (found: Int) -> Unit = {}): List<SourceImage> {
|
||||
val rootDocumentId = DocumentsContract.getTreeDocumentId(this)
|
||||
|
||||
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<SourceImage>()
|
||||
var lastReported = 0
|
||||
val pendingDirs = ArrayDeque<String>()
|
||||
val visitedDocuments = mutableSetOf(rootDocumentId)
|
||||
pendingDirs.addLast(rootDocumentId)
|
||||
|
||||
while (pendingDirs.isNotEmpty()) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val parentDocumentId = pendingDirs.removeLast()
|
||||
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(this, parentDocumentId)
|
||||
val cursor = suspendCancellableCoroutine<Cursor> { continuation ->
|
||||
val signal = CancellationSignal()
|
||||
continuation.invokeOnCancellation { signal.cancel() }
|
||||
try {
|
||||
val result = context.contentResolver.query(childrenUri, projection, null, null, null, signal)
|
||||
?: throw IOException("Document provider could not read the folder")
|
||||
continuation.resume(result) { _, value, _ -> value.close() }
|
||||
} catch (e: Exception) {
|
||||
continuation.resumeWithException(e)
|
||||
}
|
||||
}
|
||||
cursor.use {
|
||||
cursor.requireComplete()
|
||||
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()) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val documentId = cursor.getString(idColumn) ?: continue
|
||||
if (!visitedDocuments.add(documentId)) continue
|
||||
val name = cursor.getString(nameColumn) ?: continue
|
||||
// Galleries rename deleted files in place: .trashed-…, .Trash-…
|
||||
// HyperOS keeps reporting the old display name, so the id is checked too.
|
||||
val fileName = documentId.substringAfterLast('/').substringAfterLast(':')
|
||||
if (listOf(name, fileName).any { it.startsWith(".trash", ignoreCase = true) }) continue
|
||||
if (cursor.getString(mimeColumn) == DocumentsContract.Document.MIME_TYPE_DIR) {
|
||||
pendingDirs.addLast(documentId)
|
||||
} else {
|
||||
if (isSupportedSourceName(name, isEncrypted)) {
|
||||
results.add(
|
||||
SourceImage(
|
||||
uri = DocumentsContract.buildDocumentUriUsingTree(this, documentId).toString(),
|
||||
name = name,
|
||||
modifiedAt = if (cursor.isNull(modifiedColumn)) 0L else cursor.getLong(modifiedColumn)
|
||||
)
|
||||
)
|
||||
if (results.size - lastReported >= PROGRESS_REPORT_INTERVAL) {
|
||||
lastReported = results.size
|
||||
onProgress(results.size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
onProgress(results.size)
|
||||
return results
|
||||
}
|
||||
|
||||
private const val PROGRESS_REPORT_INTERVAL = 512
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.ImageDecoder
|
||||
import android.util.Log
|
||||
import androidx.core.net.toUri
|
||||
import com.anthonyla.paperize.core.ScreenType
|
||||
import com.anthonyla.paperize.core.util.adaptiveBrightnessAdjustment
|
||||
import com.anthonyla.paperize.core.util.getDeviceScreenSize
|
||||
import com.anthonyla.paperize.core.util.processBitmap
|
||||
import com.anthonyla.paperize.core.util.retrieveBitmap
|
||||
import com.anthonyla.paperize.core.util.usesLauncherManagedScrolling
|
||||
import com.anthonyla.paperize.domain.model.ScheduleSettings
|
||||
import com.anthonyla.paperize.domain.model.Wallpaper
|
||||
import com.anthonyla.paperize.domain.source.WallpaperRenderer
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import javax.inject.Inject
|
||||
import java.nio.ByteBuffer
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
class AndroidWallpaperRenderer @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context,
|
||||
private val encryptedImages: EncryptedImageStore
|
||||
) : WallpaperRenderer {
|
||||
override suspend fun render(wallpaper: Wallpaper, screen: ScreenType, settings: ScheduleSettings): Bitmap? {
|
||||
currentCoroutineContext().ensureActive()
|
||||
val effects = when (screen) {
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeEffects
|
||||
ScreenType.LOCK -> settings.lockEffects
|
||||
ScreenType.LIVE -> settings.liveEffects
|
||||
}
|
||||
val scaling = when (screen) {
|
||||
ScreenType.HOME, ScreenType.BOTH -> settings.homeScalingType
|
||||
ScreenType.LOCK -> settings.lockScalingType
|
||||
ScreenType.LIVE -> settings.liveScalingType
|
||||
}
|
||||
val size = getDeviceScreenSize(context)
|
||||
val decrypted = if (wallpaper.fileName.endsWith(".jpg_enc", ignoreCase = true)) {
|
||||
try {
|
||||
encryptedImages.decrypt(wallpaper.uri.toUri())
|
||||
} catch (e: Exception) {
|
||||
Log.e("AndroidWallpaperRenderer", "Could not decrypt wallpaper", e)
|
||||
throw e
|
||||
}
|
||||
} else null
|
||||
var bitmap = try {
|
||||
retrieveBitmap(context, wallpaper.uri.toUri(), size.width, size.height, scaling,
|
||||
usesLauncherManagedScrolling(screen, scaling, settings.homeScrollingEnabled),
|
||||
settings.blurFitBackground,
|
||||
decrypted?.let { ImageDecoder.createSource(ByteBuffer.wrap(it)) })
|
||||
} finally {
|
||||
decrypted?.fill(0)
|
||||
} ?: return null
|
||||
try {
|
||||
val 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()
|
||||
bitmap = processed
|
||||
if (settings.adaptiveBrightness) {
|
||||
val adjusted = adaptiveBrightnessAdjustment(context, bitmap)
|
||||
if (adjusted !== bitmap) bitmap.recycle()
|
||||
bitmap = adjusted
|
||||
}
|
||||
currentCoroutineContext().ensureActive()
|
||||
return bitmap
|
||||
} catch (e: Exception) {
|
||||
bitmap.recycle()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package com.anthonyla.paperize.data.source
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.AtomicFile
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.BadPaddingException
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.SecretKeyFactory
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
import javax.crypto.spec.IvParameterSpec
|
||||
import javax.crypto.spec.PBEKeySpec
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
class MissingPassphraseException : IllegalStateException("No encryption passphrase is configured")
|
||||
class PassphraseStorageException(cause: Throwable) : IllegalStateException("Cannot access the stored passphrase", cause)
|
||||
class InvalidEncryptedFileException : IOException("Invalid or truncated encrypted file")
|
||||
class IncorrectPassphraseException : IOException("Incorrect passphrase or damaged encrypted file")
|
||||
|
||||
@Singleton
|
||||
class EncryptedImageStore @Inject constructor(
|
||||
@param:ApplicationContext private val context: Context
|
||||
) {
|
||||
private val passphraseFile = AtomicFile(File(context.noBackupFilesDir, "encrypted_image_passphrase"))
|
||||
private val mutableRevision = MutableStateFlow(0)
|
||||
val revision: StateFlow<Int> = mutableRevision.asStateFlow()
|
||||
|
||||
@Synchronized
|
||||
fun setPassphrase(passphrase: String) {
|
||||
try {
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key(create = true))
|
||||
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
|
||||
val encrypted = try {
|
||||
cipher.doFinal(plaintext)
|
||||
} finally {
|
||||
plaintext.fill(0)
|
||||
}
|
||||
val output = passphraseFile.startWrite()
|
||||
try {
|
||||
output.write(cipher.iv)
|
||||
output.write(encrypted)
|
||||
passphraseFile.finishWrite(output)
|
||||
mutableRevision.value += 1
|
||||
} catch (e: Exception) {
|
||||
passphraseFile.failWrite(output)
|
||||
throw e
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
throw PassphraseStorageException(e)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun clearPassphrase() {
|
||||
passphraseFile.delete()
|
||||
check(!passphraseFile.baseFile.exists()) { "Cannot clear the stored passphrase" }
|
||||
mutableRevision.value += 1
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun hasPassphrase(): Boolean = passphraseFile.baseFile.exists()
|
||||
|
||||
fun decrypt(uri: Uri): ByteArray {
|
||||
val passphrase = synchronized(this) { readPassphrase() }
|
||||
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
?: throw IOException("Cannot open encrypted file")
|
||||
return decryptEncryptedImage(bytes, passphrase)
|
||||
}
|
||||
|
||||
fun decrypt(bytes: ByteArray): ByteArray = decryptEncryptedImage(bytes, synchronized(this) { readPassphrase() })
|
||||
|
||||
private fun readPassphrase(): String {
|
||||
if (!hasPassphrase()) throw MissingPassphraseException()
|
||||
try {
|
||||
val stored = passphraseFile.readFully()
|
||||
require(stored.size >= IV_SIZE + TAG_SIZE)
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||
cipher.init(Cipher.DECRYPT_MODE, key(create = false), GCMParameterSpec(128, stored, 0, IV_SIZE))
|
||||
val plaintext = cipher.doFinal(stored, IV_SIZE, stored.size - IV_SIZE)
|
||||
return try {
|
||||
plaintext.toString(Charsets.UTF_8)
|
||||
} finally {
|
||||
plaintext.fill(0)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
throw PassphraseStorageException(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun key(create: Boolean): SecretKey {
|
||||
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
val existing = keyStore.getKey(KEY_ALIAS, null) as? SecretKey
|
||||
if (existing != null) return existing
|
||||
check(create) { "Keystore key is missing" }
|
||||
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").run {
|
||||
init(
|
||||
KeyGenParameterSpec.Builder(
|
||||
KEY_ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.build()
|
||||
)
|
||||
generateKey()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val KEY_ALIAS = "paperize_encrypted_image_passphrase"
|
||||
const val IV_SIZE = 12
|
||||
const val TAG_SIZE = 16
|
||||
}
|
||||
}
|
||||
|
||||
internal fun decryptEncryptedImage(encrypted: ByteArray, passphrase: String): ByteArray {
|
||||
val headerSize = 16
|
||||
if (encrypted.size < headerSize + 16 ||
|
||||
(encrypted.size - headerSize) % 16 != 0 ||
|
||||
!encrypted.copyOfRange(0, 8).contentEquals("Salted__".toByteArray(Charsets.US_ASCII))
|
||||
) throw InvalidEncryptedFileException()
|
||||
|
||||
val spec = PBEKeySpec(passphrase.toCharArray(), encrypted.copyOfRange(8, headerSize), 10_000, 384)
|
||||
val material = try {
|
||||
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
|
||||
} finally {
|
||||
spec.clearPassword()
|
||||
}
|
||||
try {
|
||||
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
|
||||
cipher.init(
|
||||
Cipher.DECRYPT_MODE,
|
||||
SecretKeySpec(material, 0, 32, "AES"),
|
||||
IvParameterSpec(material, 32, 16)
|
||||
)
|
||||
return try {
|
||||
cipher.doFinal(encrypted, headerSize, encrypted.size - headerSize)
|
||||
} catch (_: BadPaddingException) {
|
||||
throw IncorrectPassphraseException()
|
||||
}
|
||||
} finally {
|
||||
material.fill(0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.anthonyla.paperize.di
|
||||
|
||||
import android.app.Application
|
||||
import android.app.WallpaperManager
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import com.anthonyla.paperize.core.constants.Constants
|
||||
import com.anthonyla.paperize.data.database.LIBRARY_MIGRATIONS
|
||||
import com.anthonyla.paperize.data.database.PaperizeDatabase
|
||||
import com.anthonyla.paperize.data.repository.AlbumRepositoryImpl
|
||||
import com.anthonyla.paperize.data.repository.SettingsRepositoryImpl
|
||||
import com.anthonyla.paperize.data.repository.WallpaperRepositoryImpl
|
||||
import com.anthonyla.paperize.data.source.AndroidDocumentSource
|
||||
import com.anthonyla.paperize.data.source.AndroidWallpaperRenderer
|
||||
import com.anthonyla.paperize.domain.repository.AlbumRepository
|
||||
import com.anthonyla.paperize.domain.repository.SettingsRepository
|
||||
import com.anthonyla.paperize.domain.repository.WallpaperRepository
|
||||
import com.anthonyla.paperize.domain.source.DocumentSource
|
||||
import com.anthonyla.paperize.domain.source.WallpaperRenderer
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import dagger.hilt.components.SingletonComponent
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
@InstallIn(SingletonComponent::class)
|
||||
object AppModule {
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
fun providePaperizeDatabase(app: Application): PaperizeDatabase =
|
||||
Room.databaseBuilder(app, PaperizeDatabase::class.java, Constants.DATABASE_NAME)
|
||||
.addMigrations(*LIBRARY_MIGRATIONS)
|
||||
.build()
|
||||
|
||||
@Provides
|
||||
fun provideWallpaperManager(@ApplicationContext context: Context): WallpaperManager =
|
||||
WallpaperManager.getInstance(context)
|
||||
|
||||
@Provides
|
||||
fun provideDocumentSource(source: AndroidDocumentSource): DocumentSource = source
|
||||
|
||||
@Provides
|
||||
fun provideWallpaperRenderer(renderer: AndroidWallpaperRenderer): WallpaperRenderer = renderer
|
||||
|
||||
@Provides
|
||||
fun provideAlbumRepository(repository: AlbumRepositoryImpl): AlbumRepository = repository
|
||||
|
||||
@Provides
|
||||
fun provideWallpaperRepository(repository: WallpaperRepositoryImpl): WallpaperRepository = repository
|
||||
|
||||
@Provides
|
||||
fun provideSettingsRepository(repository: SettingsRepositoryImpl): SettingsRepository = repository
|
||||
}
|
||||